-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
181 lines (153 loc) · 5.39 KB
/
Copy pathapp.go
File metadata and controls
181 lines (153 loc) · 5.39 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package gopilot
import (
"encoding/json"
"fmt"
"log"
"strings"
"github.com/SadikSunbul/gopilot/clients"
"github.com/SadikSunbul/gopilot/pkg/generator"
)
type Gopilot struct {
llm LLMProvider
registry *Registry
}
func NewGopilot(llm LLMProvider) (*Gopilot, error) {
if llm == nil {
return nil, fmt.Errorf("llm is required")
}
return &Gopilot{
llm: llm,
registry: NewRegistry(),
}, nil
}
// FunctionRegister registers a new function
func (g *Gopilot) FunctionRegister(fn FunctionWrapper) error {
return g.registry.Register(fn)
}
// FunctionExecute executes a registered function
func (g *Gopilot) FunctionExecute(name string, params interface{}) (interface{}, error) {
// convert to map[string]interface{} type
var paramMap map[string]interface{}
switch p := params.(type) {
case map[string]interface{}:
paramMap = p
default:
// If params are not already map, let's try JSON conversion
data, err := json.Marshal(params)
if err != nil {
return nil, fmt.Errorf("failed to marshal params: %w", err)
}
if err := json.Unmarshal(data, ¶mMap); err != nil {
return nil, fmt.Errorf("failed to convert params to map: %w", err)
}
}
return g.registry.ExecuteFunction(name, paramMap)
}
// FunctionGet retrieves a registered function
func (g *Gopilot) FunctionGet(name string) (FunctionWrapper, error) {
return Get[interface{}, interface{}](g.registry, name)
}
// FunctionsList returns all registered functions
func (g *Gopilot) FunctionsList() []FunctionWrapper {
return g.registry.List()
}
// formatParameterSchema formats the parameter schema for system prompt
func formatParameterSchema(name string, param generator.ParameterSchema, indentLevel int) string {
indent := strings.Repeat("\t", indentLevel)
requiredMark := ""
if param.Required {
requiredMark = " [required]"
}
description := param.Description
if description == "" {
description = name
}
paramStr := fmt.Sprintf("%s%s: %s%s (%s)", indent, name, param.Type, requiredMark, description)
if param.Type == "interface" && param.Properties != nil {
paramStr += " {\n"
for propName, prop := range param.Properties {
paramStr += formatParameterSchema(propName, prop, indentLevel+1)
}
paramStr += fmt.Sprintf("%s}\n", indent)
} else {
paramStr += "\n"
}
return paramStr
}
// SetSystemPrompt configures the system prompt
func (g *Gopilot) SetSystemPrompt(importantRules []string, unsupportedFunction ...FunctionWrapper) {
// Register unsupported function if not already registered
if len(unsupportedFunction) > 0 {
if err := g.FunctionRegister(unsupportedFunction[0]); err != nil {
log.Fatal("unsupported function register error:", err.Error())
}
} else {
if err := g.FunctionRegister(UnsupportedFunction()); err != nil {
log.Fatal("default unsupported function register error:", err.Error())
}
}
agentList := g.registry.List()
// Build function descriptions
var functionDescriptions strings.Builder
for _, fn := range agentList {
functionDescriptions.WriteString(fmt.Sprintf("Function: %s\n", fn.GetName()))
functionDescriptions.WriteString(fmt.Sprintf("Description: %s\n", fn.GetDescription()))
functionDescriptions.WriteString("Parameters:\n")
for name, param := range fn.GetParameters() {
functionDescriptions.WriteString(formatParameterSchema(name, param, 1))
}
functionDescriptions.WriteString("\n")
}
// Build rules
var rules strings.Builder
if importantRules == nil || len(importantRules) == 0 {
rules.WriteString(`
1. Analyze the user's intent carefully before selecting a function
2. Only select a function if it clearly matches the user's request
3. Validate all required parameters before execution
4. If unsure about any parameter, use the "unsupported" function
5. Consider the context and any previous interactions
`)
} else {
for i, rule := range importantRules {
rules.WriteString(fmt.Sprintf("%d. %s\n", i+1, rule))
}
}
// Build final prompt
prompt := fmt.Sprintf(systemPrompt, rules.String(), functionDescriptions.String())
g.llm.SetSystemPrompt(prompt)
}
// Generate generates a response from the LLM
func (g *Gopilot) Generate(input string) (*clients.LLMResponse, error) {
return g.llm.Generate(input)
}
// GenerateAndExecute generates a response and executes the corresponding function
func (g *Gopilot) GenerateAndExecute(input string) (interface{}, error) {
response, err := g.Generate(input)
if err != nil {
return nil, err
}
return g.FunctionExecute(response.Agent, response.Parameters)
}
// UnsupportedParams represents parameters for unsupported function
type UnsupportedParams struct {
Message string `json:"message" description:"Contains a simple explanation of the error." required:"true"`
}
// UnsupportedResponse represents the response from unsupported function
type UnsupportedResponse struct {
Message string `json:"message"`
}
// UnsupportedFunction creates a new unsupported function handler
func UnsupportedFunction() *Function[UnsupportedParams, UnsupportedResponse] {
fn := &Function[UnsupportedParams, UnsupportedResponse]{
Name: "unsupported",
Description: "If the user's request doesn't match any of these agents, use the \"unsupported\" agent in your response.",
Parameters: generator.GenerateParameterSchema(UnsupportedParams{}),
Execute: func(params UnsupportedParams) (UnsupportedResponse, error) {
return UnsupportedResponse{
Message: "you made an unsupported request: " + params.Message,
}, nil
},
}
return fn
}