Claude API Python SDK — Anthropic / OpenAI 兼容用法
Python 集成 Claude API 完整指南:anthropic 包安装、消息发送、流式输出、async 用法、错误处理。
安装
pip 安装bash
pip install anthropic
# 或 OpenAI 兼容
pip install openai基础调用
anthropic SDKpython
from anthropic import Anthropic
client = Anthropic(
api_key="sk-cs2-...",
base_url="https://api3.claudestore.store"
)
message = client.messages.create(
model="claude-sonnet-4.6",
max_tokens=1024,
messages=[{"role": "user", "content": "你好"}]
)
print(message.content[0].text)流式输出
流式python
with client.messages.stream(
model="claude-sonnet-4.6",
max_tokens=1024,
messages=[{"role": "user", "content": "用中文写一首唐诗"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)异步 (async)
AsyncAnthropicpython
import asyncio
from anthropic import AsyncAnthropic
async def main():
client = AsyncAnthropic(
api_key="sk-cs2-...",
base_url="https://api3.claudestore.store"
)
msg = await client.messages.create(
model="claude-sonnet-4.6",
max_tokens=512,
messages=[{"role": "user", "content": "你好"}]
)
print(msg.content[0].text)
asyncio.run(main())错误处理
try/exceptpython
from anthropic import APIStatusError, RateLimitError
try:
msg = client.messages.create(...)
except RateLimitError as e:
print(f"速率限制,等待 {e.response.headers.get('retry-after')} 秒")
except APIStatusError as e:
print(f"HTTP {e.status_code}: {e.message}")