Source: https://aiprimetech.io/zh/learn/anthropic-python-sdk/ [首页](/zh/) / [学习](/zh/learn/) / Anthropic Python SDK:安装、设置 base_url、流式传输和错误处理 # 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..."}], ) ``` ## 错误处理 | 状态 | 异常 | 是否重试? | 400 | anthropic.BadRequestError | 否:修正请求 | 401 | anthropic.AuthenticationError | 否:密钥错误或缺失 | 403 | anthropic.PermissionDeniedError | 否 | 404 | anthropic.NotFoundError | 否:检查模型 ID 或 URL | 429 | anthropic.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 | 余额已用尽 | [充值](/zh/topup/) 有关模型侧错误的更多信息,请参阅 [Claude API 错误指南](/zh/learn/claude-api-errors-troubleshooting/). ## 常见问题 如何安装 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 密钥](/register) AI Prime Tech 是独立的 API 网关,与 Anthropic 无关联,未获得其背书,也不是其经销商。Claude 及相关模型名称是其各自所有者的商标。 ## 更多 Claude API 指南 [如何获取 Claude API 密钥](/zh/learn/how-to-get-a-claude-api-key/)[Claude API 定价详解](/zh/learn/claude-api-pricing-explained/)[使用 Claude API 最便宜的方式](/zh/learn/cheapest-way-to-use-claude-api/)[通过 Claude API 不限量使用 Cursor](/learn/use-claude-api-with-cursor/)[不限量访问 Claude Code](/zh/learn/use-claude-api-with-claude-code/)[Claude API 网关与 Anthropic 直连对比](/zh/learn/claude-api-vs-anthropic-direct/)[通过兼容 OpenAI 的 API 使用 Claude](/zh/learn/openai-compatible-claude-api/)[Claude 模型详解:Claude Opus、Sonnet、Haiku 与 Fable 的模型对比——全部 Claude API 模型、Anthropic 模型名称与价格(2026)](/zh/learn/claude-api-models-compared/)[使用加密货币支付 Claude API 费用](/zh/learn/claude-api-with-crypto-payment/)[无需候补名单即可访问 Claude API](/zh/learn/claude-api-without-waitlist/)[如何减少 Claude 词元用量](/zh/learn/how-to-reduce-claude-token-usage/)[通过 Claude API 不限量使用 Cline](/zh/learn/use-claude-api-with-cline/)[通过 Claude API 不限量使用 Roo Code](/zh/learn/use-claude-api-with-roo-code/)[在 JetBrains IDE 中不限量使用 Claude](/zh/learn/use-claude-api-with-jetbrains/)[通过 Claude API 无限制使用 Aider](/zh/learn/use-claude-api-with-aider/)[在 VS Code 中不限量使用 Claude](/zh/learn/use-claude-api-with-vscode/)[OpenCode 的 Claude 配置:opencode.json 设置、模型与常见错误](/zh/learn/use-claude-api-with-opencode/)[在 Claude 上运行不受限制的 Hermes 智能体](/zh/learn/run-hermes-agent-with-claude-api/)[使用 Claude 不限量运行 OpenClaw](/zh/learn/run-openclaw-with-claude-api/)[兼容 Anthropic 的 API 意味着什么](/zh/learn/anthropic-compatible-api/)[Claude Code API 密钥 — ANTHROPIC_API_KEY:如何获取、配置,以及何时应改用 claude setup-token](/zh/learn/claude-code-api-key-setup/)[Claude Code API 成本 — 定价与降低成本的方法](/zh/learn/claude-code-api-costs/)[Claude API 错误详解:服务器错误 500、过载 529、速率限制 429、错误请求 400 — 以及各自的修复方法](/zh/learn/claude-api-errors-troubleshooting/)[如何购买 Claude API 额度,以及为什么购买 Claude 额度比任何“购买 Claude 账户”的方案都更好](/zh/learn/buy-claude-api-credits/)[Claude 免费 API:有免费的 Claude API 密钥吗?2026 年究竟有哪些内容免费?](/zh/learn/claude-api-free-trial/)[Claude API 与 Claude Pro/Max 订阅——如何选择](/zh/learn/claude-api-vs-subscription/)[使用 Claude 运行 Codex CLI](/zh/learn/use-claude-api-with-codex/)[将 Claude 连接到 n8n](/zh/learn/use-claude-api-with-n8n/)[通过 LiteLLM 路由到 Claude](/zh/learn/use-claude-api-with-litellm/)[在 Kilo Code 中使用 Claude](/zh/learn/use-claude-api-with-kilo-code/)[将 Claude 接入 GitHub Copilot](/zh/learn/use-claude-api-with-github-copilot/)[通过网关将 Zed 连接到 Claude](/zh/learn/use-claude-api-with-zed/)[将 Cherry Studio 连接到 Claude](/zh/learn/use-claude-api-with-cherry-studio/)[LangChain 中的 ChatAnthropic:导入、base_url、流式传输、工具和错误](/zh/learn/use-claude-api-with-langchain/)[通过 Vercel AI SDK 使用 Claude:createAnthropic baseURL、流式传输和问题修复](/zh/learn/use-claude-api-with-vercel-ai-sdk/)[使用 Claude 运行 Factory Droid](/zh/learn/use-claude-api-with-factory-droid/)[Claude Code API 详解](/zh/learn/claude-code-api/)[将 Claude API 集成到您的应用中](/zh/learn/claude-api-integration/)[如何不受限制地使用 Claude,以及为什么不存在“Claude Code 破解版本”](/zh/learn/get-unlimited-claude-usage/)