2025 年初,几乎所有人都在讨论 Agent。但把”Agent”这个词拆开,它的技术底座其实很朴素:大模型 + 工具 + 一个循环。会写这段循环,比记住十种框架更重要。这篇从最原始的 function calling 讲起,手写一个能跑的最小 Agent。
为什么单靠 Prompt 不够
大模型的三个先天限制:
- 没有实时信息:训练数据有截止日期,问今天的天气只能编
- 不能产生副作用:它不能发邮件、不能写数据库、不能调接口
- 不能多步推理落地:它可以”分析”,但分析完的动作要人来执行
工具调用解决的是前两个。第三个需要”循环”——让模型自己决定下一步调什么、看完结果再决定下一步。这个循环就是 Agent。
工具调用协议
以 OpenAI 兼容接口为例,工具是结构化声明的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const tools = [ { type: 'function', function: { name: 'get_weather', description: '查询指定城市的实时天气', parameters: { type: 'object', properties: { city: { type: 'string', description: '城市名,例如 杭州' }, unit: { type: 'string', enum: ['celsius', 'fahrenheit'] } }, required: ['city'] } } } ]
|
模型不会真的执行函数,它只会返回”我想调 get_weather,参数是 {"city":"杭州"}“。执行是你的代码做的。
交互过程是这样的:
1 2 3 4 5
| 用户 → 模型(带 tools 声明) 模型 → { tool_calls: [{ function: { name: 'get_weather', arguments: '{"city":"杭州"}' } }] } 你的代码 → 执行函数 → 得到结果 你的代码 → 把结果以 role: 'tool' 的消息追加回对话 模型 → 基于结果生成自然语言回答
|
手写 Agent 循环
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
| type Message = | { role: 'system' | 'user'; content: string } | { role: 'assistant'; content: string | null; tool_calls?: ToolCall[] } | { role: 'tool'; tool_call_id: string; content: string }
interface ToolCall { id: string type: 'function' function: { name: string; arguments: string } }
const registry: Record<string, (args: any) => Promise<any>> = { get_weather: async ({ city }) => ({ city, temp: 19, text: '多云' }), search_docs: async ({ query }) => ({ hits: [`关于 ${query} 的文档片段`] }) }
async function runAgent(userInput: string, maxSteps = 8) { const messages: Message[] = [ { role: 'system', content: '你是一个助手。需要外部信息时必须调用工具,不要凭空猜测。' }, { role: 'user', content: userInput } ]
for (let step = 0; step < maxSteps; step++) { const res = await client.chat.completions.create({ model: 'gpt-4o-mini', messages, tools, tool_choice: 'auto' })
const msg = res.choices[0].message messages.push({ role: 'assistant', content: msg.content, tool_calls: msg.tool_calls })
if (!msg.tool_calls?.length) { return msg.content }
for (const call of msg.tool_calls) { const fn = registry[call.function.name] let content: string
try { if (!fn) throw new Error(`未知工具: ${call.function.name}`) const args = JSON.parse(call.function.arguments) const result = await fn(args) content = JSON.stringify(result) } catch (e) { content = JSON.stringify({ error: (e as Error).message }) }
messages.push({ role: 'tool', tool_call_id: call.id, content }) } }
throw new Error('超过最大步数,可能陷入循环') }
|
这段代码不到 50 行,但它就是绝大多数 Agent 框架的核心。LangChain、LangGraph、各家 SDK 做的事情,本质都是在这个循环外面加抽象、加状态管理、加可观测性。
三个细节决定了它能不能用:
- **
maxSteps**:必须有上限,模型陷入循环时能兜住
- 错误回填:工具报错不要直接抛给用户,把错误信息返回给模型,它通常会换参数重试
- **
tool_choice: 'auto'**:让模型自行决定,强制调用会带来无意义的工具调用
ReAct:带推理的循环
ReAct 的思路是”边想边做”,在每一步显式输出思考:
1 2 3 4 5
| Thought: 用户问杭州天气,我需要调用天气工具 Action: get_weather({"city": "杭州"}) Observation: {"temp": 19, "text": "多云"} Thought: 已经拿到数据,可以回答了 Answer: 杭州现在 19 度,多云。
|
实现上两种方式:
- 纯 Prompt:在 system 里约定格式,解析模型输出。简单但脆弱
- 结构化:现在主流模型都有原生工具调用,推理链交给模型的 reasoning 能力,不再手动解析文本
2025 年的实践里,第二种是主流。所以”ReAct 的文本格式”更多是一个思维模型,而不是必须手写的协议。
三个必要组件
跑通循环之后,想让它真正可用,还需要三样东西:
1. 记忆
1 2 3
|
const memory = await vectorStore.search(lastUserMessage, { topK: 5 })
|
对话历史不能无限追加,必须有压缩策略:保留最近 N 轮 + 对早期内容做摘要。
2. 工具设计
工具的质量比模型更重要。经验规则:
- 名字用动词短语:
create_invoice 比 invoice 好
- 描述里写清”什么时候该用”,而不只是”这个工具做什么”
- 参数尽量扁平,避免深层嵌套
- 返回结构稳定、字段名自解释
- 单个工具只做一件事
1 2 3 4 5 6
| { name: 'manage_order', parameters: { action: 'create|update|delete', data: {} } }
{ name: 'create_order', parameters: { sku: string, qty: number } } { name: 'cancel_order', parameters: { orderId: string, reason?: string } }
|
3. 兜底与确认
涉及写操作的 Agent 必须有”人在环路”:
1 2 3
| if (call.function.name.startsWith('delete_') && !state.userConfirmed) { return { needConfirm: true, action: call.function.name, args } }
|
把执行动作变成”申请执行”,比事后回滚便宜得多。
常见失败模式
| 现象 |
原因 |
对策 |
| 反复调同一个工具 |
结果没被理解,或参数总错 |
优化工具返回的可读性,加步数上限 |
| 参数幻觉 |
schema 描述不清 |
用 JSON Schema 严格约束 + 服务端校验 |
| 回答里编造工具结果 |
模型绕过工具直接回答 |
system 里明确禁止,并对回答做事实校验 |
| 成本爆炸 |
长上下文 + 多轮工具 |
裁剪历史、用小模型做工具选择 |
| 越权操作 |
权限校验放在模型侧 |
权限必须在工具实现里校验 |
最后一条最重要:模型的判断不是安全边界。工具函数必须以”陌生调用方”的身份做校验,就像对待任何外部请求一样。
什么时候不该用 Agent
这一点很少被提到,但很关键:
- 流程固定的场景:用工作流(workflow)就够了,可预测、可测试、便宜
- 只有一步操作:直接函数调用 + 模型做参数提取,不需要循环
- 要求确定性输出的场景:Agent 的每一步都有不确定性,不适合做财务计算这类必须精确的任务
判断标准:如果任务路径是确定的,用工作流;只有路径需要模型动态决定时,才用 Agent。 很多被做成 Agent 的功能,其实是一个带意图识别的固定流程。
小结
Agent 的入门门槛比想象中低:一个工具声明表、一个循环、一段错误处理,就能跑。真正的门槛在工程化——工具设计得好不好、错误能不能兜住、成本能不能控住、权限有没有守住。这些在 2025 年下半年到 2026 年演化成了一整套东西:MCP 解决工具接入标准化,A2A 解决 Agent 间协作,可观测性解决”它到底在想什么”。但底座始终是今天这 50 行。