OpenAI API 的工具定义、工具调用和结果怎么配对?
查看完整题解
参考回答
直接回答
在工具列表里说明函数名、用途和参数 Schema。Chat Completions 返回工具调用后,应用检查并执行获准操作,把原助手消息和带相同 tool_call_id 的工具结果交给下一次调用。
讲清原理
Responses 的类型名称和回传形式有所不同,通常识别 function_call 并用对应的 function_call_output 和 call_id。不要混用两个接口的字段。工具登记与参数校验应在每次调用都执行。
例子与易错点
示例用一份只读库存字典演示请求、执行和回传。即使模型可以提出多次调用,应用也要控制次数,不让任意函数名或参数执行。
import json
import httpx
from openai import OpenAI
model = "gpt-6.2-astra"
tools = [{"type": "function", "function": {
"name": "stock", "description": "Read the inventory count for a SKU.",
"parameters": {"type": "object", "properties": {"sku": {"type": "string"}},
"required": ["sku"], "additionalProperties": False},
"strict": True,
}}]
inventory_for_user = {"M1": 7}
def model_reply(request):
sent = json.loads(request.content)
assert sent["tools"] == tools
if len(sent["messages"]) == 1:
answer = {"role": "assistant", "content": None, "tool_calls": [{
"id": "call_demo", "type": "function",
"function": {"name": "stock", "arguments": '{"sku":"M1"}'},
}]}
reason = "tool_calls"
else:
assistant, tool = sent["messages"][-2:]
assert assistant["tool_calls"][0]["id"] == tool["tool_call_id"] == "call_demo"
assert tool["role"] == "tool" and json.loads(tool["content"]) == {"count": 7}
answer, reason = {"role": "assistant", "content": "7 in stock"}, "stop"
return httpx.Response(200, json={
"id": "chat-fixture", "object": "chat.completion", "created": 0, "model": model,
"choices": [{"index": 0, "finish_reason": reason, "message": answer}],
})
messages = [{"role": "user", "content": "How many M1 are in stock?"}]
with OpenAI(api_key="fixture", base_url="https://fixture.invalid/v1",
http_client=httpx.Client(transport=httpx.MockTransport(model_reply))) as client:
message = client.chat.completions.create(
model=model, messages=messages, tools=tools,
).choices[0].message
assert len(message.tool_calls) == 1
call = message.tool_calls[0]
assert call.type == "function" and call.function.name == "stock"
args = json.loads(call.function.arguments)
assert isinstance(args, dict) and set(args) == {"sku"}
sku = args["sku"]
assert isinstance(sku, str) and sku in inventory_for_user
messages += [{"role": "assistant", "tool_calls": [call.model_dump(exclude_none=True)]},
{"role": "tool", "tool_call_id": call.id,
"content": json.dumps({"count": inventory_for_user[sku]})}]
final = client.chat.completions.create(model=model, messages=messages, tools=tools)
assert final.choices[0].finish_reason == "stop"
print(final.choices[0].message.content)
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。