Claude API Python 教程:使用 Anthropic's API 构建 AI 应用

Claude API 让您可以直接访问 Anthropic 最强大的 AI 模型。与 ChatGPT 的浏览器界面不同,API 让您能够构建自定义应用、自动化工作流程,并将 AI 集成到现有系统中。
本教程涵盖从零基础到投入生产所需的一切内容:身份验证、基础消息收发、流式响应、工具使用,以及构建可靠 AI 应用的最佳实践。
学完之后,您将获得适用于常见场景的可运行 Python 代码,并了解如何根据自身需求进行扩展。
Claude API 入门
为 Claude API 开发设置 Python 环境
首先,获取您的 API 密钥并设置环境。
获取您的 API 密钥:
- 在以下网址创建账户 console.anthropic.com
- 进入 API Keys
- 创建新密钥并妥善保存
安装官方 SDK (PyPI 包):
pip install anthropic
设置您的 API 密钥:
export ANTHROPIC_API_KEY="sk-ant-..."
import os
os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."
您的第一次 API 调用:
from anthropic import Anthropic
client = Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude!"}
]
)
print(message.content[0].text)
就是这样——您现在已经可以通过 Python 直接调用 Claude 了。
了解 Messages API
Messages API 是与 Claude 交互的核心接口
Messages API 负责处理与 Claude 的所有对话。其结构如下:
基本消息结构:
response = client.messages.create(
model="claude-sonnet-4-20250514", # Model selection
max_tokens=1024, # Maximum response length
system="You are a helpful coding assistant.", # System prompt
messages=[
{"role": "user", "content": "Explain Python decorators"},
{"role": "assistant", "content": "Decorators are..."},
{"role": "user", "content": "Show me an example"}
]
)
可用模型 (请参阅 Anthropic 文档 获取最新信息):
claude-opus-4-20250514- 能力最强,最适合复杂任务claude-sonnet-4-20250514- 性能与成本均衡claude-haiku-3-20250514- 速度最快、价格最低
关键参数:
model- 使用哪个 Claude 版本max_tokens- 响应的最大令牌数(必填)system- 用于配置行为的系统提示词messages- 对话历史temperature- 随机性(0-1,默认值因模型而异)stop_sequences- 用于停止生成的字符串
处理响应:
response = client.messages.create(...)
text = response.content[0].text
print(f"Input tokens: {response.usage.input_tokens}")
print(f"Output tokens: {response.usage.output_tokens}")
print(f"Stop reason: {response.stop_reason}")
流式响应
在实时应用中使用流式响应以获得更好的用户体验
对于较长的响应,流式传输会在文本生成时即时显示,从而提供更好的用户体验。
基本流式传输:
with client.messages.stream(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a short story"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
基于事件的流式传输:
with client.messages.stream(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Explain machine learning"}]
) as stream:
for event in stream:
if event.type == "content_block_delta":
print(event.delta.text, end="")
elif event.type == "message_stop":
print("\n[Complete]")
异步流式传输(适用于 Web 应用):
import asyncio
from anthropic import AsyncAnthropic
async_client = AsyncAnthropic()
async def stream_response(prompt: str):
async with async_client.messages.stream(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
) as stream:
async for text in stream.text_stream:
yield text
async def main():
async for chunk in stream_response("Tell me a joke"):
print(chunk, end="")
asyncio.run(main())
工具使用(函数调用)
让 Claude 能够调用您的函数
工具使用让 Claude 可以调用您的 Python 函数,以访问外部数据或执行操作。
定义您的工具:
tools = [
{
"name": "get_weather",
"description": "Get current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country, e.g. London, UK"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["location"]
}
}
]
处理工具调用:
def get_weather(location: str, unit: str = "celsius") -> dict:
# Your actual weather API call here
return {"temp": 22, "condition": "sunny", "location": location}
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}]
)
if response.stop_reason == "tool_use":
tool_use = response.content[1] # Tool call is second content block
tool_name = tool_use.name
tool_input = tool_use.input
# Execute the function
if tool_name == "get_weather":
result = get_weather(**tool_input)
# Send result back to Claude
final_response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in Tokyo?"},
{"role": "assistant", "content": response.content},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": str(result)
}
]
}
]
)
print(final_response.content[0].text)
构建可复用的客户端
创建可维护的 API 封装,用于生产环境
对于生产应用,请将 API 封装在一个可复用的类中:
from anthropic import Anthropic
from typing import Generator, Optional
import json
class ClaudeClient:
def __init__(
self,
model: str = "claude-sonnet-4-20250514",
system_prompt: Optional[str] = None
):
self.client = Anthropic()
self.model = model
self.system_prompt = system_prompt
self.conversation: list = []
def chat(self, message: str, max_tokens: int = 1024) -> str:
"""Send a message and get a response."""
self.conversation.append({"role": "user", "content": message})
response = self.client.messages.create(
model=self.model,
max_tokens=max_tokens,
system=self.system_prompt or "",
messages=self.conversation
)
assistant_message = response.content[0].text
self.conversation.append({
"role": "assistant",
"content": assistant_message
})
return assistant_message
def stream_chat(self, message: str) -> Generator[str, None, None]:
"""Stream a response for real-time display."""
self.conversation.append({"role": "user", "content": message})
full_response = ""
with self.client.messages.stream(
model=self.model,
max_tokens=1024,
system=self.system_prompt or "",
messages=self.conversation
) as stream:
for text in stream.text_stream:
full_response += text
yield text
self.conversation.append({
"role": "assistant",
"content": full_response
})
def clear_history(self):
"""Reset conversation history."""
self.conversation = []
claude = ClaudeClient(system_prompt="You are a Python expert.")
print(claude.chat("What's the best way to handle exceptions?"))
print(claude.chat("Show me an example")) # Has context from previous message
错误处理与速率限制
在生产环境中优雅地处理 API 错误
生产应用需要健壮的错误处理:
from anthropic import (
Anthropic,
APIError,
RateLimitError,
APIConnectionError
)
import time
def call_with_retry(
client: Anthropic,
messages: list,
max_retries: int = 3
) -> str:
for attempt in range(max_retries):
try:
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=messages
)
return response.content[0].text
except RateLimitError as e:
wait_time = 2 ** attempt # 指数退避
print(f"Rate limited. Waiting {wait_time}s...")
time.sleep(wait_time)
except APIConnectionError as e:
print(f"Connection error: {e}")
time.sleep(1)
except APIError as e:
print(f"API error: {e}")
raise
raise Exception("Max retries exceeded")
速率限制指南:
- 实现指数退避
- 尽可能缓存响应
- 对批量操作使用批处理
- 在 Anthropic 控制台中监控使用情况
结语
您已经可以开始构建生产级 AI 应用了
Claude API 带来了超越聊天界面的更多可能。您现在可以构建自定义 AI 应用、自动化工作流程,并将 Claude 集成到您现有的系统中。
关键要点:
- 所有交互均使用 Messages API
- 使用流式响应以获得更好的用户体验
- 实现工具以获得外部能力
- 通过重试逻辑处理错误
- 为生产环境构建可复用的客户端
继续学习:
- MCP 教程 了解高级集成
- OpenClaw 设置 打造全天候 24/7 AI 助手
- 自托管替代方案 保护隐私
从简单的用例开始,逐步迭代。该 API 足够灵活,可以支持您构建的任何项目。
常见问题
关于 Claude API 的常见问题
Claude API 的费用是多少?
按 token 计费。Claude Sonnet:输入 $3/百万,输出 $15/百万。Claude Haiku:输入 $0.25/百万,输出 $1.25/百万。请查看 anthropic.com/pricing 了解当前价格。
Claude API 和 OpenClaw 有什么区别?
Claude API 是 Anthropic 的原始接口。OpenClaw 在 Claude(或其他模型)的基础上增加了持久化、消息平台集成、工具和记忆功能。API 适用于自定义应用,OpenClaw 适用于个人助手场景。
我可以将 Claude API 用于商业项目吗?
可以,该 API 专为商业用途而设计。具体准则请查阅 Anthropic 的使用政策。
最大上下文长度是多少?
Claude 支持 200K token 的上下文。对于大多数应用来说,这已经绰绰有余。请谨慎管理上下文以提高成本效率。
如何降低 API 成本?
简单任务使用 Haiku,缓存响应,为长对话实现对话摘要,并将相似的请求批量处理。
更多文章
终极 OpenClaw AWS 搭建指南

在 AWS 上搭建 OpenClaw 的权威指南。包含 Spot 实例配置、成本优化以及分步说明。
在 OpenClaw 中使用工具链构建 AI 工作流
掌握工具链与函数调用的串联技巧,构建强大的多步骤 AI 自动化工作流——从数据提取到内容生成再到部署。
自托管 AI 助手成本优化指南:低预算运行 Claude
降低自托管 AI 助手 API 成本的实用策略——智能模型路由、缓存、批处理以及针对 OpenClaw 的优化,让 Claude 的运行更经济实惠。