-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.go
More file actions
332 lines (291 loc) · 10.5 KB
/
tools.go
File metadata and controls
332 lines (291 loc) · 10.5 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package ai
import (
"encoding/json"
"fmt"
)
// ═══════════════════════════════════════════════════════════════════════════
// Tool/Function Calling
// ═══════════════════════════════════════════════════════════════════════════
// Tool represents a function the model can call.
// It follows the OpenAI tool calling schema.
type Tool struct {
Type string `json:"type"` // "function" is currently the only supported type
Function ToolFunction `json:"function"` // The function definition
}
// ToolFunction describes the function schema, including name, description, and parameters.
type ToolFunction struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters map[string]any `json:"parameters,omitempty"` // JSON Schema for parameters
}
// ToolCall represents a specific invocation of a tool by the model.
type ToolCall struct {
ID string `json:"id"`
Type string `json:"type"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"` // JSON string arguments
} `json:"function"`
}
// ToolResult is the output returned to the model after executing a tool.
type ToolResult struct {
ToolCallID string `json:"tool_call_id"`
Content string `json:"content"`
}
// ToolHandler is a callback function that handles tool execution.
// It takes a map of arguments and returns a string result or error.
type ToolHandler func(args map[string]any) (string, error)
// ToolDef simplifies defining tools by bundling the schema and handler together.
type ToolDef struct {
Name string
Description string
Parameters map[string]any
Handler ToolHandler
}
// ═══════════════════════════════════════════════════════════════════════════
// Builder Methods for Tools
// ═══════════════════════════════════════════════════════════════════════════
// Tool adds a function tool to the request configuration.
// It registers the tool definition but not a handler. Use OnToolCall to register a handler separately.
func (b *Builder) Tool(name, description string, params map[string]any) *Builder {
b.tools = append(b.tools, Tool{
Type: "function",
Function: ToolFunction{
Name: name,
Description: description,
Parameters: params,
},
})
return b
}
// ToolDef adds a tool using a ToolDef struct.
// This registers both the tool definition and the execution handler.
func (b *Builder) ToolDef(def ToolDef) *Builder {
b.tools = append(b.tools, Tool{
Type: "function",
Function: ToolFunction{
Name: def.Name,
Description: def.Description,
Parameters: def.Parameters,
},
})
if b.toolHandlers == nil {
b.toolHandlers = make(map[string]ToolHandler)
}
b.toolHandlers[def.Name] = def.Handler
return b
}
// Tools adds multiple tool definitions at once.
func (b *Builder) Tools(tools ...Tool) *Builder {
b.tools = append(b.tools, tools...)
return b
}
// OnToolCall registers a handler function for a specific tool name.
// This is used when the tool was defined without a handler (e.g., via Tool() or raw Tool struct).
func (b *Builder) OnToolCall(name string, handler ToolHandler) *Builder {
if b.toolHandlers == nil {
b.toolHandlers = make(map[string]ToolHandler)
}
b.toolHandlers[name] = handler
return b
}
// ═══════════════════════════════════════════════════════════════════════════
// Tool Schema Helpers - DX-friendly parameter builders
// ═══════════════════════════════════════════════════════════════════════════
// Params creates a new ParamBuilder for constructing JSON Schemas.
func Params() *ParamBuilder {
return &ParamBuilder{
schema: map[string]any{
"type": "object",
"properties": map[string]any{},
"required": []string{},
},
}
}
// ParamBuilder helps construct JSON Schema objects for tool parameters.
// It provides a fluent API for defining strings, numbers, booleans, and arrays.
type ParamBuilder struct {
schema map[string]any
}
// String adds a string parameter to the schema.
func (p *ParamBuilder) String(name, desc string, required bool) *ParamBuilder {
props := p.schema["properties"].(map[string]any)
props[name] = map[string]any{
"type": "string",
"description": desc,
}
if required {
req := p.schema["required"].([]string)
p.schema["required"] = append(req, name)
}
return p
}
// Number adds a number (float) parameter to the schema.
func (p *ParamBuilder) Number(name, desc string, required bool) *ParamBuilder {
props := p.schema["properties"].(map[string]any)
props[name] = map[string]any{
"type": "number",
"description": desc,
}
if required {
req := p.schema["required"].([]string)
p.schema["required"] = append(req, name)
}
return p
}
// Int adds an integer parameter to the schema.
func (p *ParamBuilder) Int(name, desc string, required bool) *ParamBuilder {
props := p.schema["properties"].(map[string]any)
props[name] = map[string]any{
"type": "integer",
"description": desc,
}
if required {
req := p.schema["required"].([]string)
p.schema["required"] = append(req, name)
}
return p
}
// Bool adds a boolean parameter to the schema.
func (p *ParamBuilder) Bool(name, desc string, required bool) *ParamBuilder {
props := p.schema["properties"].(map[string]any)
props[name] = map[string]any{
"type": "boolean",
"description": desc,
}
if required {
req := p.schema["required"].([]string)
p.schema["required"] = append(req, name)
}
return p
}
// Enum adds a string parameter restricted to a set of values.
func (p *ParamBuilder) Enum(name, desc string, values []string, required bool) *ParamBuilder {
props := p.schema["properties"].(map[string]any)
props[name] = map[string]any{
"type": "string",
"description": desc,
"enum": values,
}
if required {
req := p.schema["required"].([]string)
p.schema["required"] = append(req, name)
}
return p
}
// Array adds an array parameter with a specific item type.
func (p *ParamBuilder) Array(name, desc, itemType string, required bool) *ParamBuilder {
props := p.schema["properties"].(map[string]any)
props[name] = map[string]any{
"type": "array",
"description": desc,
"items": map[string]any{"type": itemType},
}
if required {
req := p.schema["required"].([]string)
p.schema["required"] = append(req, name)
}
return p
}
// Build finalizes and returns the map representing the JSON Schema.
func (p *ParamBuilder) Build() map[string]any {
return p.schema
}
// ═══════════════════════════════════════════════════════════════════════════
// Tool Response Handling
// ═══════════════════════════════════════════════════════════════════════════
// ToolResponse encapsulates the response from a model that may contain tool calls.
type ToolResponse struct {
Content string // Text response (may be empty if tool calls are present)
ToolCalls []ToolCall // Tool calls the model wants to make
Model Model
Tokens int
}
// HasToolCalls reports whether the response contains any tool calls.
func (r *ToolResponse) HasToolCalls() bool {
return len(r.ToolCalls) > 0
}
// SendWithTools executes the request and returns a ToolResponse.
// This is used for manual handling of tool calls. For automatic execution, use RunTools.
func (b *Builder) SendWithTools() (*ToolResponse, error) {
msgs := b.buildMessages()
content, resp, toolCalls, err := SendWithTools(b.model, msgs, b.tools, SendOptions{
Temperature: b.temperature,
Thinking: b.thinking,
})
if err != nil {
return nil, err
}
result := &ToolResponse{
Content: content,
ToolCalls: toolCalls,
Model: b.model,
}
if resp != nil {
result.Tokens = resp.Usage.TotalTokens
}
return result, nil
}
// RunTools executes the request in an "agentic" loop.
// It automatically executes tool calls and feeds the results back to the model.
// It continues until the model provides a final text response or maxIterations is reached.
func (b *Builder) RunTools(maxIterations int) (string, error) {
if maxIterations <= 0 {
maxIterations = 10 // sensible default
}
for i := 0; i < maxIterations; i++ {
resp, err := b.SendWithTools()
if err != nil {
return "", err
}
// No tool calls = we're done
if !resp.HasToolCalls() {
if Pretty {
printPrettyResponse(b.model, resp.Content)
}
return resp.Content, nil
}
// Execute each tool call
for _, tc := range resp.ToolCalls {
handler, ok := b.toolHandlers[tc.Function.Name]
if !ok {
return "", fmt.Errorf("no handler for tool: %s", tc.Function.Name)
}
// Parse arguments
var args map[string]any
if err := json.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil {
return "", fmt.Errorf("invalid tool arguments: %w", err)
}
if Debug {
fmt.Printf("%s Calling tool: %s(%v)\n", colorYellow("🔧"), tc.Function.Name, args)
}
// Execute handler
result, err := handler(args)
if err != nil {
result = fmt.Sprintf("Error: %v", err)
}
if Debug {
fmt.Printf("%s Tool result: %s\n", colorGreen("✓"), truncate(result, 100))
}
// Add tool result to conversation
b.messages = append(b.messages, Message{
Role: "assistant",
Content: "",
ToolCalls: resp.ToolCalls,
ToolCallID: "",
})
b.messages = append(b.messages, Message{
Role: "tool",
Content: result,
ToolCallID: tc.ID,
})
}
}
return "", fmt.Errorf("max tool iterations (%d) reached", maxIterations)
}
func truncate(s string, max int) string {
if len(s) <= max {
return s
}
return s[:max] + "..."
}