对话补全
POST /v1/chat/completions
OpenAI 协议的主接口。绝大多数应用只需要这一个端点。
请求头
Authorization: Bearer ***
Content-Type: application/json
请求体
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 是 | 模型名,见 模型列表 |
messages | array | 是 | 消息数组,见下 |
max_tokens | integer | 否 | 输出上限 |
temperature | number | 否 | 采样温度 |
top_p | number | 否 | 核采样 |
stream | boolean | 否 | true 返回 SSE |
stop | string/array | 否 | 停止序列 |
tools | array | 否 | 工具定义 |
tool_choice | string/object | 否 | 工具选择策略 |
response_format | object | 否 | 如 {"type":"json_object"} |
user | string | 否 | 终端用户标识(便于审计) |
messages 结构
[
{"role": "system", "content": "你是简洁的助手。"},
{"role": "user", "content": "你好"},
{"role": "assistant", "content": "你好,有什么可以帮你?"},
{"role": "user", "content": "介绍一下你自己"}
]
多模态内容用数组:
{
"role": "user",
"content": [
{"type": "text", "text": "这张图里是什么?"},
{"type": "image_url", "image_url": {"url": "https://example.com/a.png"}}
]
}
最小请求
curl https://187api.com/v1/chat/completions \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"model": "MiniMax-M2.5",
"messages": [{"role": "user", "content": "你好"}],
"max_tokens": 128
}'
非流式响应
{
"id": "chatcmpl-xxx",
"object": "chat.completion",
"created": 1793532000,
"model": "MiniMax-M2.5",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "你好!"},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 12,
"completion_tokens": 5,
"total_tokens": 17
}
}
:::info usage 里的缓存字段
启用缓存后,usage 里会出现缓存相关字段(如 prompt_tokens_details.cached_tokens)。
这是上游返回的真实用量,也是计费的依据。
:::
流式响应
请求体加 "stream": true:
curl -N https://187api.com/v1/chat/completions \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{"model":"MiniMax-M2.5","messages":[{"role":"user","content":"你好"}],"stream":true}'
data: {"choices":[{"delta":{"role":"assistant"},"index":0}]}
data: {"choices":[{"delta":{"content":"你"},"index":0}]}
data: {"choices":[{"delta":{"content":"好"},"index":0}]}
data: {"choices":[{"delta":{},"finish_reason":"stop","index":0}]}
data: [DONE]
工具调用
{
"model": "MiniMax-M2.5",
"messages": [{"role": "user", "content": "北京今天天气?"}],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询城市天气",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
}
],
"tool_choice": "auto"
}
模型返回 finish_reason: "tool_calls" 时,把 tool_calls 结果按
{"role":"tool","tool_call_id":"...","content":"..."} 追加回 messages 再请求一次。
常见错误
| 错误 | 原因 |
|---|---|
model not found | 分组里没有该模型,或模型名拼错 |
insufficient quota | 令牌额度或余额不足 |
context length exceeded | 输入超过模型上下文窗口 |
rate limit | 触发限流 |