首页 / 学习 / Anthropic Python SDK:安装、设置 base_url、流式传输和错误处理
Python 中的 Claude。一条优雅的缎带状蛇形曲线环绕代码页面,并连接到一个小型 API 接口。

Anthropic Python SDK:安装、设置 base_url、流式传输和错误处理

该 anthropic 包是 Anthropic 为 Claude API 提供的官方 Python 客户端。它负责身份验证、重试、流式传输和类型化错误处理,并且无需修改即可用于任何兼容 Anthropic 的端点:设置 base_url (或 ANTHROPIC_BASE_URL),其余代码保持不变。

安装

终端
pip install anthropic

1.x 版本基于 httpx2 运行,并且需要 Python 3.10 或更新版本。如果传入自己的 HTTP 客户端,请使用 SDK 的 DefaultHttpxClient 以保留其默认超时和连接数限制。

创建客户端

app.py
import anthropic

client = anthropic.Anthropic(
    api_key="your_key",   # default: ANTHROPIC_API_KEY
    base_url="https://aiprimetech.io",    # default: ANTHROPIC_BASE_URL, else https://api.anthropic.com
)

base_url 是主机根地址。SDK 会自行追加 /v1/messages ,因此 https://aiprimetech.io/v1 会生成 /v1/v1/messages 以及一个 404 page not found。在环境中设置这两个变量后, anthropic.Anthropic() 无需传入任何参数:

终端
export ANTHROPIC_API_KEY=your_key
export ANTHROPIC_BASE_URL=https://aiprimetech.io

发送消息

app.py
message = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Summarise TCP slow start in two sentences."}],
)

for block in message.content:
    if block.type == "text":
        print(block.text)

print(message.usage.input_tokens, message.usage.output_tokens)
print(message._request_id)   # log this with any failure report

content 是一个内容块列表(文本、思考、工具使用),因此请检查 block.type ,而不是盲目读取 content[0].text 。

流式接收响应

stream.py
with client.messages.stream(
    model="claude-sonnet-5",
    max_tokens=16000,
    messages=[{"role": "user", "content": "Write a short story about a lighthouse."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    final = stream.get_final_message()

对于输入较长、输出较长或较大的 max_tokens,请使用流式传输:单个非流式请求必须在超时时限内完成,流式请求则不受此限制。 messages.create(..., stream=True) 会提供原始事件迭代器,适用于不需要辅助工具的情况。

异步客户端

async_app.py
import asyncio, anthropic

client = anthropic.AsyncAnthropic(base_url="https://aiprimetech.io")
limit = asyncio.Semaphore(3)   # stay within your key's concurrency

async def ask(question: str) -> str:
    async with limit:
        msg = await client.messages.create(
            model="claude-haiku-4-5",
            max_tokens=512,
            messages=[{"role": "user", "content": question}],
        )
        return next(b.text for b in msg.content if b.type == "text")

async def main():
    answers = await asyncio.gather(*(ask(q) for q in ["What is DNS?", "What is BGP?"]))
    print(answers)

asyncio.run(main())

信号量很重要。使用 asyncio.gather 同时发起数百个请求,是我们在 Python 客户端中最常见的 Concurrency limit exceeded 错误原因。

超时与重试

默认设置:每个请求的超时时间为 10 分钟,并进行 2 次采用指数退避的自动重试。SDK 会重试连接错误、408、409、429 和 5xx 响应。由于超时也会触发重试,最坏情况下的实际总耗时为超时时间乘以尝试次数。

app.py
client = anthropic.Anthropic(base_url="https://aiprimetech.io", timeout=60.0, max_retries=4)

# override for one call only
client.with_options(timeout=300.0).messages.create(
    model="claude-opus-5-5",
    max_tokens=4000,
    messages=[{"role": "user", "content": "Review this design doc..."}],
)

错误处理

状态 异常 是否重试?
400anthropic.BadRequestError否:修正请求
401anthropic.AuthenticationError否:密钥错误或缺失
403anthropic.PermissionDeniedError否
404anthropic.NotFoundError否:检查模型 ID 或 URL
429anthropic.RateLimitError是,稍等后重试
5xx,包括 529 过载anthropic.InternalServerError是
网络故障anthropic.APIConnectionError是
超时anthropic.APITimeoutError是,或使用流式传输
errors.py
try:
    message = client.messages.create(model="claude-sonnet-5", max_tokens=1024,
                                      messages=[{"role": "user", "content": "Hi"}])
except anthropic.NotFoundError as e:
    print("Bad model ID or URL:", e.message)
except anthropic.RateLimitError as e:
    print("Rate limited, retry after", e.response.headers.get("retry-after"))
except anthropic.APIStatusError as e:
    print(e.status_code, e.type, e.message)
except anthropic.APIConnectionError:
    print("Network problem")

先捕获具体的异常类,最后再捕获 APIStatusError ;一个宽泛的 except 会掩盖值得重试的错误与需要修改代码的错误之间的区别。 e.type 会提供 API 的错误类型字符串,例如 rate_limit_error 或 overloaded_error.

模型 ID

模型 ID 适用场景
claude-sonnet-5编程和智能体任务的默认选择:速度快、能力强、价格适中。
claude-opus-5-5更复杂的推理、大规模重构、长时间运行的智能体任务。
claude-fable-5-1能力最强,价格也最高;留给最困难的任务使用。
claude-haiku-4-5价格低、速度快:标题、摘要、分类和小步骤。

client.models.list() 会返回端点提供的模型,因此可以在使用前检查 ID。请严格按原样使用 ID,不要添加日期后缀。

网关故障排查

你会看到什么 原因 解决方法
NotFoundError 替换为 404 page not found/v1 在 base_url使用主机根地址
AuthenticationError进程中未设置密钥,或粘贴时带入了空白字符打印 len(os.environ["ANTHROPIC_API_KEY"])
RateLimitError: Concurrency limit exceeded for user正在处理的请求过多一个 asyncio.Semaphore ,如上所示
APITimeoutError 发生在耗时较长的任务中非流式请求的运行时间超过了超时时限使用流式传输,或增大 timeout
InternalServerError: No available accounts上游容量暂时不足让 SDK 重试;增大 max_retries
Insufficient account balance余额已用尽充值

有关模型侧错误的更多信息,请参阅 Claude API 错误指南.

常见问题

如何安装 Anthropic Python SDK?
运行 pip install anthropic。1.x 版本需要 Python 3.10 或更新版本。
如何在 Anthropic Python SDK 中设置自定义基础 URL?
向 anthropic.Anthropic() 传入 base_url,或设置 ANTHROPIC_BASE_URL。请使用主机根地址;SDK 会追加 /v1/messages。
默认超时时间和重试次数是多少?
每个请求的超时时间为 10 分钟,并进行 2 次采用指数退避的重试,涵盖连接错误、408、409、429 和 5xx。
如何使用 Python SDK 进行流式传输?
使用 with client.messages.stream(...) as stream:,并遍历 stream.text_stream;stream.get_final_message() 会返回完整消息。
几分钟内开始使用 Claude

获取 API 密钥,无需 Anthropic 账户,也无需加入候补名单。

获取你的 API 密钥

AI Prime Tech 是独立的 API 网关,与 Anthropic 无关联,未获得其背书,也不是其经销商。Claude 及相关模型名称是其各自所有者的商标。

更多 Claude API 指南

如何获取 Claude API 密钥Claude API 定价详解使用 Claude API 最便宜的方式通过 Claude API 不限量使用 Cursor不限量访问 Claude CodeClaude API 网关与 Anthropic 直连对比通过兼容 OpenAI 的 API 使用 ClaudeClaude 模型详解:Claude Opus、Sonnet、Haiku 与 Fable 的模型对比——全部 Claude API 模型、Anthropic 模型名称与价格(2026)使用加密货币支付 Claude API 费用无需候补名单即可访问 Claude API如何减少 Claude 词元用量通过 Claude API 不限量使用 Cline通过 Claude API 不限量使用 Roo Code在 JetBrains IDE 中不限量使用 Claude通过 Claude API 无限制使用 Aider在 VS Code 中不限量使用 ClaudeOpenCode 的 Claude 配置:opencode.json 设置、模型与常见错误在 Claude 上运行不受限制的 Hermes 智能体使用 Claude 不限量运行 OpenClaw兼容 Anthropic 的 API 意味着什么Claude Code API 密钥 — ANTHROPIC_API_KEY:如何获取、配置,以及何时应改用 claude setup-tokenClaude Code API 成本 — 定价与降低成本的方法Claude API 错误详解:服务器错误 500、过载 529、速率限制 429、错误请求 400 — 以及各自的修复方法如何购买 Claude API 额度,以及为什么购买 Claude 额度比任何“购买 Claude 账户”的方案都更好Claude 免费 API:有免费的 Claude API 密钥吗?2026 年究竟有哪些内容免费?Claude API 与 Claude Pro/Max 订阅——如何选择使用 Claude 运行 Codex CLI将 Claude 连接到 n8n通过 LiteLLM 路由到 Claude在 Kilo Code 中使用 Claude将 Claude 接入 GitHub Copilot通过网关将 Zed 连接到 Claude将 Cherry Studio 连接到 ClaudeLangChain 中的 ChatAnthropic:导入、base_url、流式传输、工具和错误通过 Vercel AI SDK 使用 Claude:createAnthropic baseURL、流式传输和问题修复使用 Claude 运行 Factory DroidClaude Code API 详解将 Claude API 集成到您的应用中如何不受限制地使用 Claude,以及为什么不存在“Claude Code 破解版本”

更多 Claude API 指南

兼容 Anthropic 的 API 意味着什么如何购买 Claude API 额度使用 Claude API 最便宜的方式Claude API 错误详解:服务器错误 500、过载 529、速率限制 429、错误请求 400 — 以及各自的修复方法Claude 免费 API:有免费的 Claude API 密钥吗?2026 年究竟有哪些内容免费?将 Claude API 集成到您的应用中Claude 模型详解:Claude Opus、Sonnet、Haiku 与 Fable 的模型对比——全部 Claude API 模型、Anthropic 模型名称与价格(2026)Claude API 定价详解Claude API 网关与 Anthropic 直连对比Claude API 与 Claude Pro/Max 订阅——如何选择使用加密货币支付 Claude API 费用无需候补名单即可访问 Claude APIClaude Code API 详解Claude Code API 成本 — 定价与降低成本的方法Claude Code API 密钥 — ANTHROPIC_API_KEY:如何获取、配置,以及何时应改用 claude setup-token如何不限量使用 Claude如何获取 Claude API 密钥如何减少 Claude 词元用量通过 OpenAI SDK 使用 Claude:OpenAI 兼容端点、流式传输、工具与限制通过网关在 Hermes Agent 中使用 Claude:自定义提供商配置、成本控制与问题修复使用 Claude 不限量运行 OpenClaw不限量 Claude API 访问意味着什么如何获取不限量的 Claude API 密钥不限量使用 Claude Code——无词元限制不限量访问 Claude Opus 4.8不限量使用 Claude——套餐与定价通过网关在 Aider 中使用 Claude:ANTHROPIC_API_BASE、配置文件、架构师模式与问题修复将 Cherry Studio 连接到 Claude不限量访问 Claude Code通过 Claude API 不限量使用 Cline通过自定义提供商使用 Codex CLI:config.toml、GPT 与 Claude 模型、IDE 扩展与问题修复通过 Claude 无限访问运行 Cursor使用 Claude 运行 Factory Droid通过网关在 GitHub Copilot Chat 中使用 Claude:自定义端点配置、智能体模式与问题修复在 JetBrains IDE 中不限量使用 Claude在 Kilo Code 中使用 ClaudeLangChain 中的 ChatAnthropic:导入、base_url、流式传输、工具和错误通过 LiteLLM 路由到 Claude将 Claude 连接到 n8nOpenCode 的 Claude 配置:opencode.json 设置、模型与常见错误通过 Claude API 不限量使用 Roo Code通过 Vercel AI SDK 使用 Claude:createAnthropic baseURL、流式传输和问题修复在 VS Code 中不限量使用 Claude通过网关将 Zed 连接到 Claude