- 人工智能
- AI Agent
- Agent 框架
- 工具调用
- 大模型
【免费下载链接】fantasy
Build AI agents with Go. Multiple providers, multiple models, one API. 🧙
Fantasy 是一个用 Go 构建 AI Agent 的开源 SDK,核心卖点是多提供商(Multi-provider)、多模型(Multi-model)、一个统一 API。无论你偏好 OpenAI、Anthropic、Google 还是 OpenRouter,代码写法都保持同一套接口,切换模型只需改一行。这篇文章将带你用 5 分钟时间,从零搭建起第一个具备工具调用能力的 Go AI Agent。
一、Fantasy 是什么?为什么值得用?🧙
一句话总结 Fantasy 的定位:
Build AI agents with Go. Multiple providers, multiple models, one API.
它的三步工作流非常直观:
- 选模型和提供商(Choose a model and provider)
- 加几个工具(Add some tools)
- 编译成原生机器码直接跑(Compile to native machine code and let it rip)
对新手最友好的三个特性:
- 🎯统一接口:
Provider接口只有两个方法(见 provider.go),所有提供商实现同一套抽象; - 🛠️工具即函数:用 Go 函数 + 结构体 tag 就能定义工具,JSON Schema 自动生成(见 tool.go 与 schema/);
- 🔁内置重试与修复:自动退避重试(retry.go)、损坏 JSON 自动修复(jsonrepair/)。
💡 Fantasy 正是 Charm 团队为其 AI 编程助手 Crush 打造的底层框架,生产级稳定性有保障。
二、环境准备与一键安装步骤 📦
1. 确认 Go 版本
Fantasy 要求Go 1.27.0+(见 go.mod)。在终端执行:
go version版本不足的话,先升级到最新的 Go 稳定版即可。
2. 克隆仓库
git clone https://gitcode.com/gh_mirrors/fantasy6/fantasy项目结构速览(新手重点关注examples/即可):
| 目录 | 作用 |
|---|---|
| examples/ | 全部上手示例:简单对话、流式、结构化输出、联网搜索等 |
| providers/ | 各提供商实现:openai、anthropic、google、azure、bedrock、openrouter、vercel等 |
| agent.go | Agent 核心:多步工具循环、停止条件、选项配置 |
| object/ | 类型安全的结构化输出:object.Generate[T]/object.Stream[T] |
3. 配置 API Key
以 OpenRouter 为例(新手推荐,一个 Key 可用多家模型):
export OPENROUTER_API_KEY="你的密钥"⚠️ 不同提供商对应不同环境变量:
OPENAI_API_KEY、ANTHROPIC_API_KEY、GOOGLE_API_KEY等,命名规则为<提供商>_API_KEY。
三、5分钟写出你的第一个 Agent 🚀
下面按官方示例 examples/simple/main.go 拆解成 4 步,核心代码总共不到 30 行。
第 1 步:创建 Provider 并选择模型
import ( "charm.land/fantasy" "charm.land/fantasy/providers/openrouter" ) // 创建提供商 provider, _ := openrouter.New(openrouter.WithAPIKey(os.Getenv("OPENROUTER_API_KEY"))) // 选择模型 model, _ := provider.LanguageModel(ctx, "moonshotai/kimi-k2")注意LanguageModel这一步:同一个 Fantasy 里可以创建任意多个不同提供商的 model,这就是"多模型"的来源。
第 2 步:定义一个 Agent 工具
工具就是一个普通的 Go 函数,输入用结构体 +descriptiontag 描述:
type cuteDogQuery struct { Location string `json:"location" description:"The location to search for cute dogs."` } 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 } cuteDogTool := fantasy.NewAgentTool("cute_dog_tool", "Provide up-to-date info on cute dogs.", fetchCuteDogInfo)模型会自动根据description填出正确的调用参数,无需手写 schema。
第 3 步:组装 Agent
agent := fantasy.NewAgent( model, fantasy.WithSystemPrompt("You are a moderately helpful, dog-centric assistant."), fantasy.WithTools(cuteDogTool), )NewAgent支持一系列选项(完整列表见 agent.go):WithSystemPrompt、WithTools、WithTemperature、WithMaxRetries、WithStopConditions……按需取用即可。
第 4 步:发起调用,拿到结果 🎉
result, _ := agent.Generate(ctx, fantasy.AgentCall{ Prompt: "Find all the cute dogs in Silver Lake, Los Angeles.", }) fmt.Println(result.Response.Content.Text())Fantasy 会自动完成模型思考 → 调用工具 → 把工具结果喂回模型 → 输出最终答案的完整多步循环,你不需要自己写任何工具循环逻辑。
运行它
示例是独立 Go module(examples/go.mod 通过replace指向主仓库),在examples/目录下直接运行:
cd examples go run ./simple四、多模型多提供商如何选?(附速查表)🌐
Fantasy 为每个主流平台提供了专属包,位于 providers/ 目录:
| 提供商 | 导入包 | 典型模型示例 |
|---|---|---|
| OpenAI | providers/openai/ | gpt-4o、gpt-5 |
| Anthropic | providers/anthropic/ | claude-sonnet-4、claude-haiku-4-5 |
| providers/google/ | gemini-2.5-flash、gemini-3-pro-preview | |
| Azure | providers/azure/ | azure-gpt-5-mini |
| Amazon Bedrock | providers/bedrock/ | bedrock-anthropic-claude-sonnet-4-5 |
| OpenRouter | providers/openrouter/ | moonshotai/kimi-k2等聚合模型 |
| Vercel AI Gateway | providers/vercel/ | gpt-5、claude-sonnet-4 |
| OpenAI 兼容层 | providers/openaicompat/ | xAI、GLM、Kimi、llama.cpp 等 |
关键技巧:遇到没有专属包的服务商(比如自建推理服务、Groq、HuggingFace 等),只要它兼容 OpenAI 接口,就用openaicompat通用层 +WithBaseURL指向你的地址即可接入,一行搞定:
provider, _ := openaicompat.New( openaicompat.WithAPIKey("sk-xxx"), openaicompat.WithBaseURL("http://localhost:8080/v1"), )🔑 记住这个原则:专属包优先,
openaicompat兜底,这就是 Fantasy "一个 API 通吃多模型" 的真正含义。
五、进阶玩法:从聊天到生产级 Agent 🔧
跑通第一个 Agent 后,这些官方示例值得逐个体验:
1. 流式输出(Streaming)
通过agent.Stream配合回调,实时打印文字增量、工具调用过程(完整示例见 examples/stream/main.go):
streamCall := fantasy.AgentStreamCall{ Prompt: "Chuck just met a new dog at the park...", OnTextDelta: func(id, text string) error { return fmt.Print(text) }, OnToolCall: func(tc fantasy.ToolCallContent) error { return nil }, } _, _ = agent.Stream(ctx, streamCall)2. 结构化输出(类型安全的数据)
定义一个 struct,模型返回的就是编译期类型安全的 Go 对象,而不是需要解析的字符串(见 examples/structured-outputs/main.go):
type Recipe struct { Name string `json:"name" description:"The name of the recipe"` Ingredients []string `json:"ingredients" description:"List of ingredients needed"` PrepTime int `json:"prep_time" description:"Preparation time in minutes"` } result, _ := object.GenerateRecipe}, }) fmt.Println(result.Object.Name, result.Object.PrepTime)3. 联网搜索与 Computer Use
- Web Search:一行
anthropic.WebSearchTool(nil)或openai.WebSearchTool(nil)即可让 Agent 服务端联网并附来源引用(examples/web-search/main.go); - Computer Use:让 Claude 操作虚拟屏幕、点击、输入、截图(examples/computer-use/main.go)。
4. 控制 Agent 停止条件
WithStopConditions支持按步数、Token 上限、特定工具调用等条件停止(如StepCountIs(3)、MaxTokensUsed(10000)),配合WithMaxRetries让长任务既稳定又省钱。
六、学习路线图:下一步看哪里?🗺️
| 想学什么 | 去哪里 |
|---|---|
| 最小完整示例 | examples/simple/main.go |
| 天气查询式工具 + 用量统计 | examples/moon/main.go |
| 多提供商横向对比测试 | providertests/ |
| 工具调用与响应细节 | tool.go |
| Agent 多步循环与选项 | agent.go |
| 结构化输出 API | object/object.go |
| 开发规范与项目布局 | AGENTS.md |
一句话行动清单:
- ✅ 克隆仓库并配置一个
OPENROUTER_API_KEY - ✅ 运行
examples/simple跑通第一个 Agent - ✅ 把
moonshotai/kimi-k2换成gpt-4o或claude-sonnet-4,体会"换模型不换代码" - ✅ 尝试
structured-outputs拿到类型安全结果
Fantasy 用一套极简的 Go 接口抹平了各家 AI 提供商的差异,让你把精力真正花在 Agent 的业务逻辑上。现在就开始,5 分钟后的你已经在运行自己的第一个多模型 AI Agent 了 🧙♂️
- 人工智能
- AI Agent
- Agent 框架
- 工具调用
- 大模型
【免费下载链接】fantasy
Build AI agents with Go. Multiple providers, multiple models, one API. 🧙
相关推荐
5分钟快速上手Goravel:从零构建你的第一个Web应用
5分钟快速上手Goravel:从零构建你的第一个Web应用 想要快速构建高性能的Go语言Web应用吗?Goravel框架正是您需要的完美解决方案!🎯 作为一个
后端Web框架OpenHands Software Agent SDK快速上手:10分钟构建你的第一个AI Agent
OpenHands Software Agent SDK快速上手:10分钟构建你的第一个AI Agent OpenHands Software Agent SD
designing-multiagent-systems 快速上手:5分钟从零构建你的第一个LLM Agent(PicoAgents实战)
designing multiagent systems 快速上手:5分钟从零构建你的第一个LLM Agent(PicoAgents实战) designing
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考