-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathtool.go
More file actions
307 lines (263 loc) · 7.65 KB
/
tool.go
File metadata and controls
307 lines (263 loc) · 7.65 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
package ai
import (
"context"
"encoding/json"
"fmt"
"reflect"
"slices"
"strings"
)
// Schema represents a JSON schema for tool input validation.
type Schema struct {
Type string `json:"type"`
Properties map[string]*Schema `json:"properties,omitempty"`
Required []string `json:"required,omitempty"`
Items *Schema `json:"items,omitempty"`
Description string `json:"description,omitempty"`
Enum []any `json:"enum,omitempty"`
Format string `json:"format,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
MinLength *int `json:"minLength,omitempty"`
MaxLength *int `json:"maxLength,omitempty"`
}
// ToolInfo represents tool metadata, matching the existing pattern.
type ToolInfo struct {
Name string
Description string
Parameters map[string]any
Required []string
}
// ToolCall represents a tool invocation, matching the existing pattern.
type ToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Input string `json:"input"`
}
// ToolResponse represents the response from a tool execution, matching the existing pattern.
type ToolResponse struct {
Type string `json:"type"`
Content string `json:"content"`
Metadata string `json:"metadata,omitempty"`
IsError bool `json:"is_error"`
}
// NewTextResponse creates a text response.
func NewTextResponse(content string) ToolResponse {
return ToolResponse{
Type: "text",
Content: content,
}
}
// NewTextErrorResponse creates an error response.
func NewTextErrorResponse(content string) ToolResponse {
return ToolResponse{
Type: "text",
Content: content,
IsError: true,
}
}
// WithResponseMetadata adds metadata to a response.
func WithResponseMetadata(response ToolResponse, metadata any) ToolResponse {
if metadata != nil {
metadataBytes, err := json.Marshal(metadata)
if err != nil {
return response
}
response.Metadata = string(metadataBytes)
}
return response
}
// AgentTool represents a tool that can be called by a language model.
// This matches the existing BaseTool interface pattern.
type AgentTool interface {
Info() ToolInfo
Run(ctx context.Context, params ToolCall) (ToolResponse, error)
}
// NewAgentTool creates a typed tool from a function with automatic schema generation.
// This is the recommended way to create tools.
func NewAgentTool[TInput any](
name string,
description string,
fn func(ctx context.Context, input TInput, call ToolCall) (ToolResponse, error),
) AgentTool {
var input TInput
schema := generateSchema(reflect.TypeOf(input))
return &funcToolWrapper[TInput]{
name: name,
description: description,
fn: fn,
schema: schema,
}
}
// funcToolWrapper wraps a function to implement the AgentTool interface.
type funcToolWrapper[TInput any] struct {
name string
description string
fn func(ctx context.Context, input TInput, call ToolCall) (ToolResponse, error)
schema Schema
}
func (w *funcToolWrapper[TInput]) Info() ToolInfo {
if w.schema.Required == nil {
w.schema.Required = []string{}
}
return ToolInfo{
Name: w.name,
Description: w.description,
Parameters: schemaToParameters(w.schema),
Required: w.schema.Required,
}
}
func (w *funcToolWrapper[TInput]) Run(ctx context.Context, params ToolCall) (ToolResponse, error) {
var input TInput
if err := json.Unmarshal([]byte(params.Input), &input); err != nil {
return NewTextErrorResponse(fmt.Sprintf("invalid parameters: %s", err)), nil
}
return w.fn(ctx, input, params)
}
// schemaToParameters converts a Schema to the parameters map format expected by ToolInfo.
func schemaToParameters(schema Schema) map[string]any {
if schema.Type != "object" || schema.Properties == nil {
return map[string]any{}
}
params := make(map[string]any)
for name, propSchema := range schema.Properties {
param := map[string]any{
"type": propSchema.Type,
}
if propSchema.Description != "" {
param["description"] = propSchema.Description
}
if len(propSchema.Enum) > 0 {
param["enum"] = propSchema.Enum
}
if propSchema.Format != "" {
param["format"] = propSchema.Format
}
if propSchema.Minimum != nil {
param["minimum"] = *propSchema.Minimum
}
if propSchema.Maximum != nil {
param["maximum"] = *propSchema.Maximum
}
if propSchema.MinLength != nil {
param["minLength"] = *propSchema.MinLength
}
if propSchema.MaxLength != nil {
param["maxLength"] = *propSchema.MaxLength
}
if propSchema.Items != nil {
param["items"] = schemaToParameters(*propSchema.Items)
}
params[name] = param
}
return params
}
// generateSchema automatically generates a JSON schema from a Go type.
func generateSchema(t reflect.Type) Schema {
return generateSchemaRecursive(t, make(map[reflect.Type]bool))
}
func generateSchemaRecursive(t reflect.Type, visited map[reflect.Type]bool) Schema {
// Handle pointers
if t.Kind() == reflect.Pointer {
t = t.Elem()
}
// Prevent infinite recursion
if visited[t] {
return Schema{Type: "object"}
}
visited[t] = true
defer delete(visited, t)
switch t.Kind() {
case reflect.String:
return Schema{Type: "string"}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return Schema{Type: "integer"}
case reflect.Float32, reflect.Float64:
return Schema{Type: "number"}
case reflect.Bool:
return Schema{Type: "boolean"}
case reflect.Slice, reflect.Array:
itemSchema := generateSchemaRecursive(t.Elem(), visited)
return Schema{
Type: "array",
Items: &itemSchema,
}
case reflect.Map:
if t.Key().Kind() == reflect.String {
valueSchema := generateSchemaRecursive(t.Elem(), visited)
return Schema{
Type: "object",
Properties: map[string]*Schema{
"*": &valueSchema,
},
}
}
return Schema{Type: "object"}
case reflect.Struct:
schema := Schema{
Type: "object",
Properties: make(map[string]*Schema),
}
for i := range t.NumField() {
field := t.Field(i)
// Skip unexported fields
if !field.IsExported() {
continue
}
jsonTag := field.Tag.Get("json")
if jsonTag == "-" {
continue
}
fieldName := field.Name
required := true
// Parse JSON tag
if jsonTag != "" {
parts := strings.Split(jsonTag, ",")
if parts[0] != "" {
fieldName = parts[0]
}
// Check for omitempty
if slices.Contains(parts[1:], "omitempty") {
required = false
}
} else {
// Convert field name to snake_case for JSON
fieldName = toSnakeCase(fieldName)
}
fieldSchema := generateSchemaRecursive(field.Type, visited)
// Add description from struct tag if available
if desc := field.Tag.Get("description"); desc != "" {
fieldSchema.Description = desc
}
// Add enum values from struct tag if available
if enumTag := field.Tag.Get("enum"); enumTag != "" {
enumValues := strings.Split(enumTag, ",")
fieldSchema.Enum = make([]any, len(enumValues))
for i, v := range enumValues {
fieldSchema.Enum[i] = strings.TrimSpace(v)
}
}
schema.Properties[fieldName] = &fieldSchema
if required {
schema.Required = append(schema.Required, fieldName)
}
}
return schema
case reflect.Interface:
return Schema{Type: "object"}
default:
return Schema{Type: "object"}
}
}
// toSnakeCase converts PascalCase to snake_case.
func toSnakeCase(s string) string {
var result strings.Builder
for i, r := range s {
if i > 0 && r >= 'A' && r <= 'Z' {
result.WriteByte('_')
}
result.WriteRune(r)
}
return strings.ToLower(result.String())
}