agent tool use guide

Agent 工具使用指南:从 Function Calling 到自主工具发现

工具使用:Agent 的双手 没有工具的 LLM 是一个"只会说话的大脑"——它知道很多,但什么都做不了。工具使用让 Agent 从"问答机器"变成"行动者"。 演进路径 2023: Hard-coded Functions(硬编码函数) 2024: Function Calling(OpenAI 标准化) 2025: Tool Use API(Anthropic 扩展) 2026: MCP + 自主工具发现(工具市场) 第一阶段:Function Calling 基本用法 from openai import OpenAI client = OpenAI() tools = [ { "type": "function", "function": { "name": "get_weather", "description": "获取指定城市的天气", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "城市名称,如北京、上海" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "温度单位" } }, "required": ["city"] } } } ] response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "北京今天多少度?"}], tools=tools, ) # LLM 返回工具调用 tool_call = response.choices[0].message.tool_calls[0] # {"name": "get_weather", "arguments": {"city": "北京", "unit": "celsius"}} # 执行工具 result = get_weather(**json.loads(tool_call.function.arguments)) # 把结果返回给 LLM response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "user", "content": "北京今天多少度?"}, response.choices[0].message, {"role": "tool", "tool_call_id": tool_call.id, "content": result} ], tools=tools, ) 多工具并行调用 # 现代 LLM 支持一轮调用多个工具 response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "北京和上海今天天气怎么样?"}], tools=tools, ) # 返回两个 tool_calls: get_weather(北京) + get_weather(上海) # 并行执行 results = await asyncio.gather(*[ execute_tool(tc) for tc in response.choices[0].message.tool_calls ]) 第二阶段:工具设计原则 原则一:描述要精确 # ❌ 差:描述模糊 { "name": "search", "description": "搜索内容" } # ✅ 好:描述精确 { "name": "search_web", "description": "在互联网上搜索给定查询,返回前10个结果的标题、URL和摘要。适用于查找最新信息、新闻、技术文档。", "parameters": { "properties": { "query": { "type": "string", "description": "搜索关键词,30字以内,去除无意义词" }, "time_range": { "type": "string", "enum": ["day", "week", "month", "year", "all"], "description": "时间范围过滤" } } } } 原则二:参数要简洁 # ❌ 差:参数太多 { "name": "send_email", "parameters": { "properties": { "to": {}, "cc": {}, "bcc": {}, "subject": {}, "body": {}, "attachments": {}, "priority": {}, "format": {}, "encoding": {}, "reply_to": {}, "sender_name": {} } } } # ✅ 好:只保留必要参数 { "name": "send_email", "parameters": { "properties": { "to": {"type": "string", "description": "收件人邮箱"}, "subject": {"type": "string", "description": "邮件主题"}, "body": {"type": "string", "description": "邮件正文"} }, "required": ["to", "subject", "body"] } } 原则三:错误信息要友好 async def execute_tool(tool_call): try: result = await tool_registry[tool_call.name](**tool_call.args) return {"status": "success", "data": result} except ValidationError as e: return { "status": "error", "error": f"参数错误:{e}", "hint": "请检查参数格式和必填项" } except Exception as e: return { "status": "error", "error": str(e), "hint": "如果重试仍失败,请尝试其他方法" } 第三阶段:MCP(Model Context Protocol) MCP 是 Anthropic 提出的工具标准协议,让工具可以跨模型使用: ...

2026-06-24 · 4 min · 675 words · 硅基 AGI 探索者
鲁ICP备2026018361号