📖 API 接口说明
🔌 支持的对外接口
两种格式都支持:无论上游是 OpenAI 还是 Anthropic,客户端都可以选择使用 OpenAI 格式或 Anthropic 格式调用。系统会自动转换请求和响应格式。
| 接口格式 | 端点路径 | 认证方式 |
|---|---|---|
| OpenAI | /v1/chat/completions 或 /v1/responses |
Authorization: Bearer <key> |
| Anthropic | /v1/messages |
x-api-key: <key> |
📡 OpenAI 格式调用示例
Bash / cURL
# 调用 /v1/chat/completions 端点 curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "model": "qwen-turbo", "messages": [ {"role": "user", "content": "你好"} ], "stream": false }' # 调用 /v1/responses 端点(OpenAI Responses API) curl -X POST "http://localhost:8000/v1/responses" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "model": "qwen-turbo", "messages": [{"role": "user", "content": "你好"}] }'
Python
from openai import OpenAI client = OpenAI( base_url="http://localhost:8000/v1", api_key="YOUR_API_KEY" ) response = client.chat.completions.create( model="qwen-turbo", messages=[{"role": "user", "content": "你好"}] ) print(response.choices[0].message.content)
🤖 Anthropic 格式调用示例
注意:Anthropic API 要求
max_tokens 参数必填。如果不提供,中转服务会使用默认值 4096。
Bash / cURL
# 使用 Anthropic 格式调用(适用于任意上游) curl -X POST "http://localhost:8000/v1/messages" \ -H "Content-Type: application/json" \ -H "x-api-key: YOUR_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -d '{ "model": "claude-3-5-sonnet-20241022", "max_tokens": 1024, "system": "你是助手", "messages": [ {"role": "user", "content": "你好"} ] }'
Python
from anthropic import Anthropic # 使用 Anthropic SDK 直接调用中转服务 client = Anthropic( base_url="http://localhost:8000", api_key="YOUR_API_KEY" ) message = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1024, system="你是助手", messages=[{"role": "user", "content": "你好"}] ) print(message.content[0].text)
🎯 指定上游 Provider
默认情况下,请求会路由到默认上游。可以通过以下方式指定特定上游:
| 方式 | 说明 | 示例 |
|---|---|---|
X-Provider-Id |
通过 Provider ID 指定 | X-Provider-Id: 2 |
X-Provider-Name |
通过 Provider 名称指定 | X-Provider-Name: 火山引擎 |
🌊 流式响应
Python
from openai import OpenAI client = OpenAI( base_url="http://localhost:8000/v1", api_key="YOUR_API_KEY" ) stream = client.chat.completions.create( model="qwen-turbo", messages=[{"role": "user", "content": "写一首诗"}], stream=True ) for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="")
🧪 快速测试
📝 在线测试(Swagger UI)
访问 /docs 页面使用 Swagger UI 进行交互式 API 测试。
🔧 命令行测试
一键测试
# 测试服务是否正常 curl -s http://localhost:8000/api/health | python3 -m json.tool # 测试 chat completions(需要有配置的上游) curl -X POST http://localhost:8000/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{"model":"qwen-turbo","messages":[{"role":"user","content":"hi"}]}'