-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuser_request.go
62 lines (48 loc) · 1.47 KB
/
user_request.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package typechat
import (
"fmt"
"reflect"
"strings"
)
const (
userRequestSchemaInstructions = `You are a service that translates user requests into JSON objects of type %s
according to the following Go definitions:`
userRequestPromptInstructions = `The following is the user request translated into a JSON object with 2 spaces of
indentation and no properties with the value undefined:`
)
type userRequest[T any] struct {
input string
messages []Message
}
func newUserRequest[T any](i string) *userRequest[T] {
return &userRequest[T]{input: i}
}
func (b *userRequest[T]) prompt() ([]Message, error) {
if b.messages != nil {
return b.messages, nil
}
var schema T
name, def, err := structDef(reflect.TypeOf(schema))
if err != nil {
return nil, err
}
b.messages = append(b.messages, newSystemMessage(b.schema(name, def)))
b.messages = append(b.messages, newUserMessage(b.userMessage()))
b.messages = append(b.messages, newSystemMessage(b.instructions()))
return b.messages, nil
}
func (b *userRequest[T]) userMessage() string {
var sb strings.Builder
sb.WriteString(newline("The following is a user request:"))
sb.WriteString(newline(b.input))
return sb.String()
}
func (b *userRequest[T]) instructions() string {
return userRequestPromptInstructions
}
func (b *userRequest[T]) schema(name, def string) string {
var sb strings.Builder
sb.WriteString(newline(fmt.Sprintf(userRequestSchemaInstructions, name)))
sb.WriteString(newline(def))
return sb.String()
}