Chatbot 只会聊天;Agent 还能决定调用工具:查库、搜文档、算数、调 API。理解 Function Calling,是进入 Agent 开发的第一扇门。
一次典型循环
- 用户提出目标
- 模型选择:直接回答 or 调用某个工具
- 程序执行工具,把结果回填
- 模型基于工具结果继续推理,直到给出最终答案
工具描述示例
tools = [{
"type": "function",
"function": {
"name": "get_order",
"description": "根据订单号查询订单状态与金额",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "订单号"}
},
"required": ["order_id"]
}
}
}]
伪代码主循环
messages = [{"role": "user", "content": "帮我查订单 A10086 到哪了"}]
while True:
resp = llm.chat(messages, tools=tools)
if resp.tool_calls:
for call in resp.tool_calls:
result = run_tool(call.name, call.arguments)
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
continue
return resp.content
设计原则
- 工具要少而精,描述写清楚「何时用」
- 参数 schema 严格,减少胡编参数
- 工具执行必须鉴权与审计