OpenAI · 对话补全
发送消息并获取模型回复,支持多轮对话与流式输出。
/v1/chat/completions查看候选模型 ID
没有符合条件的模型。请调整筛选或重置。
| 模型 ID | 厂商 | 类型 | 说明 | 上下文窗口 | 最大输出 Token | 媒体规格 | 价格 | 状态 |
|---|---|---|---|---|---|---|---|---|
gpt-5.4 | OpenAI | 文本 | GPT-5.4是 OpenAI 复杂专业工作的前沿模型。 | — | — | — | — | — |
gpt-5.4-10-07 | OpenAI | 文本 | — | — | — | — | — | — |
gpt-5.5 | OpenAI | 文本 | — | — | — | — | — | — |
o4-mini | OpenAI | 文本 | O4-mini 是OpenAI最新的小型 O 系列型号,它针对快速、有效的推理进行了优化,在编码和视觉任务中具有异常高效的性能。 | — | — | — | — | — |
按公开标签归类,并补充模型广场资料;— 表示暂无明确资料。左右滑动查看完整表格。
Headers请求头
左右滑动查看完整参数表
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 |
|---|---|---|---|---|
Authorization | string | 必填 | 平台 API Key,使用 Bearer 认证。 | |
Content-Type | string | 必填 | 请求体编码格式。 |
Request Body请求体
application/json左右滑动查看完整参数表
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
model | string | 必填 | 模型 ID;请替换为账户可用且支持当前接口的模型。 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
messages | array<object> | 必填 | 按时间顺序排列的对话消息。 | — | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
role | string | 必填 | 消息角色。 可选值 systemuserassistanttooldeveloper | — | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
content | string | array<object> | null | 可选 | 消息文本或多模态内容块。assistant 发出工具调用时可为 null;其他角色须提供与角色匹配的内容。 | — | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
type | string | 必填 | 内容块类型;与下面相应字段配套使用。 可选值 textimage_urlinput_audio | — | |||||||||||||||
text | string | 可选 | type=text 时的文本。 | — | |||||||||||||||
image_url | object | 可选 | type=image_url 时的图片。 | — | |||||||||||||||
| |||||||||||||||||||
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 |
|---|---|---|---|---|
url | string | 必填 | 图片 URL 或 data:image/...;base64,...。 | — |
detail | string | 可选 | 图片处理精度。 可选值 autolowhigh | — |
input_audiotype=input_audio 时的音频。
messages[].content[].input_audio 的子字段 2
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 |
|---|---|---|---|---|
data | string | 必填 | 音频的 Base64 编码内容。 | — |
format | string | 必填 | 编码前的音频格式。 可选值 wavmp3 | — |
name可选的发送者名称。
tool_callsassistant 发起的工具调用。
messages[].tool_calls[] 的子字段 3
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
id | string | 必填 | 工具调用 ID。 | — | |||||||||||||||
type | string | 必填 | 调用类型。 可选值 function | — | |||||||||||||||
function | object | 必填 | 调用的函数与参数。 | — | |||||||||||||||
| |||||||||||||||||||
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 |
|---|---|---|---|---|
name | string | 必填 | 函数名称。 | — |
arguments | string | 必填 | JSON 编码的参数字符串,需在应用端解析。 | — |
tool_call_idrole=tool 时必填,关联对应 assistant 工具调用的 id。
reasoning_content部分推理模型的推理上下文;仅在对应模型要求时回传。
temperature采样温度;支持范围由模型决定。通常与 top_p 二选一调整。
top_p核采样阈值;通常与 temperature 二选一调整。
n每次请求生成的候选回复数量;需模型支持。
stream设为 true 时返回 SSE 事件流。
stream_options仅在 stream=true 时使用的流式选项。
stream_options 的子字段 1
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 |
|---|---|---|---|---|
include_usage | boolean | 可选 | 请求在流结束前返回用量统计。 | — |
stop遇到指定字符串时停止输出;部分推理模型不支持。
max_tokens输出 Token 上限;部分新模型改用 max_completion_tokens。
max_completion_tokens补全 Token 上限;部分模型同时计入可见输出与推理 Token。
presence_penalty按 Token 是否已出现调整生成倾向,通常为 -2 到 2。
frequency_penalty按 Token 出现频率调整生成倾向,通常为 -2 到 2。
logit_biasToken ID 到采样偏置值的映射;需模型支持。
user应用内终端用户标识。
tools允许模型调用的函数工具。
tools[] 的子字段 2
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
type | string | 必填 | 工具类型。 可选值 function | — | |||||||||||||||||||||||||||||||||||||||||||||||||||||||
function | object | 必填 | 函数定义。 | — | |||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 | |||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
name | string | 必填 | 函数名称。 | ||||||||||||||||||||||||||
description | string | 可选 | 函数用途描述。 | — | |||||||||||||||||||||||||
parameters | object | 可选 | 函数输入参数的 JSON Schema。 | — | |||||||||||||||||||||||||
| |||||||||||||||||||||||||||||
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 |
|---|---|---|---|---|
type | string | 必填 | JSON Schema 数据类型。 | |
properties | object | 可选 | 属性名及其 JSON Schema 定义。 | — |
required | array<string> | 可选 | 必填属性名列表。 | — |
additionalProperties | boolean | 可选 | 是否允许未声明的属性;严格模式通常设为 false。 | — |
strict是否启用严格参数结构;需模型支持。
tool_choice工具选择策略:auto、none、required,或指定函数对象;需模型支持。
tool_choice 的子字段 2
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
type | string | 必填 | 指定工具的类型。 可选值 function | — | ||||||||||
function | object | 必填 | 指定使用的函数。 | — | ||||||||||
| ||||||||||||||
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 |
|---|---|---|---|---|
name | string | 必填 | 已在 tools 中声明的函数名。 | — |
parallel_tool_calls是否允许单轮并行发起多个工具调用;需模型支持。
response_format输出格式约束。
response_format 的子字段 2
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 | |||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
type | string | 必填 | 响应格式。 可选值 textjson_objectjson_schema | — | |||||||||||||||||||||||||
json_schema | object | 可选 | type=json_schema 时的结构定义。 | — | |||||||||||||||||||||||||
| |||||||||||||||||||||||||||||
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 |
|---|---|---|---|---|
name | string | 必填 | Schema 名称。 | — |
description | string | 可选 | 结构说明。 | — |
schema | object | 必填 | JSON Schema 定义。 | — |
strict | boolean | 可选 | 是否严格遵循 Schema。 | — |
seed尝试复现采样结果的随机种子,不保证完全确定性。
reasoning_effort推理强度;仅限支持该参数的模型。
lowmediumhighmodalities请求的输出模态,例如 ["text"] 或 ["text", "audio"];需模型支持。
audio请求音频输出时的设置。
audio 的子字段 2
| 参数名 | 类型 | 必填 | 说明 | 默认值 / 示例 |
|---|---|---|---|---|
voice | string | 可选 | 模型支持的音色。 | — |
format | string | 可选 | 输出音频格式。 | — |
logprobs是否返回输出 Token 的对数概率;需模型支持。
top_logprobs每个位置返回的候选 Token 数;需同时启用 logprobs。
使用说明
- 示例为非流式文本对话;多模态、推理、工具和采样参数需所选模型支持。
- stream=true 时响应为 text/event-stream;增量内容通常位于 choices[].delta,最终以 [DONE] 结束。
- 响应示例展示模型回复与用量字段。
流式请求与 SSE 消费
先将 MODEL_ID 替换为账户可用且支持相应能力的模型,并设置环境变量 KEDANG_API_KEY。流式、工具、图像和结构化输出分别依赖模型能力。以下 Python 示例可单独保存运行,API Key 仅在服务端读取。
| 文本增量 | 成功结束 | 异常处理 |
|---|---|---|
| choices[].delta.content | [DONE] | HTTP 错误、error 事件、截断或缺少结束标记均停止处理 |
SSE 以空行分帧,多行 data: 用换行连接;不能把任意网络分块直接当作 JSON。示例读取文本增量;流式工具参数需要按调用 ID 或内容块索引累积后再解析,下面的工具示例采用非流式两步调用。
展开 Python:请求、解析事件与处理结束状态
# 安装依赖:python -m pip install requests
import base64
import json
import os
from pathlib import Path
from urllib.parse import quote
import requests
BASE_URL = "https://ai.kedang.net"
MODEL_ID = "MODEL_ID" # 替换为账户可用、支持当前能力的模型
def request_json(path, body, extra_headers=None):
headers = {"Authorization": "Bearer " + os.environ["KEDANG_API_KEY"]}
headers.update(extra_headers or {})
response = requests.post(BASE_URL + path, headers=headers, json=body, timeout=120)
response.raise_for_status()
result = response.json()
if result.get("error"):
raise RuntimeError(result["error"])
return result
def sse_lines(chunks):
"""增量解码 UTF-8,并跨网络分块正确识别 LF、CR 和 CRLF。"""
import codecs
decoder = codecs.getincrementaldecoder("utf-8")()
line, skip_lf = [], False
for chunk in chunks:
for char in decoder.decode(chunk):
if skip_lf:
skip_lf = False
if char == "\n":
continue
if char in ("\r", "\n"):
yield "".join(line)
line = []
skip_lf = char == "\r"
else:
line.append(char)
decoder.decode(b"", final=True) # 不接受 EOF 处截断的 UTF-8 字符。
if line:
yield "".join(line)
def iter_sse(lines):
"""只在空行处派发完整 SSE 帧。"""
event, data_lines = "message", []
first_line = True
for line in lines:
if first_line:
line = line.removeprefix("\ufeff")
first_line = False
if line == "":
if data_lines:
yield event, "\n".join(data_lines)
event, data_lines = "message", []
continue
if line.startswith(":"):
continue # 心跳或注释
field, separator, value = line.partition(":")
if separator and value.startswith(" "):
value = value[1:]
if field == "event":
event = value or "message"
elif field == "data":
data_lines.append(value)
# EOF 前没有空行的半帧不能当作完整事件;由下层检查终止事件。
def stream_text(events):
completed = False
for event, data in events:
if data.strip() == "[DONE]":
completed = True
break
item = json.loads(data)
if event == "error" or item.get("error"):
raise RuntimeError(item)
for choice in item.get("choices", []):
reason = choice.get("finish_reason")
if reason in ("length", "content_filter"):
raise RuntimeError("输出未完整完成:" + reason)
delta = choice.get("delta", {})
if delta.get("refusal"):
raise RuntimeError(delta["refusal"])
text = delta.get("content")
if isinstance(text, str):
yield text
# usage 帧的 choices 可为空;finish_reason 后继续等 [DONE]。
if not completed:
raise RuntimeError("连接在 [DONE] 前结束,请保留已收内容并检查状态。")
def main():
path = "/v1/chat/completions"
body = {"model": MODEL_ID, "messages": [{"role": "user", "content": "用三句话介绍杭州。"}], "stream": True}
headers = {"Authorization": "Bearer " + os.environ["KEDANG_API_KEY"],
"Accept": "text/event-stream"}
headers.update({})
with requests.post(BASE_URL + path, headers=headers, json=body,
stream=True, timeout=(10, 120)) as response:
response.raise_for_status()
if "text/event-stream" not in response.headers.get("Content-Type", ""):
raise RuntimeError("预期 SSE,请检查返回的 Content-Type 和错误信息。")
events = iter_sse(sse_lines(response.iter_content(chunk_size=128)))
for text in stream_text(events):
print(text, end="", flush=True)
print()
if __name__ == "__main__":
main()工具调用:返回结果后继续回答
第一步让模型提出工具调用,应用校验参数并执行本地函数;第二步将每个结果和原始调用上下文一起发回。示例只允许调用本地加法函数,第二轮关闭工具,避免无界循环。实际业务需自行设置允许执行的工具与轮次上限。
| 结果关联字段 | 本地工具 | 回传内容 |
|---|---|---|
| messages[].tool_call_id | add_numbers(a, b) | JSON 对象 {"sum": 5} |
展开 Python:完整两步工具调用
# 安装依赖:python -m pip install requests
import base64
import json
import os
from pathlib import Path
from urllib.parse import quote
import requests
BASE_URL = "https://ai.kedang.net"
MODEL_ID = "MODEL_ID" # 替换为账户可用、支持当前能力的模型
def request_json(path, body, extra_headers=None):
headers = {"Authorization": "Bearer " + os.environ["KEDANG_API_KEY"]}
headers.update(extra_headers or {})
response = requests.post(BASE_URL + path, headers=headers, json=body, timeout=120)
response.raise_for_status()
result = response.json()
if result.get("error"):
raise RuntimeError(result["error"])
return result
PARAMETERS = {
"type": "object",
"properties": {"a": {"type": "number"}, "b": {"type": "number"}},
"required": ["a", "b"],
"additionalProperties": False,
}
def run_tool(name, args):
# 工具名和参数都先校验;只执行应用主动注册的函数。
if name != "add_numbers" or not isinstance(args, dict) or set(args) != {"a", "b"}:
raise ValueError("未知工具或参数不匹配")
if any(type(args[key]) not in (int, float) for key in ("a", "b")):
raise ValueError("a 和 b 必须为数字")
return {"sum": args["a"] + args["b"]}
def main():
tools = [{"type": "function", "function": {
"name": "add_numbers", "description": "计算两个数字之和", "parameters": PARAMETERS}}]
messages = [{"role": "user", "content": "请用工具计算 2 加 3。"}]
first = request_json("/v1/chat/completions", {
"model": MODEL_ID, "messages": messages, "tools": tools, "tool_choice": "auto"})
assistant = first["choices"][0]["message"]
calls = assistant.get("tool_calls", [])
if not calls:
print(assistant.get("content", ""))
return
messages.append(assistant) # 保留整条消息、调用 ID 及模型返回的附加上下文。
for call in calls:
function = call["function"]
result = run_tool(function["name"], json.loads(function["arguments"]))
messages.append({"role": "tool", "tool_call_id": call["id"],
"content": json.dumps(result, ensure_ascii=False)})
second = request_json("/v1/chat/completions", {
"model": MODEL_ID, "messages": messages, "tools": tools, "tool_choice": "none"})
print(second["choices"][0]["message"].get("content", ""))
if __name__ == "__main__":
main()图片输入
示例读取本地 input.png。文件格式与 MIME 类型必须一致;图片数量、大小和支持格式以所选模型为准。这里展示图片理解输入,生成图片请使用图像生成接口。
展开 Python:发送本地 PNG 图片
# 安装依赖:python -m pip install requests
import base64
import json
import os
from pathlib import Path
from urllib.parse import quote
import requests
BASE_URL = "https://ai.kedang.net"
MODEL_ID = "MODEL_ID" # 替换为账户可用、支持当前能力的模型
def request_json(path, body, extra_headers=None):
headers = {"Authorization": "Bearer " + os.environ["KEDANG_API_KEY"]}
headers.update(extra_headers or {})
response = requests.post(BASE_URL + path, headers=headers, json=body, timeout=120)
response.raise_for_status()
result = response.json()
if result.get("error"):
raise RuntimeError(result["error"])
return result
def main():
image = base64.b64encode(Path("input.png").read_bytes()).decode("ascii")
result = request_json("/v1/chat/completions", {"model": MODEL_ID, "messages": [
{"role": "user", "content": [
{"type": "text", "text": "请描述这张图片。"},
{"type": "image_url", "image_url": {"url": "data:image/png;base64," + image}}
]}]})
print(result["choices"][0]["message"].get("content", ""))
if __name__ == "__main__":
main()结构化输出
只有支持所选格式约束的模型才能使用此示例;普通 JSON 模式与严格 JSON Schema 的约束强度不同。 输出仍需处理拒绝、截断和字段类型错误。
| 当前协议字段 | 应用侧校验 |
|---|---|
| response_format.json_schema | city 为字符串,days 为整数;仅接受完整返回结果 |
展开 Python:提取 JSON 对象并校验
# 安装依赖:python -m pip install requests
import base64
import json
import os
from pathlib import Path
from urllib.parse import quote
import requests
BASE_URL = "https://ai.kedang.net"
MODEL_ID = "MODEL_ID" # 替换为账户可用、支持当前能力的模型
def request_json(path, body, extra_headers=None):
headers = {"Authorization": "Bearer " + os.environ["KEDANG_API_KEY"]}
headers.update(extra_headers or {})
response = requests.post(BASE_URL + path, headers=headers, json=body, timeout=120)
response.raise_for_status()
result = response.json()
if result.get("error"):
raise RuntimeError(result["error"])
return result
SCHEMA = {
"type": "object",
"properties": {"city": {"type": "string"}, "days": {"type": "integer"}},
"required": ["city", "days"],
"additionalProperties": False,
}
def check_trip(value):
# 业务侧仍校验结果,尤其要区分拒绝、截断和有效 JSON。
if not isinstance(value, dict) or set(value) != {"city", "days"}:
raise ValueError("返回对象不匹配 Schema")
if not isinstance(value["city"], str) or type(value["days"]) is not int:
raise ValueError("字段类型不匹配 Schema")
return value
def main():
result = request_json("/v1/chat/completions", {"model": MODEL_ID,
"messages": [{"role": "user", "content": "提取旅行信息:杭州,3 天。"}],
"response_format": {"type": "json_schema", "json_schema": {
"name": "trip", "strict": True, "schema": SCHEMA}}})
choice = result["choices"][0]
message = choice["message"]
if message.get("refusal") or choice.get("finish_reason") != "stop":
raise RuntimeError("未得到完整结构化结果")
print(check_trip(json.loads(message["content"])))
if __name__ == "__main__":
main()