POST
Chat(工具tools调用)
POST /v1/chat/completions — 函数/工具调用
Chat(工具tools调用)
让模型调用您定义的函数(Function Calling),实现 AI Agent 能力。
接口信息
| HTTP 方法 | POST |
| 接口路径 | /v1/chat/completions |
| 认证 | Bearer Token |
请求示例
from openai import OpenAI
import json
client = OpenAI(
base_url="https://api000.com/v1",
api_key="sk-xxxxxxxxxxxxxxxx"
)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的当前天气",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称,如 '北京'"
}
},
"required": ["city"]
}
}
}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
tools=tools,
tool_choice="auto"
)
message = response.choices[0].message
if message.tool_calls:
tool_call = message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
print(f"调用函数: {tool_call.function.name}")
print(f"参数: {args}")
工具调用响应
{
"id": "chatcmpl-abc123",
"choices": [
{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_xyz",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\": \"北京\"}"
}
}
]
},
"finish_reason": "tool_calls"
}
]
}
tool_choice 参数
| 值 | 说明 |
|---|---|
"auto" |
模型自动决定是否调用工具(默认) |
"none" |
禁止调用工具 |
"required" |
强制调用至少一个工具 |
{"type": "function", "function": {"name": "xxx"}} |
强制调用指定函数 |