龙虾-OpenClaw一文详细了解-手搓OpenClaw-4.0 Tool Runtime
本文以 OpenAI 风格的工具调用举例说明“工具调用Tool Calling”的协议约定。1. 核心概念tools你提供给模型可调用的工具列表最常见是function类型。tool_choice控制模型是否/如何调用工具auto/none/required/ 指定某个工具。tool_calls模型决定调用工具时在响应中返回的调用指令函数名 参数 JSON。tool消息客户端执行工具后把结果作为roletool回传给模型。2. 请求格式你发给模型典型请求字段model: 模型名messages: 对话消息数组system/user/assistant/tooltools: 工具定义数组tool_choice: 工具策略默认常用auto2.1 tools 定义function{type:function,function:{name:get_weather,description:查询城市天气,parameters:{type:object,properties:{city:{type:string,description:城市名称如 Beijing},unit:{type:string,enum:[celsius,fahrenheit]}},required:[city],additionalProperties:false}}}说明name使用稳定、可读、无空格命名。parameters模型会按它生成参数。additionalProperties: false可减少模型多传无关字段,默认为true.2.2 tool_choice 值auto模型自行决定“直接回答”或“调用工具”。none禁止工具调用。required必须调用至少一个工具。指定工具强制某个函数tool_choice:{type:function,function:{name:get_weather}}2.3 一次完整请求示例{model:gpt-4.1,messages:[{role:system,content:你是一个天气助手},{role:user,content:北京现在天气怎么样}],tools:[{type:function,function:{name:get_weather,description:查询城市天气,parameters:{type:object,properties:{city:{type:string},unit:{type:string,enum:[celsius,fahrenheit]}},required:[city],additionalProperties:false}}}],tool_choice:auto}3. 返回格式模型回给你3.1 不调用工具时通常是普通 assistant 文本{choices:[{message:{role:assistant,content:今天天气晴约 20°C。},finish_reason:stop}]}3.2 调用工具时模型不会直接给最终答案而是给tool_calls{choices:[{message:{role:assistant,content:null,tool_calls:[{id:call_123,type:function,function:{name:get_weather,arguments:{\city\:\Beijing\,\unit\:\celsius\}}}]},finish_reason:tool_calls}]}关键点function.arguments常见是 JSON 字符串客户端需要json.loads后校验。finish_reason常见为tool_calls表示这轮在请求你执行工具。4. 客户端协议循环标准循环如下发起请求含messages tools tool_choice。若响应含tool_calls逐个解析参数并执行本地工具函数。把每个工具执行结果作为roletool消息追加到messages。再次请求模型让模型基于工具结果生成最终回答。若无tool_calls直接把 assistant 文本返回给用户。4.1 tool 回传消息格式{role:tool,tool_call_id:call_123,content:{\temp\:20,\condition\:\Sunny\}}说明tool_call_id必须对应模型返回的tool_calls[i].id。content通常是字符串可放 JSON 字符串。5. 完整多轮示例第 1 轮用户提问[{role:system,content:你是天气助手},{role:user,content:北京天气}]模型返回要求调用工具{role:assistant,content:null,tool_calls:[{id:call_123,type:function,function:{name:get_weather,arguments:{\city\:\Beijing\}}}]}客户端执行工具后追加消息[{role:assistant,content:null,tool_calls:[{id:call_123,type:function,function:{name:get_weather,arguments:{\city\:\Beijing\}}}]},{role:tool,tool_call_id:call_123,content:{\temp\:20,\condition\:\Sunny\}}]第 2 轮模型产出最终答案{role:assistant,content:北京当前晴约 20°C。}6. OpenAI 官方原始资料链接Function calling 指南https://platform.openai.com/docs/guides/function-callingChat Completions APItools/tool_choice所在接口https://platform.openai.com/docs/api-reference/chat/createResponses APIhttps://platform.openai.com/docs/api-reference/responses/createOpenAI 官方文档https://platform.openai.com/docs/overview