聊天(Chat Completions)
对话补全是最常用的接口,适用于对话、问答、代码生成、工具调用等场景。
创建对话补全
POST /v1/chat/completions请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 是 | 模型标识,如 gpt-4o-mini |
messages | array | 是 | 对话消息列表,见下方 |
stream | boolean | 否 | 是否流式返回,默认 false |
temperature | number | 否 | 采样温度,0~2,默认 1 |
top_p | number | 否 | 核采样,默认 1 |
max_tokens | integer | 否 | 生成的最大 Token 数 |
stop | string | array | 否 | 停止词 |
tools | array | 否 | 可调用的工具(函数)定义 |
tool_choice | string | object | 否 | 工具选择策略 |
response_format | object | 否 | 如 { "type": "json_object" } |
messages 结构
每条消息包含 role 与 content:
role:system/user/assistant/toolcontent:字符串,或多模态内容数组(文本 + 图像)
基础请求
bash
curl https://ai.youqi.tech/v1/chat/completions \
-H "Authorization: Bearer sk-YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{ "role": "system", "content": "你是一个乐于助人的助手。" },
{ "role": "user", "content": "用一句话介绍杭州。" }
]
}'响应示例
json
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1715367049,
"model": "gpt-4o-mini",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "杭州是一座以西湖闻名、兼具历史底蕴与数字经济活力的城市。"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 26,
"completion_tokens": 22,
"total_tokens": 48
}
}流式输出(SSE)
在请求体中加入 "stream": true,服务端会以 SSE 逐块返回增量内容,最后以 data: [DONE] 结束。
bash
curl https://ai.youqi.tech/v1/chat/completions \
-H "Authorization: Bearer sk-YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o-mini",
"stream": true,
"messages": [{ "role": "user", "content": "写一首关于秋天的短诗" }]
}'每个数据块形如:
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"秋"},"finish_reason":null}]}多模态输入(图像)
支持视觉能力的模型可在 content 中混合文本与图像:
json
{
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": [
{ "type": "text", "text": "这张图片里有什么?" },
{
"type": "image_url",
"image_url": { "url": "https://example.com/photo.jpg" }
}
]
}
]
}工具调用(Function Calling)
json
{
"model": "gpt-4o-mini",
"messages": [{ "role": "user", "content": "北京今天天气怎么样?" }],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询指定城市的天气",
"parameters": {
"type": "object",
"properties": { "city": { "type": "string" } },
"required": ["city"]
}
}
}
]
}当模型决定调用工具时,响应的 finish_reason 为 tool_calls,并在 message.tool_calls 中返回调用参数;你执行后将结果以 role: "tool" 的消息回传,继续下一轮对话。
提示
不同模型对 tools、response_format、多模态等能力的支持程度不同。若某模型不支持某参数,网关会透传上游的行为或返回相应错误。