Claude Tool Use 怎么用?从零到生产的完整教程(2026)
上周接了个需求做一个能查天气、查数据库、还能发邮件的 AI 助手。一开始想着用 LangChain 套一层后来发现 Claude 原生的 Tool Use也叫 Function Calling已经很成熟了根本不需要额外框架。但官方文档写得有点绕我踩了不少坑才把整条链路跑通。把摸索出来的东西全写下来让你少走弯路。Claude Tool Use 是 Anthropic 提供的原生函数调用能力允许你在对话中定义工具函数Claude 会自动判断何时调用哪个工具、提取参数你执行函数后把结果返回给它它再生成最终回答。目前 Claude Sonnet 4.6 和 Opus 4.6 都支持Sonnet 性价比最高Opus 复杂推理更强。先说结论维度说明支持模型Claude Opus 4.6、Sonnet 4.6、Haiku 4.6协议格式Anthropic 原生格式 / OpenAI 兼容格式均可核心流程定义工具 → 发送请求 → Claude 返回工具调用 → 你执行函数 → 结果回传 → Claude 生成回答并行调用支持一次可调用多个工具嵌套调用支持工具结果可触发新一轮工具调用踩坑重灾区tool_result 的 content 必须是字符串、工具描述写得烂会导致调用率暴跌核心流程一图看懂本地工具函数Claude API你的代码本地工具函数Claude API你的代码发送消息 工具定义返回 tool_use要调用哪个工具、参数是什么执行本地函数返回执行结果把 tool_result 回传Claude 生成最终回答这个流程是整个 Tool Use 的骨架后面的代码全是围绕这个转的。环境准备pipinstallopenai httpx这里用的是 OpenAI SDK。因为很多聚合平台都兼容 OpenAI 协议Claude 的 Tool Use 在 OpenAI 兼容模式下也能正常工作切换模型零成本。方案一基础 Tool Use单工具调用先来最简单的场景——让 Claude 调用一个查天气的函数。importjsonfromopenaiimportOpenAI clientOpenAI(api_keyyour-api-key,base_urlhttps://api.ofox.ai/v1# 聚合接口一个 Key 调 Claude/GPT/Gemini)# 1. 定义工具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]}}}]# 2. 你的本地函数实际项目中这里调真实 APIdefget_weather(city:str,unit:strcelsius)-dict:# 模拟数据实际替换成真实天气 APIfake_data{北京:{temp:22,humidity:45,condition:晴},上海:{temp:26,humidity:72,condition:多云},深圳:{temp:31,humidity:80,condition:雷阵雨},}datafake_data.get(city,{temp:20,humidity:50,condition:未知})ifunitfahrenheit:data[temp]data[temp]*9/532data[city]city data[unit]unitreturndata# 3. 发送请求messages[{role:user,content:深圳今天天气怎么样适合跑步吗}]responseclient.chat.completions.create(modelclaude-sonnet-4.6,messagesmessages,toolstools,tool_choiceauto# 让 Claude 自己决定要不要调工具)# 4. 处理工具调用assistant_messageresponse.choices[0].messageifassistant_message.tool_calls:# Claude 决定调用工具messages.append(assistant_message)# 先把 assistant 消息加进去fortool_callinassistant_message.tool_calls:func_nametool_call.function.name func_argsjson.loads(tool_call.function.arguments)print(fClaude 要调用:{func_name}({func_args}))# 执行本地函数iffunc_nameget_weather:resultget_weather(**func_args)# 把结果回传注意content 必须是字符串messages.append({role:tool,tool_call_id:tool_call.id,content:json.dumps(result,ensure_asciiFalse)})# 5. 让 Claude 根据工具结果生成最终回答final_responseclient.chat.completions.create(modelclaude-sonnet-4.6,messagesmessages,toolstools)print(final_response.choices[0].message.content)else:# Claude 觉得不需要调工具直接回答了print(assistant_message.content)实测输出Claude 要调用: get_weather({city: 深圳}) 深圳今天31°C湿度80%有雷阵雨。不太建议户外跑步哦 湿度太高容易中暑雷阵雨也不安全。建议等晚上凉快点再去 或者去室内跑步机上练练。Claude 不是机械地把数据复述一遍它会结合天气数据给出建议。这就是 Tool Use 比硬编码模板强的地方。方案二多工具 自动循环调用真实项目很少只有一个工具。下面这个例子定义了三个工具并且实现了自动循环——Claude 可能调完一个工具还想调另一个代码自动处理。importjsonfromopenaiimportOpenAI clientOpenAI(api_keyyour-api-key,base_urlhttps://api.ofox.ai/v1)# 定义多个工具tools[{type:function,function:{name:search_products,description:根据关键词搜索商品返回商品列表名称、价格、库存,parameters:{type:object,properties:{keyword:{type:string,description:搜索关键词},max_results:{type:integer,description:最多返回几条默认5}},required:[keyword]}}},{type:function,function:{name:get_product_reviews,description:获取指定商品ID的用户评价摘要,parameters:{type:object,properties:{product_id:{type:string,description:商品ID}},required:[product_id]}}},{type:function,function:{name:create_order,description:创建订单。注意仅在用户明确表示要购买时才调用,parameters:{type:object,properties:{product_id:{type:string},quantity:{type:integer,description:购买数量默认1}},required:[product_id]}}}]# 模拟业务函数defsearch_products(keyword,max_results5):return[{id:P001,name:f机械键盘-{keyword}款,price:359,stock:42},{id:P002,name:f薄膜键盘-{keyword}入门,price:89,stock:156},]defget_product_reviews(product_id):reviews{P001:{score:4.7,count:2341,summary:手感好Cherry轴就是有点吵},P002:{score:4.1,count:892,summary:便宜够用适合办公},}returnreviews.get(product_id,{score:0,summary:暂无评价})defcreate_order(product_id,quantity1):return{order_id:ORD20260329001,status:created,product_id:product_id,quantity:quantity}# 函数路由FUNC_MAP{search_products:search_products,get_product_reviews:get_product_reviews,create_order:create_order,}defchat_with_tools(user_input:str):messages[{role:system,content:你是一个电商购物助手帮用户搜索商品、查看评价、下单购买。},{role:user,content:user_input}]max_rounds5# 防止死循环forround_numinrange(max_rounds):responseclient.chat.completions.create(modelclaude-sonnet-4.6,messagesmessages,toolstools,tool_choiceauto)msgresponse.choices[0].message# 没有工具调用说明 Claude 准备好回答了ifnotmsg.tool_calls:returnmsg.content# 有工具调用执行并回传messages.append(msg)fortool_callinmsg.tool_calls:func_nametool_call.function.name func_argsjson.loads(tool_call.function.arguments)print(f [Round{round_num1}] 调用{func_name}({func_args}))resultFUNC_MAP[func_name](**func_args)messages.append({role:tool,tool_call_id:tool_call.id,content:json.dumps(result,ensure_asciiFalse)})return工具调用轮次超限请简化问题# 测试answerchat_with_tools(我想买个键盘打代码用帮我看看有啥推荐的评价好的那种)print(answer)跑起来后Claude 会先调search_products看到结果后自动调get_product_reviews查评价再综合两次结果给出推荐。两轮工具调用全自动。踩坑记录这部分是我花时间最多的地方。坑 1tool_result 的 content 不是字符串直接报错content字段必须是字符串不能直接传 dict。# ❌ 错误写法messages.append({role:tool,tool_call_id:tool_call.id,content:{temp:22}# 这会报 422 错误})# ✅ 正确写法messages.append({role:tool,tool_call_id:tool_call.id,content:json.dumps({temp:22},ensure_asciiFalse)})坑 2工具描述写太简单Claude 不调或者乱调这个坑比较隐蔽。我一开始给get_weather的 description 写的是获取天气三个字。结果 Claude 经常不调这个工具直接瞎编一个天气回答。description 要写清楚三件事这个函数干什么、输入什么、返回什么。参数的 description 也一样别偷懒。# ❌ 太简单description:获取天气# ✅ 写清楚description:获取指定城市的当前天气信息返回温度数字、湿度百分比、天气状况文字描述坑 3忘记把 assistant message 加回 messages这个 bug 特别坑报错信息还不明显。Claude 返回工具调用后必须先把那条 assistant 消息原封不动加回 messages再加 tool result顺序不能乱。# ❌ 漏掉了 assistant messagemessages.append({role:tool,tool_call_id:tool_call.id,content:result_str})# ✅ 先加 assistant再加 tool resultmessages.append(assistant_message)# 这一步不能少messages.append({role:tool,tool_call_id:tool_call.id,content:result_str})坑 4并行工具调用时 tool_call_id 必须一一对应Claude 有时候一次返回多个 tool_calls比如同时查两个城市的天气。每个 tool_result 的tool_call_id必须和对应的 tool_call 匹配搞混了就 400 错误。用上面for tool_call in msg.tool_calls的写法就不会出问题。tool_choice 参数详解这个参数控制 Claude 调不调工具、怎么调值行为适用场景autoClaude 自己决定推荐大多数场景none禁止调工具纯聊天轮次required强制必须调工具你确定这轮一定要调工具{type: function, function: {name: xxx}}强制调指定工具流程编排、测试90% 的时候用auto就够了。只有在做严格的多步骤流程编排时才需要强制指定。小结Claude Tool Use 的核心就是那个请求-调用-回传的循环搞懂这个剩下的都是细节。重点记四条description 要写详细、content 必须是字符串、assistant message 不能漏、循环要设上限防死循环。我现在用的方案是通过 ofox.ai 的聚合接口调 Claude它是一个 AI 模型聚合平台一个 API Key 可以调 Claude Opus 4.6、GPT-5、Gemini 3 等 50 模型低延迟直连支持支付宝付款。换模型不用改代码Claude 的 Tool Use 和 GPT-5 的 Function Calling 用同一套代码就能跑方便对比效果。代码我放 Gist 上了直接 copy 就能跑。有问题评论区见。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2464713.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!