聊天补全 API 是最常用的接口,支持多轮对话、系统提示、工具调用等。
POST /v1/chat/completions
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 是 | 模型 ID,如 gpt-4o |
messages | array | 是 | 消息数组,包含 role 和 content |
temperature | number | 否 | 采样温度 0-2,默认 1 |
max_tokens | integer | 否 | 最大输出 Token 数 |
top_p | number | 否 | 核采样参数,默认 1 |
stream | boolean | 否 | 是否流式输出,默认 false |
stop | string/array | 否 | 停止序列 |
frequency_penalty | number | 否 | 频率惩罚 -2~2,默认 0 |
presence_penalty | number | 否 | 存在惩罚 -2~2,默认 0 |
tools | array | 否 | 工具/函数定义数组 |
tool_choice | string/object | 否 | 工具选择策略 |
messages = [
{"role": "system", "content": "你是一个有帮助的助手。"},
{"role": "user", "content": "你好!"},
{"role": "assistant", "content": "你好!有什么可以帮你的?"},
{"role": "user", "content": "解释一下量子计算。"}
]
支持的角色:
system - 系统提示,设定助手行为user - 用户消息assistant - 助手回复(用于多轮对话)tool - 工具调用结果response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个 Python 专家。"},
{"role": "user", "content": "写一个快速排序算法。"}
],
temperature=0.7,
max_tokens=1000
)
# 响应结构
print(response.id) # chatcmpl-xxx
print(response.choices[0].message.content) # 助手回复内容
print(response.usage.prompt_tokens) # 输入 Token 数
print(response.usage.completion_tokens) # 输出 Token 数
print(response.usage.total_tokens) # 总 Token 数
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1717000000,
"model": "gpt-4o",
"choices": [{
"index": 0,
"message": {"role": "assistant", "content": "..."},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 25,
"completion_tokens": 150,
"total_tokens": 175
}
}
GPT-4o 等多模态模型支持图像输入:
messages = [{
"role": "user",
"content": [
{"type": "text", "text": "这张图片是什么?"},
{"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
]
}]