Appearance
OpenRouter Python SDK(openrouter 包)是官方提供的 Python 客户端,处于 beta 阶段。基于 OpenAPI spec 自动生成,提供 Pydantic 类型验证和清晰报错信息,支持同步 client.chat.send()、异步 client.chat.send_async()、流式输出。使用 with OpenRouter(...) as client 上下文管理器管理连接,支持 Python 3.9+,推荐用 uv 安装。
Beta:Python SDK 及文档处于 beta 阶段,如遇问题请在 GitHub 提 issue。
OpenRouter Python SDK 提供类型安全的接口,用一行代码调用 300+ 语言模型。
安装
bash
# 推荐:uv
uv add openrouter
# pip
pip install openrouter
# poetry
poetry add openrouter要求:Python 3.9 或更高版本。
从 openrouter.ai/settings/keys 获取 API key。
快速示例
python
from openrouter import OpenRouter
import os
with OpenRouter(
api_key=os.getenv("OPENROUTER_API_KEY")
) as client:
response = client.chat.send(
model="openai/gpt-4o",
messages=[
{"role": "user", "content": "Hello!"}
]
)
print(response.choices[0].message.content)核心特性
自动同步 API 变更
SDK 从 OpenRouter OpenAPI spec 自动生成。新模型、参数、接口在每次 API 更新后立即可用,IDE 自动补全实时跟进,无需手动升级。
Pydantic 类型验证
每个参数、响应字段、配置选项都有完整的 Python type hint,由 Pydantic 在运行时验证:
python
response = client.chat.send(
model="openai/gpt-4o",
messages=[
{"role": "user", "content": "Hello"} # Pydantic 验证消息结构
],
temperature=0.7, # 类型检查并验证
stream=True # 响应类型随此参数变化
)错误信息清晰可操作,例如:
"Model 'openai/o1-preview' requires at least 2 messages. You provided 1 message."
Streaming 流式输出
python
stream = client.chat.send(
model="openai/gpt-4o",
messages=[{"role": "user", "content": "Write a story"}],
stream=True
)
for event in stream:
content = event.choices[0].delta.content if event.choices else None
if content:
print(content, end="", flush=True)异步支持
python
import asyncio
from openrouter import OpenRouter
import os
async def main():
async with OpenRouter(
api_key=os.getenv("OPENROUTER_API_KEY")
) as client:
response = await client.chat.send_async(
model="openai/gpt-4o",
messages=[{"role": "user", "content": "Hello"}]
)
print(response.choices[0].message.content)
asyncio.run(main())Python SDK vs TypeScript SDK
| Python SDK | TypeScript SDK | |
|---|---|---|
| 验证方式 | Pydantic(运行时) | TypeScript(编译时) |
| 异步 | send_async() | await send() |
| 上下文管理 | with / async with | 直接使用 |
| Agent SDK | 暂无 | @openrouter/agent |
常见问题
Q: Python SDK 是否支持 Agent 功能(多轮循环、工具调用)?
A: 目前 Agent SDK 只有 TypeScript 版本(@openrouter/agent)。Python SDK 主要覆盖直接 API 调用场景(chat、streaming、embeddings)。如果需要在 Python 中实现 agent 循环,需要自行管理对话状态。
Q: with 语法是必须的吗?
A: 推荐使用 with OpenRouter(...) as client 上下文管理器,确保连接被正确释放。异步场景用 async with。
Q: 如何报告 beta 阶段的问题?
A: 在 GitHub 仓库 OpenRouterTeam/python-sdk 的 Issues 中反馈。