跳到主要内容

Chat Completions

OpenAI 兼容的聊天补全接口,支持流式输出、函数调用、结构化输出和视觉理解。

POST /v1/chat/completions

请求示例

curl https://gw.opentoken.io/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPEN_TOKEN_KEY" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "你是资深 Python 工程师。"},
{"role": "user", "content": "解释装饰器的工作原理。"}
],
"temperature": 0.7,
"max_tokens": 500
}'

流式输出

在请求中添加 "stream": true 启用 SSE 流式输出。

curl -N https://gw.opentoken.io/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPEN_TOKEN_KEY" \
-d '{
"model": "gpt-4o",
"messages": [{"role": "user", "content": "写一首关于 AI 的诗"}],
"stream": true
}'

请求参数

参数类型必填默认值描述
modelstring-模型 ID,例如 gpt-4o
messagesarray-对话消息数组,每条含 rolecontent
temperaturenumber1.0采样温度,用于控制生成过程中的随机性。较低的值通常会使输出更稳定、可预测;较高的值通常会增加输出的多样性。
max_tokensinteger-限制本次响应可生成的最大 token 数;实际输出长度可能因停止条件、上下文长度或模型限制而更短。
top_pnumber1.0核采样参数,用于将每一步采样限制在累计概率达到 top_p 的候选集合内。
frequency_penaltynumber0.0频率惩罚,用于降低模型重复生成高频内容的倾向。
presence_penaltynumber0.0存在惩罚,用于提高模型引入新主题或新词汇的倾向。
stopstring / array-停止序列,触发后停止生成
streambooleanfalse启用 SSE 流式输出
response_formatobject-结构化输出格式:json_objectjson_schema
toolsarray-工具定义数组,用于 Function Calling

Function Calling(函数调用)

通过 tools 参数定义函数,使模型能够结构化地请求调用外部工具。

{
"model": "gpt-4o",
"messages": [{"role": "user", "content": "北京今天天气怎么样?"}],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": { "type": "string", "description": "城市名称" }
},
"required": ["city"]
}
}
}
]
}

Structured Outputs(结构化输出)

使用 response_format 强制模型返回结构化 JSON:

  • JSON 模式{"type": "json_object"} — 确保输出为有效 JSON
  • JSON Schema{"type": "json_schema", "json_schema": {...}} — 按指定 schema 输出
{
"model": "gpt-4o",
"messages": [{"role": "user", "content": "列出 3 种水果及颜色"}],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "fruits",
"schema": {
"type": "object",
"properties": {
"fruits": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"color": { "type": "string" }
},
"required": ["name", "color"]
}
}
}
}
}
}
}

响应结构

{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1717800000,
"model": "gpt-4o",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "装饰器是 Python 中的一种设计模式..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 30,
"completion_tokens": 120,
"total_tokens": 150
}
}

流式响应结构

{
"id": "chatcmpl-abc123",
"object": "chat.completion.chunk",
"created": 1717800000,
"model": "gpt-4o",
"choices": [
{
"index": 0,
"delta": {
"content": "装饰"
},
"finish_reason": null
}
]
}
Copyright © 2026 OpenToken.