前置准备
本教程使用 Clawonetoken 作为 API 中转站,无需科学上网即可在国内直接调用 Claude API。如果你还不了解 AI API 中转站的工作原理,可以先阅读 什么是 AI API 中转站?
安装依赖:
pip install openai # 使用 OpenAI 兼容接口调用 Claude
# 或使用官方 SDK
pip install anthropic
方式一:使用 OpenAI 兼容接口(推荐)
Clawonetoken 提供完全兼容 OpenAI 格式的接口,无需修改现有代码结构:
from openai import OpenAI
client = OpenAI(
api_key="your-clawonetoken-key",
base_url="https://api.clawonetoken.com/v1"
)
# 同步调用
response = client.chat.completions.create(
model="claude-3-5-sonnet-20241022",
messages=[
{"role": "system", "content": "你是一个专业的 Python 开发助手。"},
{"role": "user", "content": "请帮我写一个快速排序算法,并加上详细注释。"}
],
max_tokens=2000,
temperature=0.7
)
print(response.choices[0].message.content)
方式二:流式输出(Streaming)
流式输出可以让用户看到实时生成的内容,适合长文本生成场景:
from openai import OpenAI
client = OpenAI(
api_key="your-clawonetoken-key",
base_url="https://api.clawonetoken.com/v1"
)
# 流式输出
with client.chat.completions.stream(
model="claude-3-5-sonnet-20241022",
messages=[{"role": "user", "content": "请写一篇关于人工智能的 500 字文章"}],
max_tokens=1000
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
print() # 换行
方式三:异步并发调用
当需要同时处理多个请求时,使用异步模式可以大幅提升吞吐量:
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI(
api_key="your-clawonetoken-key",
base_url="https://api.clawonetoken.com/v1"
)
async def ask_claude(question: str) -> str:
response = await client.chat.completions.create(
model="claude-3-5-sonnet-20241022",
messages=[{"role": "user", "content": question}],
max_tokens=500
)
return response.choices[0].message.content
async def main():
questions = [
"Python 和 JavaScript 的主要区别是什么?",
"什么是 RESTful API?",
"解释一下什么是装饰器模式"
]
# 并发发送所有请求
results = await asyncio.gather(*[ask_claude(q) for q in questions])
for q, r in zip(questions, results):
print(f"Q: {q}")
print(f"A: {r[:100]}...")
print()
asyncio.run(main())
Claude 模型选择建议
| 模型 | 适用场景 | 上下文 | 速度 |
|---|---|---|---|
| claude-3-5-sonnet-20241022 | 代码、复杂分析、长文档 | 200K | 中等 |
| claude-3-5-haiku-20241022 | 简单问答、分类、摘要 | 200K | 快速 |
| claude-3-opus-20240229 | 最高质量输出(旧版旗舰) | 200K | 较慢 |
如果你想了解 Claude 与 GPT-4o、DeepSeek 的性能对比,可以参考 2025 年主流大模型横向对比。
错误处理最佳实践
from openai import OpenAI, RateLimitError, APITimeoutError
import time
client = OpenAI(
api_key="your-clawonetoken-key",
base_url="https://api.clawonetoken.com/v1"
)
def call_with_retry(messages, model="claude-3-5-sonnet-20241022", max_retries=3):
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model=model,
messages=messages,
max_tokens=1000,
timeout=30
)
return response.choices[0].message.content
except RateLimitError:
wait_time = 2 ** attempt # 指数退避
print(f"速率限制,{wait_time}s 后重试...")
time.sleep(wait_time)
except APITimeoutError:
print(f"请求超时,重试 {attempt + 1}/{max_retries}")
raise Exception("达到最大重试次数")
