接入 Anthropic Claude
Anthropic 通过 API 提供 Claude 模型。本指南介绍如何使用 ai-proxy 插件,通过 API7 网关将流量路由到 Anthropic。
前置条件
-
安装 Docker。
-
安装 cURL,用于发送请求并验证服务。
-
拥有一个正在运行的 API7 网关实例。
-
从控制台获取令牌,并将其保存到环境变量:
export API_KEY=your-dashboard-token # 请替换为你的控制台令牌 -
将
{gateway_group_id}替换为网关组 ID。如果正在按照快速入门 操作,请使用default。 -
如果使用 Admin API 示例,请在 API7 网关中创建或复用一个服务。如果尚无服务,请按照创建或复用服务操作,然后将其 ID 保存到环境变量:
export SERVICE_ID=your-service-id # 请替换为你的服务 ID
获取 Anthropic API Key(API 密钥)
按照 Anthropic API 文档创建账户和 API Key,并将 API Key 保存到环境变量:
export ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxxxxx # 请替换为你的 Anthropic API Key
为 Anthropic 配置 AI 代理
创建一个启用 ai-proxy 插件的路由:
- Admin API
- ADC
curl -k "https://localhost:7443/apisix/admin/routes?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
--data-binary @- <<EOF
{
"id": "anthropic-route",
"service_id": "$SERVICE_ID",
"paths": ["/anthropic"],
"plugins": {
"ai-proxy": {
"provider": "anthropic",
"auth": {
"header": {
"Authorization": "Bearer $ANTHROPIC_API_KEY"
}
},
"options": {
"model": "claude-sonnet-4-20250514"
}
}
}
}
EOF
❶ 将服务提供方设置为 anthropic。
❷ 使用 Authorization 请求头附加 Anthropic API Key。
❸ 将模型设置为 claude-sonnet-4-20250514。可用模型请参阅 Anthropic 模型页面。
services:
- name: Anthropic Service
routes:
- uris:
- /anthropic
name: anthropic-route
plugins:
ai-proxy:
provider: anthropic
auth:
header:
Authorization: "Bearer ${ANTHROPIC_API_KEY}"
options:
model: claude-sonnet-4-20250514
❶ 将服务提供方设置为 anthropic。
❷ 使用 Authorization 请求头附加 Anthropic API Key。
❸ 将模型设置为 claude-sonnet-4-20250514。可用模型请参阅 Anthropic 模型页面。
将配置同步到 API7 网关:
adc sync -f adc.yaml
验证配置
发送聊天补全请求:
curl "http://127.0.0.1:9080/anthropic" -X POST \
-H "Content-Type: application/json" \
-d '{
"messages": [
{ "role": "user", "content": "What is the capital of France?" }
]
}'
你应收到类似以下内容的响应:
{
"id": "msg_01abc123",
"object": "chat.completion",
"model": "claude-sonnet-4-20250514",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "The capital of France is Paris."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 12,
"completion_tokens": 8,
"total_tokens": 20
}
}
无论后端服务提供方使用哪种格式,API7 网关都会将所有大语言模型响应规范化为 OpenAI 聊天补全格式,客户端始终收到一致的响应结构。如需使用 Anthropic 原生协议,请参阅协议转换。
要启用流式响应,请在请求体中设置 "stream": true。使用 proxy-buffering 插件禁用 NGINX proxy_buffering,避免服务器发送事件(SSE)被缓冲。
后续步骤
你已经了解如何通过 API7 网关将流量路由到 Anthropic。更多信息请参阅 Anthropic API 文档和模型页面。
- 协 议转换 — 使用 Anthropic 原生协议访问任意后端服务提供方,或将 Anthropic 请求路由到 OpenAI。
- 多模型路由和故障转移 — 将 Anthropic 与其他服务提供方组合,实现故障转移。