聊天补全 (Python)

向 chat.completions.create 传入按顺序排列的消息。结果包含 choices;返回 usage 时可查看 token 用量。

本指南使用 OpenAI 官方客户端连接 TheRouter;它不是 TheRouter 自有 SDK。旧文档所述的 therouter 和 @therouter/sdk 包目前未在公开包仓库发布。

安装并运行

bash
pip install openai

在服务端设置 THEROUTER_API_KEY 后运行:

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["THEROUTER_API_KEY"], base_url="https://api.therouter.ai/v1")
completion = client.chat.completions.create(
    model="openai/gpt-4o-mini",
    messages=[{"role": "user", "content": "Hello!"}],
    max_tokens=32,
)
print(completion.choices[0].message.content)

相关资源

帮助与联系