代理 OpenRouter 请求
OpenRouter 提供了一个统一的、OpenAI 兼容的 API,它聚合了来自多个提供商(OpenAI、Anthropic、Google、Mistral 等)的模型 。
本指南展示了如何使用 ai-proxy 插件将 APISIX 与 OpenRouter 集成。将 provider 设置为 openrouter 后,你无需设置自定义端点。
前置条件
获取 OpenRouter API 密钥
按照 OpenRouter 快速入门 创建帐户和 API 密钥。你可以选择将密钥保存到环境变量:
export OPENROUTER_API_KEY=sk-or-v1-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # replace with your API key
创建到 OpenRouter 的路由
创建一个带有 ai-proxy 插件的路由,如下所示:
- Admin API
- ADC
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT -d '{
"id": "openrouter-chat",
"uri": "/anything",
"plugins": {
"ai-proxy": {
"provider": "openrouter",
"auth": {
"header": {
"Authorization": "Bearer '"$OPENROUTER_API_KEY"'"
}
},
"options": {
"model": "deepseek/deepseek-chat"
}
}
}
}'
❶ 将提供商设置为 openrouter。
❷ 使用 Authorization 标头附加 OpenRouter API 密钥。
❸ 设置 OpenRouter 支持的模型,例如 deepseek/deepseek-chat。
adc.yaml
services:
- name: OpenRouter Service
routes:
- uris:
- /anything
name: openrouter-chat
plugins:
ai-proxy:
provider: openrouter
auth:
header:
Authorization: "Bearer ${OPENROUTER_API_KEY}"
options:
model: deepseek/deepseek-chat
❶ 将提供商设置为 openrouter。
❷ 使用 Authorization 标头附加 OpenRouter API 密钥。
❸ 设置 OpenRouter 支持的模型,例如 deepseek/deepseek-chat。
将配置同步到 APISIX:
adc sync -f adc.yaml
验证
向路由发送带有以下提示的请求:
curl "http://127.0.0.1:9080/anything" -X POST \
-H "Content-Type: application/json" \
-d '{
"messages": [
{
"role": "system",
"content": "You are a computer scientist."
},
{
"role": "user",
"content": "Explain in one sentence what a Turing machine is."
}
]
}'
你应该收到类似以下的响应:
{
"id": "gen-1770023173-XYUZ4kUwUAWHwDMPLN20",
"provider": "Novita",
"model": "deepseek/deepseek-chat",
...
"choices": [
{
"logprobs": null,
"finish_reason": "stop",
"native_finish_reason": "stop",
"index": 0,
"message": {
"role": "assistant",
"content": "A Turing machine is a theoretical computational model that manipulates symbols on an infinite tape according to a set of rules, simulating any algorithm's logic and serving as the foundation for modern computability theory.",
"refusal": null,
"reasoning": null
}
}
],
...
}
下一步
你现在已经学会了如何将 APISIX 与 OpenRouter 集成。请参阅 OpenRouter 快速入门 和模型 页面以了解更多详细信息。
如果你想流式传输响应,请在请求中启用流式传输,并使用 proxy-buffering 插件来禁用 NGINX 的 proxy_buffering 指令,以避免缓冲服务器发送事件 (SSE)。