DeepSeek Chat Completions 的地址怎么配?
查看完整题解
参考回答
直接回答
OpenAI 兼容的 Chat Completions 请求用 POST https://api.deepseek.com/chat/completions。使用对应的 SDK 时,把 base_url 配成 https://api.deepseek.com,SDK 会加上资源路径。
讲清原理
直接 HTTP 调用要填完整地址,SDK 配置只填服务的基地址。Responses 与 Anthropic 兼容接口各有自己的路径和协议字段。
例子与易错点
下面用本地模拟传输检查 SDK 拼出的地址、方法和 Authorization。代码在内存里返回固定响应。
import json
import httpx
from openai import OpenAI
events = []
def fake_service(request):
body = json.loads(request.content)
events.append((request, body))
return httpx.Response(200, json={
"id": "local-chat", "object": "chat.completion", "created": 0,
"model": body["model"], "choices": [{
"index": 0, "finish_reason": "stop",
"message": {"role": "assistant", "content": "收到"},
}],
})
with OpenAI(api_key="local-test-key", base_url="https://api.deepseek.com",
http_client=httpx.Client(transport=httpx.MockTransport(fake_service)),
max_retries=0) as client:
reply = client.chat.completions.create(
model="deepseek-flash", messages=[{"role": "user", "content": "请回答收到"}],
)
request, body = events[0]
assert str(request.url) == "https://api.deepseek.com/chat/completions"
assert request.method == "POST"
assert request.headers["authorization"] == "Bearer local-test-key"
assert reply.choices[0].message.content == "收到"
print("POST and Bearer header verified using an in-memory response")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。