本文介绍了python调用anthropic api的两种主要方式,包括
- requests 调用
- 官方 sdk 调用
https://api-docs.deepseek.com/zh-cn/guides/anthropic_api
python 调用 anthropic api 的两种方式
anthropic api 本质是标准 http 接口,python 中通常有两种主流调用方式:
- 使用
requests:轻量、灵活、适合工程封装 - 使用官方 sdk:封装完善、自动处理部分配置
下文对两种方式进行对比与示例说明。
一、使用 requests 调用(适合生产环境工程封装)
requests 是 python 最通用的 http 客户端,适合你在框架(django / fastapi / 微服务)中封装统一的 ai 调用模块。
1. 基本非流式调用
import requests
api_key = "your_api_key"
base_url = "https://api.deepseek.com/anthropic/v1/messages"
headers = {
"content-type": "application/json",
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
}
payload = {
"model": "deepseek-chat",
"max_tokens": 2048,
"messages": [{"role": "user", "content": "你好"}],
}
resp = requests.post(base_url, json=payload, headers=headers, timeout=600)
print(resp.json())
2. 流式响应(sse stream)
import requests
import json
api_key = "your_api_key"
base_url = "https://api.deepseek.com/anthropic/v1/messages"
headers = {
"content-type": "application/json",
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
}
payload = {
"model": "deepseek-chat",
"max_tokens": 2000,
"messages": [{"role": "user", "content": "介绍一下你自己"}],
"stream": true,
}
with requests.post(base_url, json=payload, headers=headers, stream=true, timeout=600) as r:
for line in r.iter_lines():
if not line:
continue
data = line.decode("utf-8")
if data.startswith("data: "):
content = data[6:]
if content == "[done]":
break
event = json.loads(content)
delta = event.get("delta", {}).get("text")
if delta:
print(delta, end="", flush=true)
3. 使用毫秒超时(api_timeout_ms)
anthropic 配置通常使用毫秒,需要转成秒:
api_timeout_ms = 600000 requests.post(url, json=payload, headers=headers, timeout=api_timeout_ms / 1000)
二、使用官方 sdk 调用(简单、封装完善)
anthropic 提供官方 python sdk,支持自动处理 headers、base_url、超时管理等。
安装:
pip install anthropic
1. 基本调用
from anthropic import anthropic
client = anthropic(
api_key="your_api_key",
base_url="https://api.deepseek.com/anthropic",
timeout=600,
)
resp = client.messages.create(
model="deepseek-chat",
max_tokens=2048,
messages=[{"role": "user", "content": "你好"}],
)
print(resp)
2. 流式调用(逐 token 输出)
from anthropic import anthropic
client = anthropic(
api_key="your_api_key",
base_url="https://api.deepseek.com/anthropic",
)
with client.messages.stream(
model="deepseek-chat",
max_tokens=2048,
messages=[{"role": "user", "content": "写一段话"}],
) as stream:
for event in stream:
if event.type == "message_delta" and event.delta.text:
print(event.delta.text, end="", flush=true)
三、两种方式对比
| 对比项 | requests | 官方 sdk |
|---|---|---|
| 轻量性 | 高 | 中 |
| 灵活度 | 高(可自由封装) | 中 |
| 上手难度 | 需要写 headers、处理 sse | 简单直接 |
| 流式支持 | 需要手动解析 sse | 官方封装 |
| 配置管理(base_url、timeout) | 手动控制 | 构造参数即可 |
| 适合场景 | 生产级 api 服务、统一调用层 | 技术验证、快速开发 |
两种方式都稳定可靠,你可以针对团队习惯选择合适的方式。
到此这篇关于python 调用anthropic api 的两种方式的文章就介绍到这了,更多相关python调用 anthropic api 内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论