第 3 章
工具:定义、校验、执行
上一章的模型已经会说:请帮我执行 read,参数是 {"path":"package.json"}。程序照着去读文件,不就完了吗?
没这么简单。参数是模型写的,它可能漏掉 path,可能把 path 写成数字 1,还可能只写了半截 {"path":。参数没毛病,文件也可能不存在;工具的代码自己也可能崩。这些情况哪一种都不该让 agent 停下来。办法是把每一种失败都写成一条工具结果交还给模型,让它看了自己改。

这一章做完,你手里有一个 read 工具,和一个函数 RunToolCall:交给它任何一次工具调用,它都交回一条结果,不崩,也不返回 Go 的 error。代码已经写好了,先跑起来。
cd chapters/03-tools
go run ./demo
调用 id=call_1 name=read arguments={"path":"package.json"}
结果 tool=read is_error=false
内容 "{\"name\":\"demo\",\"version\":\"1.0.0\"}\n"
调用 id=call_2 name=read arguments={}
结果 tool=read is_error=true
内容 "Invalid arguments for tool read: $: missing required property \"path\""
一起读这 7 行
这里还没有模型。你屏幕上的两次调用是我们替模型写好的,demo 把它们交给 RunToolCall,再把交回来的结果打印出来。demo/main.go:
toolset := []agent.Tool{tools.NewRead(dir)}
calls := []ai.ToolCall{
{ID: "call_1", Name: "read", Arguments: []byte(`{"path":"package.json"}`)},
{ID: "call_2", Name: "read", Arguments: []byte(`{}`)},
}
dir 是 demo 刚建的一个临时目录,里面只有一个文件 package.json,内容是 {"name":"demo","version":"1.0.0"}。ai.ToolCall 是第 1 章的类型,三个字段是编号、工具名和参数。toolset 是这次能用的工具,只有 read 一个。
第一次:读到了
你屏幕上每次调用占三行。「调用」那行是交进去的东西,「结果」和「内容」两行是交回来的东西。call_1 的参数是 {"path":"package.json"},交回来 is_error=false,内容就是那个文件。外面的引号和 \"、\n 是打印时加的,实际内容就是那一行 JSON 加一个换行。
交回来的是一条工具结果消息 ToolResultMessage。第 1 章把它定义在 ai/message.go 里,可一直没有代码造出它,现在有了:
type ToolResultMessage struct {
ToolCallID string
ToolName string
Text string
IsError bool
}
Text 是「内容」那一行,IsError 是 is_error。ToolCallID 屏幕上没打印,它填的是 call_1,送回模型的时候,模型靠它知道这是哪一次调用的结果。
第二次:参数里没有 path
call_2 的参数是 {},什么都没写。交回来的 is_error=true,内容是一句英文,拆开读:
Invalid arguments for tool read:read这个工具收到的参数不合格。$:出问题的位置。$指整个参数,也就是{}本身。missing required property "path":缺了必填的path。
这句话是写给模型看的。下一章的 agent 循环会把它连同编号 call_2 送回模型,模型读到「缺了 path」,下一轮就能补上再调一次。
再看一眼你终端里的结局:第二次失败了,程序照样打印完,正常退出。失败也是一条结果,这就是这一章要守的规矩。下面我们看看不守它会怎样。
动手改三次
下面的试验都在 chapters/03-tools 里改代码。每个做完,用 git checkout <文件> 把改过的文件改回去,再做下一个。
试验 1:不检查,直接执行
RunToolCall 先检查参数,再交给工具执行。不检查行不行?我们绕过它,直接调用 read 的执行函数,参数还是 {}。在 demo/main.go 的 for 循环后面加两行:
printResult(agent.RunToolCall(context.Background(), toolset, call))
}
+ text, err := toolset[0].Execute(context.Background(), []byte(`{}`))
+ fmt.Printf("\n直接执行 text=%q err=%v\n", text, err)
return 0
运行 go run ./demo,你会看到前 7 行不变,后面多了两行:
直接执行 text="" err=read .../afz-demo-449710726: is a directory
路径我们截短了。临时目录的名字每次随机,你那里的路径会不一样。
read 去读了一个目录。哪来的目录?参数里没有 path,Go 解析 JSON 时不会抱怨少了字段,没出现的字段保持零值,字符串的零值是空串 ""。空串拼在临时目录后面,还是临时目录本身,于是读了它,得到 is a directory。

模型要是收到这句话,会以为自己给的路径指向了一个目录,接下来多半去换路径。它不会知道真正的毛病是忘了写 path。而 RunToolCall 交回的那句 missing required property "path" 正好说中了。所以执行之前要先拿参数去对一遍格式。
改回去:git checkout demo/main.go。
试验 2:再写错四次
模型还能怎么写错?我们把开头那几种都试一遍,外加一次文件不存在。在 demo/main.go 的 calls 里加四行:
{ID: "call_2", Name: "read", Arguments: []byte(`{}`)},
+ {ID: "call_3", Name: "read", Arguments: []byte(`{"path":1}`)},
+ {ID: "call_4", Name: "read", Arguments: []byte(`{"path":`)},
+ {ID: "call_5", Name: "write", Arguments: []byte(`{"path":"a.txt"}`)},
+ {ID: "call_6", Name: "read", Arguments: []byte(`{"path":"notes.txt"}`)},
}
运行,你屏幕上前 7 行不变,后面是:
调用 id=call_3 name=read arguments={"path":1}
结果 tool=read is_error=true
内容 "Invalid arguments for tool read: $.path: expected string, got number"
调用 id=call_4 name=read arguments={"path":
结果 tool=read is_error=true
内容 "Invalid arguments for tool read: $: arguments are not valid JSON"
调用 id=call_5 name=write arguments={"path":"a.txt"}
结果 tool=write is_error=true
内容 "Tool write not found"
调用 id=call_6 name=read arguments={"path":"notes.txt"}
结果 tool=read is_error=true
内容 "open .../afz-demo-1040760951/notes.txt: no such file or directory"
逐个看:
call_3:位置从$变成了$.path,指到了参数里的path字段。它要的是字符串(string),来的是数字(number)。call_4:半截的{"path":,连 JSON 都不是。第 1 章见过它。call_5:模型想用一个根本没有的工具write。call_6:参数完全合格,文件却不存在。这句话是read自己报的,原样交了回来。
六次调用五次失败,程序一次也没停,每次都交回一条模型读得懂的结果。
改回去。
试验 3:工具自己崩了
前面的失败都是「好好地失败」:要么参数不合格,要么工具返回了一个 error。可工具的代码也会有 bug。我们写一个一调就崩的工具 boom,放在两次 read 中间。demo/main.go:
- toolset := []agent.Tool{tools.NewRead(dir)}
+ toolset := []agent.Tool{tools.NewRead(dir), agent.NewTool("boom", "Always crashes.", []byte(`{"type":"object"}`),
+ func(ctx context.Context, args struct{}) (string, error) {
+ var lines []string
+ return lines[0], nil
+ })}
calls := []ai.ToolCall{
{ID: "call_1", Name: "read", Arguments: []byte(`{"path":"package.json"}`)},
- {ID: "call_2", Name: "read", Arguments: []byte(`{}`)},
+ {ID: "call_2", Name: "boom", Arguments: []byte(`{}`)},
+ {ID: "call_3", Name: "read", Arguments: []byte(`{}`)},
}
lines 是一个空的切片,lines[0] 去取第一个元素,下标越界。agent.NewTool 是怎么回事,写代码时再讲。运行:
调用 id=call_1 name=read arguments={"path":"package.json"}
结果 tool=read is_error=false
内容 "{\"name\":\"demo\",\"version\":\"1.0.0\"}\n"
调用 id=call_2 name=boom arguments={}
结果 tool=boom is_error=true
内容 "Tool boom panicked: runtime error: index out of range [0] with length 0"
调用 id=call_3 name=read arguments={}
结果 tool=read is_error=true
内容 "Invalid arguments for tool read: $: missing required property \"path\""

看你屏幕上的 call_2:boom 崩了,可崩掉的只是它自己这一次调用:交回一条 Tool boom panicked: ... 的结果,后面的 call_3 照常执行。下标越界这种错误,Go 叫 panic(运行时的严重错误)。没人接住的 panic 会让整个程序退出。这里有人接住了,接住它的代码在 agent/tool.go 里。我们把它删掉,看看没人接是什么样:
- // A panicking tool must not take the whole agent down; the model gets to see the failure instead.
- defer func() {
- if r := recover(); r != nil {
- result = ai.ToolResultMessage{
- ToolCallID: call.ID, ToolName: call.Name, IsError: true,
- Text: fmt.Sprintf("Tool %s panicked: %v", call.Name, r),
- }
- }
- }()
-
text, err := tool.Execute(ctx, call.Arguments)
再运行:
调用 id=call_1 name=read arguments={"path":"package.json"}
结果 tool=read is_error=false
内容 "{\"name\":\"demo\",\"version\":\"1.0.0\"}\n"
调用 id=call_2 name=boom arguments={}
panic: runtime error: index out of range [0] with length 0
下面还有一段调用栈,最后一行是 exit status 2,这里没有贴。整个程序没了,call_3 根本没机会跑。
这就是「抛异常」和「交回一条结果」的差别。换成真的 agent,一个工具里的一个 bug 会带走整个会话,用户这一轮的进度跟着一起没了;模型也看不到出了什么事,没法换个办法接着干。
两个文件都改回去:git checkout demo/main.go agent/tool.go。三个试验做完,RunToolCall 要处理的事你都见过了。
现在把它写出来
起点是第 2 章的目录:拷一份过来,ai/ 和 replay/ 一行不动。下面按我们自己写的顺序来:先写检查参数的校验器,再写工具的类型,然后是 read,最后把它们串成 RunToolCall。每块代码前面写了它在哪个文件里。
第 1 步:校验器(schema/schema.go)
模型怎么知道 read 要一个字符串 path?工具会附上一段参数说明,格式叫 JSON Schema,它本身也是一段 JSON。read 的这段是:
{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}
读出来是:参数是一个对象("type":"object");里面的 path 是字符串;path 必须有。模型照着它写参数,我们的校验器拿着它检查模型写的参数。JSON Schema 的关键字有几十个,校验器只认五个:type、properties、required、enum(只能取这几个值之一)、items(数组里每个元素的格式)。其余的一律不管,旁白 2 会说这意味着什么。
先定检查不过时交回什么:
// Error is the first violation found.
type Error struct {
Path string // JSONPath-like: "$", "$.path", "$.tags[1]"
Message string
}
func (e *Error) Error() string { return e.Path + ": " + e.Message }
Path 是位置,Message 是哪里不对,中间用冒号连起来,就是屏幕上的 $: missing required property "path"。只报第一处,找到一处就停。
五个关键字装进一个结构体:
// node holds the supported keywords. Unknown keywords are dropped by the decoder.
type node struct {
Type string `json:"type"`
Properties map[string]json.RawMessage `json:"properties"`
Required []string `json:"required"`
Enum []any `json:"enum"`
Items json.RawMessage `json:"items"`
}
字段后面反引号里的 json:"type" 是标签(tag),告诉 Go 解析 JSON 时这个字段对应哪个键。没有对应字段的键,解析时直接丢掉,「只认五个」就是这么来的。Properties 和 Items 里装的还是 JSON Schema,先原样留着,用到时再解析。
入口:
func Validate(schema, value json.RawMessage) error {
if !json.Valid(value) {
return &Error{Path: "$", Message: "arguments are not valid JSON"}
}
decoded, err := decodeNumbers(value)
if err != nil {
return err
}
return validate(schema, decoded, "$")
}
第一个 if 就是试验 2 里 call_4 的那句 arguments are not valid JSON。过了这一关,把参数解析成 Go 的值(decodeNumbers 在数字上有个讲究,见旁白 1),交给 validate,位置从 $ 开始。
validate 先解析这一层的 schema,查类型和取值:
var s node
if err := json.Unmarshal(schemaRaw, &s); err != nil {
return fmt.Errorf("schema at %s is not a valid schema object: %w", path, err)
}
if s.Type != "" && !matchesType(s.Type, value) {
return &Error{Path: path, Message: fmt.Sprintf("expected %s, got %s", s.Type, typeName(value))}
}
if s.Enum != nil && !inEnum(s.Enum, value) {
return &Error{Path: path, Message: "value is not one of the allowed values"}
}
typeName 把一个 Go 值说成 JSON 的类型名,call_3 那句 got number 就是它说的。留意第一个 return:schema 自己坏了的时候,返回的是普通的 error,不是 *Error。为什么要分开,第 4 步就用上了。
接着按值的样子往下走。值是对象,先查必填:
switch v := value.(type) {
case map[string]any:
for _, name := range s.Required {
if _, ok := v[name]; !ok {
return &Error{Path: path, Message: fmt.Sprintf("missing required property %q", name)}
}
}
这就是 call_2 那句话的出处。再一个一个查对象里的属性:
for _, name := range names {
if child, ok := v[name]; ok {
if err := validate(s.Properties[name], child, path+"."+name); err != nil {
return err
}
}
}
看第三行:validate 调用了它自己,拿 path 那一小段 schema 去查 path 的值,位置接上 .path。$.path 就是这样来的。names 是属性名排好序的列表,上面几行准备的。Go 遍历 map 的顺序每次随机,排了序,同一份参数错了两处时,报的总是同一处。
值是数组时是一个套路,每个元素拿 items 去查,位置接上 [下标]:
case []any:
if len(s.Items) > 0 {
for i, item := range v {
if err := validate(s.Items, item, path+"["+strconv.Itoa(i)+"]"); err != nil {
return err
}
}
}
read 的参数里没有数组,也没有套着的对象。这两种走法 schema/schema_test.go 里有,用的是一份字段更多的 schema:
{"array item", `{"path":"a","tags":["x",1]}`, `$.tags[1]: expected string, got number`},
{"nested required", `{"path":"a","opts":{}}`, `$.opts: missing required property "deep"`},
拿第一条来说,validate 从 $ 一层一层走到 $.tags[1]:
第二个元素 1 不是字符串,报在 $.tags[1];opts 里缺了 deep,报在 $.opts。跑一下:
go test ./schema
ok afz/schema 0.509s
过了。最后的耗时你那里会不一样。剩下的 typeName、matchesType、inEnum、equal 都是对照类型、比较取值的小函数,照着文件抄就行。
第 2 步:工具长什么样(agent/tool.go)
一个工具有四样东西:
// Tool is something the model can call.
type Tool struct {
Name string
Description string
Parameters json.RawMessage // JSON Schema for the arguments object
Execute func(ctx context.Context, args json.RawMessage) (string, error)
}
前三样是说给模型听的:名字 read,一句描述 Read the contents of a file.,加上第 1 步那段 JSON Schema。第四样 Execute 是真正干活的函数,收到原样的参数字节,交回一段文字或者一个 error。ctx 是第 1 章喊停用的那个。
同一个文件里的 Declarations 把前三样抄进第 1 章的 ai.ToolDeclaration,放进请求的 Tools,第 2 章的 OpenAI 客户端就会把它们发给模型。
Execute 收的是字节,每个工具都得先自己解析一遍,挺烦。所以再写一个帮手,让写工具的人只管写一个收「解析好的参数」的函数:
func NewTool[A any](name, description string, parameters json.RawMessage,
run func(ctx context.Context, args A) (string, error)) Tool {
return Tool{
Name: name,
Description: description,
Parameters: parameters,
Execute: func(ctx context.Context, raw json.RawMessage) (string, error) {
var args A
if err := json.Unmarshal(raw, &args); err != nil {
return "", fmt.Errorf("decode arguments of tool %s: %w", name, err)
}
return run(ctx, args)
},
}
}
函数名后面的 [A any] 是 Go 的泛型:A 代表一个类型,调用的时候才定下来是哪个。调用时不用写出来,Go 会从 run 的参数类型推出来。Execute 里把字节解析进一个 A,再交给 run。run 拿到的已经是结构体了。试验 3 的 boom 用的也是它,A 是空结构体 struct{}。
解析要是失败,比如 schema 说 path 是字符串,结构体里却写成了 int,交回的 error 以 decode arguments of tool 开头。可是写错还有不报错的写法,这是个试验。把 read 的结构体标签改个名,tools/read.go:
type readArgs struct {
- Path string `json:"path"`
+ Path string `json:"file"`
}
运行:
调用 id=call_1 name=read arguments={"path":"package.json"}
结果 tool=read is_error=true
内容 "read .../afz-demo-3695848795: is a directory"
调用 id=call_2 name=read arguments={}
结果 tool=read is_error=true
内容 "Invalid arguments for tool read: $: missing required property \"path\""
你会发现 call_1 原本是成功的,现在又读到了目录,和试验 1 一模一样。参数 {"path":"package.json"} 对得上 schema,检查放行了;可结构体要的键是 file,Go 解析时把 path 丢掉,Path 留成空串。schema 和结构体是写工具的人分开写的两样东西,没有谁去核对它们是否一致。现在知道这一点就够了,pi 怎么避开它,见「对照 pi」。

改回去:git checkout tools/read.go。
第 3 步:read 工具(tools/read.go)
参数只有一个字段:
type readArgs struct {
Path string `json:"path"`
}
NewRead(root) 用 NewTool 造出 read,名字、描述、schema 就是上面见过的那三样。干活的函数是这样:
func(ctx context.Context, args readArgs) (string, error) {
path := args.Path
if !filepath.IsAbs(path) {
path = filepath.Join(root, path)
}
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
return string(data), nil
})
相对路径拼在 root 后面,demo 里 root 是那个临时目录,所以 package.json 读到的是临时目录里的文件。读失败就把 os.ReadFile 的 error 原样返回,这是 call_6 那句 no such file or directory。
read 不管路径跑到 root 外面去:../outside.txt 照样能读,tools/read_test.go 专门有一条测试钉住这一点。把文件工具限制在工作目录里是第 10 章的事。
第 4 步:把一次调用跑完(agent/tool.go)
最后是 RunToolCall。先看它的样子:
// RunToolCall validates and executes one call. Every failure comes back as an error result.
func RunToolCall(ctx context.Context, tools []Tool, call ai.ToolCall) (result ai.ToolResultMessage) {
result = ai.ToolResultMessage{ToolCallID: call.ID, ToolName: call.Name, IsError: true}
返回值只有一条 ToolResultMessage,没有 error。调用方拿到什么都一样处理:放进对话,送回模型。第一行先把结果填成「失败」,编号和工具名照抄调用的。下面每一道关卡没过,只要填上 Text 就能返回;只有走到最后成功了,才把 IsError 改成 false。
头两道关卡:
if ctx.Err() != nil {
result.Text = "Operation aborted"
return result
}
tool, ok := findTool(tools, call.Name)
if !ok {
result.Text = fmt.Sprintf("Tool %s not found", call.Name)
return result
}
第二道是试验 2 的 Tool write not found。第一道还没见过:用户已经喊了停,就不再开始执行新的工具,但仍然交回一条结果。试一下,在 demo/main.go 里先喊停,再跑两次调用:
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
for i, call := range calls {
@@
- printResult(agent.RunToolCall(context.Background(), toolset, call))
+ printResult(agent.RunToolCall(ctx, toolset, call))
运行:
调用 id=call_1 name=read arguments={"path":"package.json"}
结果 tool=read is_error=true
内容 "Operation aborted"
调用 id=call_2 name=read arguments={}
结果 tool=read is_error=true
内容 "Operation aborted"
你屏幕上两次都没有执行,各自交回一条 Operation aborted。为什么被喊停了还要交结果?模型提过的每一次调用,都得有一条结果对上它的编号,对话才是完整的。改回去。
第三道是检查参数:
if err := schema.Validate(tool.Parameters, call.Arguments); err != nil {
var violation *schema.Error
if errors.As(err, &violation) {
result.Text = fmt.Sprintf("Invalid arguments for tool %s: %s", call.Name, err)
} else {
// The tool author's schema is broken; do not blame the model's arguments.
result.Text = fmt.Sprintf("Tool %s has an invalid parameter schema: %s", call.Name, err)
}
return result
}
errors.As 问的是:这个 err 是不是一个 *schema.Error?是,就是参数不合格,错在模型,前面见过的 Invalid arguments for tool read: ... 都走这条。不是,就是第 1 步说的 schema 自己坏了,错在写工具的人。我们把 read 的 schema 写坏一处看看,required 应该是数组,写成字符串。tools/read.go:
- []byte(`{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}`),
+ []byte(`{"type":"object","properties":{"path":{"type":"string"}},"required":"path"}`),
运行:
调用 id=call_1 name=read arguments={"path":"package.json"}
结果 tool=read is_error=true
内容 "Tool read has an invalid parameter schema: schema at $ is not a valid schema object: json: cannot unmarshal string into Go struct field node.required of type []string"
调用 id=call_2 name=read arguments={}
结果 tool=read is_error=true
内容 "Tool read has an invalid parameter schema: schema at $ is not a valid schema object: json: cannot unmarshal string into Go struct field node.required of type []string"
参数对的 call_1 和参数错的 call_2 得到同一句话。这时候怪参数就冤枉了模型:它怎么改都没用。所以这句话直说是工具的 schema 坏了。改回去。
参数还可能是空的,一个字节都没有。这也算不合格,交回的是 arguments are not valid JSON,agent/tool_test.go 里的 empty arguments 那条测的就是它。真模型调一个不需要参数的工具时,确实可能一个参数片段都不发,但这种情况在第 2 章的 OpenAI 客户端里就处理掉了。工具调用结束时,参数是空的就补成 {},ai/openai.go:
if len(call.Arguments) == 0 {
call.Arguments = json.RawMessage("{}")
s.content[index] = call
}
也就是说,空参数在字节进门的地方就整理好了。还能走到 RunToolCall 的空参数,说明前面哪段代码出了错,当成不合格交回去,正好让它露出来。
三道关卡都过了,执行。执行之前先安排好接 panic 的人:
// A panicking tool must not take the whole agent down; the model gets to see the failure instead.
defer func() {
if r := recover(); r != nil {
result = ai.ToolResultMessage{
ToolCallID: call.ID, ToolName: call.Name, IsError: true,
Text: fmt.Sprintf("Tool %s panicked: %v", call.Name, r),
}
}
}()
defer 后面的函数会在 RunToolCall 返回时执行,正常返回也好,panic 也好。recover() 就是接住 panic 的那只手:有 panic,它返回 panic 带的值(试验 3 的 runtime error: index out of range [0] with length 0),并让程序不再往外崩;没有,它返回 nil,什么都不做。接住以后要改返回值,所以函数签名里给返回值起了名字 result:起了名字,defer 里的函数才改得到它。
最后真正执行:
text, err := tool.Execute(ctx, call.Arguments)
if err != nil {
result.Text = err.Error()
return result
}
result.Text = text
result.IsError = false
return result
工具返回 error,把 error 的文字原样交回去,call_6 那句就是这么来的。只有最后三行是成功的路,IsError 在这里才变成 false。
第 5 步:demo 和全部测试(demo/main.go)
demo 我们已经看过大半:开头准备临时目录和 package.json,中间是那两次调用,printResult 打印三行里的后两行。
demo/main.go 还有一个 --real 模式:用第 2 章的环境变量连真模型,把 read 的说明(Declarations 的结果)放进请求,请模型读 go.mod,执行它返回的工具调用,最后打印「结果还没有送回模型,这是下一章的事。」这个模式没有对真实的接口验证过,所以这里不贴它的输出。配好第 2 章的三个环境变量 AFZ_BASE_URL、AFZ_API_KEY、AFZ_MODEL,你可以自己运行 go run ./demo --real。模型照做的话,你会看到一行带 name=read 的「调用」,接着「结果」那行是 is_error=false,「内容」是 go.mod 的两行;模型没调工具,屏幕上是以「回复」开头的一行,或者「模型没有返回工具调用。」真模型可以让 read 读它想读的任何路径,绝对路径也行,第 3 步说过 read 不把路径限制在哪个目录里,限制是第 10 章的事。
把全部测试跑一遍:
go test ./...
ok afz/agent 0.387s
ok afz/ai 0.805s
? afz/demo [no test files]
ok afz/replay 0.942s
ok afz/schema 1.286s
ok afz/tools 1.655s
agent/tool_test.go 把这一章见过的每一句结果都固定成了一条测试:成功、工具不存在、缺字段、半截 JSON、空参数、schema 坏了、执行出错、喊停、panic。另外还多一条你没见过的:参数是字符串 "x" 而不是对象,交回 expected object, got string。以后谁改坏了其中一句,它会先叫。
旁白
主线走完了。下面三段是路上绕开的东西,跳过去不影响后面的章节。
旁白 1:数字为什么不直接解析成 float64
Go 解析 JSON 时,默认把所有数字都变成 float64。这对 "type":"integer" 不够用:float64 存不下 1.0000000000000001,解析出来就是 1,一查还是整数。所以 decodeNumbers 打开了 UseNumber,让数字保持原来的写法(json.Number),matchesType 再用 math/big 的有理数按写法判断是不是整数。测试里写明了两头:2.0 算整数,1.5 不算。
旁白 2:没认识的关键字,一律放过
校验器只认五个关键字。schema 里写了 minLength(字符串最短多长)、additionalProperties(能不能有多余的字段)这类别的关键字,它不报错,也不检查。测试里的 extra property 那条写明了:{"path":"a","extra":true} 能过。也就是说,模型多写几个字段不算错,工具解析时会把它们丢掉。要更多关键字,就往 node 里加字段、往 validate 里加检查;这本教程用到的工具,五个就够了。
旁白 3:recover 只接得住自己这条线上的 panic
recover 只对同一个 goroutine(Go 的轻量线程)里的 panic 有效。要是一个工具自己另起了一个 goroutine,panic 发生在那里,RunToolCall 里的 recover 接不到,程序照样会崩。写工具时另起 goroutine,得在那个 goroutine 里自己接。这一章的工具都不另起 goroutine,下一章并行执行多个工具调用时,每个调用会在自己的 goroutine 里走一遍 RunToolCall,接 panic 的人也就跟着到了那条线上。
对照 pi
这一章照的是 pi 的 packages/agent 里执行工具的那一段,和它检查参数用的 packages/schema。下面每一条都对着 v1.7.0 的源码。
execute 多两个参数。 pi 的工具 AgentTool 也有名字、描述、参数说明三样(来自模型层的 Tool)和一个执行函数,另外多一个必填的 label,是界面上显示的名字。它的 execute 收四个参数:工具调用的编号 toolCallId、参数、用来喊停的 signal(相当于我们的 ctx),和一个进度回调 onUpdate。工具每调用一次 onUpdate,pi 就发一个 tool_execution_update 事件,界面可以边执行边显示。我们的 Execute 只收 ctx 和参数,交回一段文字。pi 交回的 AgentToolResult 可以带图片,还有给界面用、不发给模型的 details。
准备的顺序。 pi 的 prepareToolCall 依次做:查有没有被喊停,按名字找工具,整理参数,校验参数,最后调用 beforeToolCall 钩子。「整理参数」是工具可选的 prepareArguments,注释说它是校验之前给原始参数用的兼容垫片。我们的 RunToolCall 是同样的顺序,少了整理参数和钩子;钩子在第 9 章。喊停了为什么还要交结果,pi 的注释写了:调用方照样会把这条结果记下来,这样没有哪次调用缺结果。
错误结果的文字。 我们的 Operation aborted 和 Tool write not found 是照抄 pi 的:pi 的喊停和找不到工具都用 createErrorToolResult 把一句话包成工具结果。准备阶段抛出的异常被接住,执行时抛出的异常在 executePreparedToolCall 里被接住,都变成结果。pi 导出的 runToolCall 的注释写得最明白:工具失败时它从不报错,喊停、找不到工具、校验失败、抛异常,全都以 isError: true 的结果交回。pi 的工具报告失败有两种办法:抛异常,或者交回一个 isError: true 的结果,两种最后都是一条错误结果,try 管的是抛异常那一种。我们的 Execute 返回 error,对应的是 pi 的 isError;Go 另外还有 panic 这条路,它不走返回值,所以要靠 recover 接住。
校验时先纠正参数。 pi 选择了先纠正、再校验:注释说,模型常常把数字写成 "42",把数组写成单个值,或者给没填的可选字段写 null。我们不纠正,{"path":1} 就是不合格。pi 的校验失败时会列出所有问题,后面附上收到的参数,我们只报第一处。模型交来的参数不是合法 JSON 时,第 1 章说过 pi 会把毛病记在 argumentsError 里,到这里直接报 Invalid arguments for tool,和我们的 call_4 是一个意思。
schema 编译一次,我们每次解释。 pi 的 packages/schema 把一份 schema 编译成一组普通的闭包,只编译一次,理由写在同一句里:这样检查的速度接近生成代码的校验器,在禁止 eval 的严格安全策略下也能用。编译器文件的开头说,常见的几种形状各有一个专门的闭包。编译好的校验器按 schema 缓存:工具的 schema 会一直用下去,缓存住就不必每次重新编译。我们的 validate 每次调用都重新解析 schema 的 JSON,一层一层边读边查,好懂,但同一份 schema 每次都要再读一遍。pi 支持 JSON Schema 的 2020-12 和 7 两个版本,我们只认五个关键字。
参数的类型从 schema 推出来。 第 2 步的试验里,schema 和结构体各写各的,对不上也没人发现。pi 的工具拿到的参数类型是 Static<TParameters>,从 schema 的类型推出来。用 packages/schema 的构建函数写 schema 时,TypeScript 类型由同一份 schema 推出,就没有两份要核对。Go 的泛型做不到从一段 JSON 推出结构体,所以 NewTool 要写工具的人自己让两边一致。
你现在手里有什么
回到开头:模型说要读文件,程序照办之前要做什么?先找到工具,再拿 schema 检查参数,然后执行,执行时还得防着它崩。不管哪一步出事,交回去的都是一条结果,不是一个让 agent 停下的 error。
具体到代码:
- 一个校验器
schema.Validate:认type、properties、required、enum、items,不合格时交回*schema.Error,带位置,比如$.path。 - 工具类型
agent.Tool,和帮手agent.NewTool:写一个收结构体的函数,就得到一个工具。 agent.RunToolCall:喊停、找不到工具、参数不合格、schema 坏了、执行出错、panic,全都变成IsError为真的ToolResultMessage。- 一个
read工具:tools.NewRead(root)。
第 4 章把这些接成 agent 循环:模型提出工具调用,RunToolCall 执行,结果送回模型,再问一次,直到模型不再要工具。到那时,call_2 那句 missing required property "path" 就真的会被模型读到。
这一章的文件
A agent/tool.go
A agent/tool_test.go
M demo/main.go
A schema/schema.go
A schema/schema_test.go
A tools/read.go
A tools/read_test.go