源码级别解析 · 源码解析 · 技术架构 · 最佳实践
2026-05-25 | 每日技术深度解读
Anthropic公司开发的新一代AI助手API,提供强大的自然语言处理能力
每个模型都有不同的token限制、推理速度和智能水平
import os
from anthropic import Anthropic
client = Anthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY"),
)
response = client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, Claude! Explain quantum computing in simple terms."
}
],
model="claude-opus-4-7",
)
print(response.content)
最基本的Claude 3 API调用方式,使用同步客户端
| 模型 | 上下文窗口 | 最大输出 | 推理速度 |
|---|---|---|---|
| Claude Opus 4-7 | 200K tokens | 4096 tokens | 较慢 |
| Claude Sonnet 4-7 | 200K tokens | 4096 tokens | 中等 |
| Claude Haiku 4-7 | 200K tokens | 4096 tokens | 快速 |
| Claude Instant | 128K tokens | 2048 tokens | 最快 |
import base64
from anthropic import Anthropic
client = Anthropic()
# 图像内容
with open("chart.png", "rb") as image_file:
image_data = base64.b64encode(image_file.read()).decode()
response = client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Analyze this chart and explain the trends."
},
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": image_data
}
}
]
}
],
model="claude-opus-4-7",
)
支持图像、PDF等多模态内容输入,实现复杂文档分析
import anthropic
def get_current_weather(location, unit="celsius"):
# Mock weather API
return {
"location": location,
"temperature": 22,
"unit": unit,
"condition": "Sunny"
}
tools = [{
"name": "get_current_weather",
"description": "Get current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}]
client = anthropic.Anthropic()
response = client.beta.tools.messages.create(
model="claude-sonnet-4-7",
max_tokens=1024,
tools=tools,
messages=[{
"role": "user",
"content": "What's the weather in Tokyo?"
}]
)
完整的工具使用流程,包含工具定义、调用和结果处理
def process_tool(tool_name, input_data):
"""Tool processor/router"""
try:
match tool_name:
case "get_current_weather":
return get_current_weather(input_data["location"])
case "search_database":
return search_database(input_data["query"])
case "calculate_math":
return calculate_math(input_data["expression"])
case _:
raise ValueError(f"Unknown tool: {tool_name}")
except Exception as e:
return {"error": str(e), "tool": tool_name}
def handle_tool_calls(message):
"""Handle tool calls from Claude"""
if hasattr(message, 'content') and all(isinstance(block, dict) and block.get('type') == 'tool_use' for block in message.content):
for tool_use in message.content:
tool_name = tool_use.name
input_data = tool_use.input
result = process_tool(tool_name, input_data)
# Return result to Claude
return result
return None
智能工具路由系统,支持多工具自动调用和结果处理
response = client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "Explain quantum computing basics",
"cache_control": {"type": "ephemeral"}
}
]
}
],
model="claude-sonnet-4-7",
extra_headers={"anthropic-beta": "prompt-caching-2024-07-31"}
)
使用缓存控制优化重复内容的处理性能
response = client.messages.create(
max_tokens=1024,
messages=[{
"role": "user",
"content": "Write a detailed explanation of machine learning algorithms."
}],
model="claude-opus-4-7",
)
print(f"Input tokens: {response.usage.input_tokens}")
print(f"Output tokens: {response.usage.output_tokens}")
print(f"Total tokens: {response.usage.input_tokens + response.usage.output_tokens}")
print(f"Cache creation input tokens: {response.usage.cache_creation_input_tokens}")
精确统计Token使用量,帮助优化API调用成本
class ClaudeChatBot:
def __init__(self, model="claude-sonnet-4-7"):
self.client = Anthropic()
self.model = model
self.conversation_history = []
def add_message(self, role, content):
"""添加消息到对话历史"""
self.conversation_history.append({
"role": role,
"content": content
})
def chat(self, user_input, tools=None):
"""处理用户输入"""
self.add_message("user", user_input)
response = self.client.messages.create(
max_tokens=1024,
messages=self.conversation_history,
model=self.model,
tools=tools if tools else [],
)
# 处理工具调用
if hasattr(response.content, 'tool_use'):
tool_result = self._process_tools(response.content)
self.add_message("assistant", tool_result)
else:
self.add_message("assistant", response.content)
return response
def _process_tools(self, tool_calls):
"""处理工具调用"""
# 工具处理逻辑
return "Tool executed successfully"
完整的聊天机器人实现,支持多轮对话和工具集成
感谢阅读!
访问 https://atcfu.com/ai-articles/claude-3-api/ 回顾本文