首页/博客/使用教程
使用教程2025-04-28· 10 分钟阅读

Python 调用 Claude API 完整指南:同步、流式、异步三种模式详解

详细教程:使用 Python 调用 Claude 3.5 Sonnet API,涵盖同步调用、流式输出(streaming)、异步并发三种模式,含完整代码示例。通过 AI API 中转站无需科学上网即可直连。

Python 调用 Claude APIClaude API Python 教程Claude 流式输出 PythonAnthropic Python SDKClaude API 中转Python AI 开发

前置准备

本教程使用 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("达到最大重试次数")

立即体验 Clawonetoken

一个 API Key,调用 GPT-4o、Claude 3.5、DeepSeek V3 等 120+ 主流模型,按量计费,无月租。

免费注册 →查看文档

相关文章

使用教程

Cherry Studio 接入 AI API 完整教程:一键配置 GPT-4o、Claude、DeepSeek

6 分钟阅读
使用教程

如何在 Cursor 中配置 DeepSeek API:代码补全 + 对话双模式完整教程

7 分钟阅读
© 2026 Clawonetoken · AI API 中转站 · 博客 · 文档