Skip to Content
AnyRouter.cc
文字接口参考

Chat Completions

POST /v1/chat/completions,兼容 OpenAI Chat Completions。

POST https://anyrouter.cc/v1/chat/completions
Authorization: Bearer sk-你的Key
Content-Type: application/json

使用 OpenAI Chat Completions 请求格式接入;模型支持的功能和参数见对应系列指南。DeepSeek、豆包、GPT、Gemini 系列都可用;Claude 请用 Messages。

基本调用

from openai import OpenAI

client = OpenAI(base_url="https://anyrouter.cc/v1", api_key="sk-你的Key")

resp = client.chat.completions.create(
    model="doubao-seed-evolving",
    messages=[
        {"role": "system", "content": "你是一名简洁的助手。"},
        {"role": "user", "content": "用一句话介绍你自己"},
    ],
    max_tokens=2000,
)
print(resp.choices[0].message.content)
print(resp.usage)  # prompt_tokens / completion_tokens / 缓存命中等

常用参数

参数说明
model必填,模型名见模型与价格
messages必填,system / user / assistant / tool 消息
max_tokens / max_completion_tokens输出上限。思考模型的思考 token 也算在里面,开思考时至少给 4000
temperature、top_p采样参数。部分思考模型会忽略
streamtrue 时按 SSE 流式返回
stream_options{"include_usage": true} 让最后一个 chunk 带用量
tools、tool_choice函数调用,写法同 OpenAI
response_format{"type":"json_object"} 或 json_schema,结构化输出
reasoning_effort思考深度:minimal/low/medium/high,各模型支持情况见模型参数

供应商独有参数(例如豆包、DeepSeek 的 thinking)直接放进请求体;用 Python SDK 时放进 extra_body。

流式输出

stream = client.chat.completions.create(
    model="deepseek-flash",
    messages=[{"role": "user", "content": "写一首四行小诗"}],
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices:
        d = chunk.choices[0].delta
        print(getattr(d, "reasoning_content", None) or "", d.content or "", end="", flush=True)

思考模型会先输出 reasoning_content(思考过程),再输出 content(最终答案)。

长输出请用流式

非流式请求要等整段生成完才返回。长思考或长文本可能超过一些客户端、代理的默认超时(常见 60–120 秒),连接被断开后请求仍会计费。生成长内容时请用 stream: true,并把客户端读取超时调到 10 分钟以上。

识图

doubao-seed-*、GPT、Gemini 系列支持图片输入,写法同 OpenAI:

messages=[{"role": "user", "content": [
    {"type": "text", "text": "图里有什么?"},
    {"type": "image_url", "image_url": {"url": "https://你的图片地址.jpg"}},
]}]

url 也可以是 data:image/png;base64,…。deepseek-flash 不支持图片输入。

函数调用

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "查询城市天气",
        "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
    },
}]
resp = client.chat.completions.create(model="deepseek-flash", messages=[{"role": "user", "content": "杭州天气怎么样"}], tools=tools)
print(resp.choices[0].message.tool_calls)

把工具结果作为 {"role": "tool", "tool_call_id": …, "content": …} 追加到 messages 再请求一次。

多轮对话

把上一轮的完整 assistant 消息及后续用户消息追加到 messages。涉及工具调用时,同时保留 tool_calls、相应的工具结果与模型要求的思考字段,不要只复制可见正文。不同上游对思考历史的要求不同,不要统一删除所有 reasoning 字段。

On this page