给AI Agent装上双手:Fantasy工具调用(Tool Calling)实战,从新手到高手

原创2026-10-14 13:18:471,351 阅读
文章标签:人工智能大模型AI AgentAgent 框架工具调用

给AI Agent装上双手:Fantasy工具调用(Tool Calling)实战,从新手到高手

Fantasy 是一个用 Go 构建 AI Agent 的开源框架,主打「多 Provider、多模型、统一 API」。而 Tool Calling(工具调用)正是它最有魅力的部分——它让大模型不再只会"说",还能真正"动手":查天气、执行 SQL、操作电脑屏幕。本文带你从零理解 Tool Calling 的原理,到用 Fantasy 写出第一个工具,再到并行调用、流式观测等高手技巧。

🐶 什么是 Tool Calling?为什么 Agent 需要它

大模型本身只能输出文本,而"动手"意味着执行外部动作:

  • 查数据库、调 API、读文件
  • 执行命令、操作浏览器或电脑
  • 调用其他程序完成计算

Tool Calling 就是桥梁:模型判断"我该用哪个工具、传什么参数",你的代码负责真正执行,再把结果喂回给模型,如此循环直到任务完成。Fantasy 把这个循环完全托管给 Agent,你只需关注"工具本身"。

核心代码位于根目录的 tool.go,定义了 ToolInfo(工具元信息)、ToolCall(一次调用请求)、ToolResponse(执行结果)三个关键类型,是整篇文章的主线。

🧩 Fantasy 工具调用的四大组件

组件 所在文件 作用
ToolInfo tool.go#L16-L22 工具的名称、描述、参数 schema,交给模型"看菜单"
ToolCall tool.go#L24-L29 模型发起的一次调用:ID + 工具名 + JSON 参数
ToolResponse tool.go#L37-L49 执行结果,支持文本、图片、音频等媒体类型
AgentTool tool.go#L101-L106 工具接口:Info() 描述自己,Run() 执行自己

最省心的用法是 fantasy.NewAgentTool(name, description, fn)——传一个 Go 函数即可创建工具,参数 schema 自动生成。

🚀 新手上路:三步写出第一个工具

官方示例 examples/simple/main.go 展示了一个"查可爱狗狗"的工具,三步走:

第 1 步:定义输入结构体。 用结构体描述工具参数,struct tag 直接生成 schema:

type cuteDogQuery struct {
    Location string `json:"location" description:"The location to search for cute dogs."`
}

第 2 步:实现工具函数。 签名固定为 (ctx, input, call) (ToolResponse, error):

fetchCuteDogInfo := func(ctx context.Context, input cuteDogQuery, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
    if input.Location == "Silver Lake, Los Angeles" {
        return fantasy.NewTextResponse("Cute dogs are everywhere!"), nil
    }
    return fantasy.NewTextResponse("No cute dogs found."), nil
}

第 3 步:装备 Agent。 通过 WithTools 把工具交给 Agent,然后像聊天一样提问:

agent := fantasy.NewAgent(
    model,
    fantasy.WithSystemPrompt("You are a moderately helpful, dog-centric assistant."),
    fantasy.WithTools(cuteDogTool),
)
result, err := agent.Generate(ctx, fantasy.AgentCall{Prompt: "Find all the cute dogs in Silver Lake."})

Agent 会自动完成「模型请求工具 → 执行工具 → 结果回传 → 模型继续」的整个循环(见 agent.go#L440 的 Generate),你只管拿最终答案。

📐 高手进阶一:schema 自动生成与修复

Fantasy 的 schema/schema.go 会从 Go 类型递归生成 JSON Schema,支持 json、description、enum 等 tag,嵌套结构、数组、枚举都能处理。

更妙的是内置了 jsonrepair/ 包:当模型返回的 JSON 参数略有瑕疵(漏了引号、多了注释),框架会先尝试自动修复再解析,而不是直接报错——这在生产环境中能大幅减少工具调用失败。

🎛 高手进阶二:用 ToolChoice 控制模型行为

默认情况下模型"自己决定"用不用工具,你可以通过 WithToolChoice 干预策略(定义见 model.go#L197-L212):

  • ToolChoiceAuto(默认):模型自行判断
  • ToolChoiceRequired:强制必须调用某个工具
  • ToolChoiceNone:禁用工具
  • SpecificToolChoice("weather"):指定只能用某个工具

比如做数据提取流水线时,ToolChoiceRequired 能保证每步都走工具,输出更稳定。

🔁 高手进阶三:并行工具与停止条件

并行工具:无副作用的只读工具(如查询)可以用 NewParallelAgentTool 创建(tool.go#L127-L140),模型会一次性发出多个调用,Agent 并行执行,速度明显更快。

停止条件:Agent 循环需要"刹车"防止失控,agent.go 内置了丰富的 StopCondition:

  • StepCountIs(10) —— 最多跑 10 步
  • HasToolCall("done") —— 调用了指定工具就停
  • MaxTokensUsed(n) —— token 预算耗尽就停

👀 高手进阶四:流式观测每一步

想知道 Agent 内部发生了什么?用流式 API + 回调即可全程"围观",参考 examples/stream/main.go#L86-L117:

streamCall := fantasy.AgentStreamCall{
    Prompt: "Chuck just met a new dog at the park.",
    OnTextDelta:  func(id, text string) error { fmt.Print(text); return nil },
    OnToolCall:   func(tc fantasy.ToolCallContent) error { /* 工具被调用 */ return nil },
    OnToolResult: func(res fantasy.ToolResultContent) error { /* 拿到工具结果 */ return nil },
    OnStepFinish: func(_ fantasy.StepResult) error { return nil },
}

OnStepStart / OnStepFinish 等钩子让你对每一步了如指掌,非常适合做 TUI 或调试面板。

💪 高手进阶五:处理错误与特殊工具

优雅的错误:工具执行失败不等于任务失败。返回 fantasy.NewTextErrorResponse("msg") 时,错误信息会作为普通结果回传给模型,让它自己想办法重试(tool.go#L59-L67)。而 ToolResponse 的 StopTurn 字段则用于"致命错误,立即终止"。

图片等媒体结果:NewImageResponse / NewMediaResponse 可以把截图、音频直接喂回给多模态模型。

Provider 定义的工具:像 Anthropic 的 computer use(操作电脑)这类由模型侧定义参数的工具,用 WithProviderDefinedTools 注册即可。官方示例 examples/computer-use/main.go#L59-L89 演示了 Agent 如何自动处理截屏→点击→再截屏的完整闭环。

🗺 生态速览:一个工具,所有模型

Fantasy 在 providers/ 下内置了 OpenAI、Anthropic、Google、Azure、Bedrock、OpenRouter、Vercel 等多家适配层,未适配的厂商可以走通用的 openaicompat。你的工具代码一次编写、跨模型运行,切换模型只需换 Provider 和模型名。跨 Provider 的工具调用测试用例可参考 providertests/。

✅ 常见场景速查表

场景 推荐做法
快速创建工具 fantasy.NewAgentTool(name, desc, fn)
只读查询提速 NewParallelAgentTool 并行执行
保证一定调用工具 WithToolChoice(ToolChoiceRequired)
防止循环失控 WithStopConditions(fantasy.StepCountIs(n))
工具失败让模型自救 返回 NewTextErrorResponse
实时展示执行过程 AgentStreamCall + OnToolCall 回调
操作电脑/浏览器 WithProviderDefinedTools + 截图回传

总结

Fantasy 把 Tool Calling 中最繁琐的部分——schema 生成、参数修复、多步循环、跨 Provider 差异——全部封装好了。你只需三步:定义输入结构体 → 写一个执行函数 → WithTools 装备 Agent。剩下的进阶玩法(并行、ToolChoice、停止条件、流式回调)按需取用,就能从新手快速进阶为 Agent 高手。

想动手试试?先看看 examples/ 目录下的 simple、stream、computer-use 三个示例,它们是最佳学习路径。🧙

登录后查看全文
fantasy