claude-api by affaan-m/everything-claude-code
npx skills add https://github.com/affaan-m/everything-claude-code --skill claude-api使用 Anthropic Claude API 和 SDK 构建应用程序。
anthropic (Python) 或 @anthropic-ai/sdk (TypeScript) 时| 模型 | ID | 最佳用途 |
|---|---|---|
| Opus 4.1 | claude-opus-4-1 | 复杂推理、架构设计、研究 |
| Sonnet 4 | claude-sonnet-4-0 | 平衡的编码任务,大多数开发工作 |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| Haiku 3.5 |
claude-3-5-haiku-latest |
| 快速响应、高吞吐量、成本敏感型任务 |
除非任务需要深度推理(Opus)或速度/成本优化(Haiku),否则默认使用 Sonnet 4。对于生产环境,建议使用固定的快照 ID 而非别名。
pip install anthropic
import anthropic
client = anthropic.Anthropic() # 从环境变量读取 ANTHROPIC_API_KEY
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[
{"role": "user", "content": "Explain async/await in Python"}
]
)
print(message.content[0].text)
with client.messages.stream(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a haiku about coding"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
system="You are a senior Python developer. Be concise.",
messages=[{"role": "user", "content": "Review this function"}]
)
npm install @anthropic-ai/sdk
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(); // 从环境变量读取 ANTHROPIC_API_KEY
const message = await client.messages.create({
model: "claude-sonnet-4-0",
max_tokens: 1024,
messages: [
{ role: "user", content: "Explain async/await in TypeScript" }
],
});
console.log(message.content[0].text);
const stream = client.messages.stream({
model: "claude-sonnet-4-0",
max_tokens: 1024,
messages: [{ role: "user", content: "Write a haiku" }],
});
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
process.stdout.write(event.delta.text);
}
}
定义工具并让 Claude 调用它们:
tools = [
{
"name": "get_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"]
}
}
]
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in SF?"}]
)
# 处理工具使用响应
for block in message.content:
if block.type == "tool_use":
# 使用 block.input 执行工具
result = get_weather(**block.input)
# 发送结果返回
follow_up = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in SF?"},
{"role": "assistant", "content": message.content},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": block.id, "content": str(result)}
]}
]
)
发送图像进行分析:
import base64
with open("diagram.png", "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": image_data}},
{"type": "text", "text": "Describe this diagram"}
]
}]
)
用于复杂推理任务:
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=16000,
thinking={
"type": "enabled",
"budget_tokens": 10000
},
messages=[{"role": "user", "content": "Solve this math problem step by step..."}]
)
for block in message.content:
if block.type == "thinking":
print(f"Thinking: {block.thinking}")
elif block.type == "text":
print(f"Answer: {block.text}")
缓存大型系统提示词或上下文以降低成本:
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
system=[
{"type": "text", "text": large_system_prompt, "cache_control": {"type": "ephemeral"}}
],
messages=[{"role": "user", "content": "Question about the cached context"}]
)
# 检查缓存使用情况
print(f"Cache read: {message.usage.cache_read_input_tokens}")
print(f"Cache creation: {message.usage.cache_creation_input_tokens}")
以 50% 的成本降低异步处理大量请求:
import time
batch = client.messages.batches.create(
requests=[
{
"custom_id": f"request-{i}",
"params": {
"model": "claude-sonnet-4-0",
"max_tokens": 1024,
"messages": [{"role": "user", "content": prompt}]
}
}
for i, prompt in enumerate(prompts)
]
)
# 轮询完成状态
while True:
status = client.messages.batches.retrieve(batch.id)
if status.processing_status == "ended":
break
time.sleep(30)
# 获取结果
for result in client.messages.batches.results(batch.id):
print(result.result.message.content[0].text)
构建多步骤智能体:
# 注意:Agent SDK API 接口可能变更 — 请查阅官方文档
import anthropic
# 将工具定义为函数
tools = [{
"name": "search_codebase",
"description": "Search the codebase for relevant code",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"]
}
}]
# 运行带有工具使用的智能体循环
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Review the auth module for security issues"}]
while True:
response = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=4096,
tools=tools,
messages=messages,
)
if response.stop_reason == "end_turn":
break
# 处理工具调用并继续循环
messages.append({"role": "assistant", "content": response.content})
# ... 执行工具并追加 tool_result 消息
| 策略 | 节省 | 使用时机 |
|---|---|---|
| 提示词缓存 | 缓存令牌最高 90% | 重复的系统提示词或上下文 |
| 批量 API | 50% | 非时间敏感的批量处理 |
| 使用 Haiku 而非 Sonnet | ~75% | 简单任务、分类、提取 |
| 缩短 max_tokens | 可变 | 当您知道输出会很短时 |
| 流式传输 | 无(成本相同) | 更好的用户体验,相同价格 |
import time
from anthropic import APIError, RateLimitError, APIConnectionError
try:
message = client.messages.create(...)
except RateLimitError:
# 退避并重试
time.sleep(60)
except APIConnectionError:
# 网络问题,退避重试
pass
except APIError as e:
print(f"API error {e.status_code}: {e.message}")
# 必需
export ANTHROPIC_API_KEY="your-api-key-here"
# 可选:设置默认模型
export ANTHROPIC_MODEL="claude-sonnet-4-0"
切勿硬编码 API 密钥。始终使用环境变量。
每周安装数
449
代码仓库
GitHub 星标数
102.1K
首次出现
11 天前
安全审计
安装于
codex427
cursor373
gemini-cli369
github-copilot369
amp369
cline369
Build applications with the Anthropic Claude API and SDKs.
anthropic (Python) or @anthropic-ai/sdk (TypeScript)| Model | ID | Best For |
|---|---|---|
| Opus 4.1 | claude-opus-4-1 | Complex reasoning, architecture, research |
| Sonnet 4 | claude-sonnet-4-0 | Balanced coding, most development tasks |
| Haiku 3.5 | claude-3-5-haiku-latest | Fast responses, high-volume, cost-sensitive |
Default to Sonnet 4 unless the task requires deep reasoning (Opus) or speed/cost optimization (Haiku). For production, prefer pinned snapshot IDs over aliases.
pip install anthropic
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from env
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[
{"role": "user", "content": "Explain async/await in Python"}
]
)
print(message.content[0].text)
with client.messages.stream(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a haiku about coding"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
system="You are a senior Python developer. Be concise.",
messages=[{"role": "user", "content": "Review this function"}]
)
npm install @anthropic-ai/sdk
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(); // reads ANTHROPIC_API_KEY from env
const message = await client.messages.create({
model: "claude-sonnet-4-0",
max_tokens: 1024,
messages: [
{ role: "user", content: "Explain async/await in TypeScript" }
],
});
console.log(message.content[0].text);
const stream = client.messages.stream({
model: "claude-sonnet-4-0",
max_tokens: 1024,
messages: [{ role: "user", content: "Write a haiku" }],
});
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
process.stdout.write(event.delta.text);
}
}
Define tools and let Claude call them:
tools = [
{
"name": "get_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"]
}
}
]
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in SF?"}]
)
# Handle tool use response
for block in message.content:
if block.type == "tool_use":
# Execute the tool with block.input
result = get_weather(**block.input)
# Send result back
follow_up = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in SF?"},
{"role": "assistant", "content": message.content},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": block.id, "content": str(result)}
]}
]
)
Send images for analysis:
import base64
with open("diagram.png", "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": image_data}},
{"type": "text", "text": "Describe this diagram"}
]
}]
)
For complex reasoning tasks:
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=16000,
thinking={
"type": "enabled",
"budget_tokens": 10000
},
messages=[{"role": "user", "content": "Solve this math problem step by step..."}]
)
for block in message.content:
if block.type == "thinking":
print(f"Thinking: {block.thinking}")
elif block.type == "text":
print(f"Answer: {block.text}")
Cache large system prompts or context to reduce costs:
message = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=1024,
system=[
{"type": "text", "text": large_system_prompt, "cache_control": {"type": "ephemeral"}}
],
messages=[{"role": "user", "content": "Question about the cached context"}]
)
# Check cache usage
print(f"Cache read: {message.usage.cache_read_input_tokens}")
print(f"Cache creation: {message.usage.cache_creation_input_tokens}")
Process large volumes asynchronously at 50% cost reduction:
import time
batch = client.messages.batches.create(
requests=[
{
"custom_id": f"request-{i}",
"params": {
"model": "claude-sonnet-4-0",
"max_tokens": 1024,
"messages": [{"role": "user", "content": prompt}]
}
}
for i, prompt in enumerate(prompts)
]
)
# Poll for completion
while True:
status = client.messages.batches.retrieve(batch.id)
if status.processing_status == "ended":
break
time.sleep(30)
# Get results
for result in client.messages.batches.results(batch.id):
print(result.result.message.content[0].text)
Build multi-step agents:
# Note: Agent SDK API surface may change — check official docs
import anthropic
# Define tools as functions
tools = [{
"name": "search_codebase",
"description": "Search the codebase for relevant code",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"]
}
}]
# Run an agentic loop with tool use
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Review the auth module for security issues"}]
while True:
response = client.messages.create(
model="claude-sonnet-4-0",
max_tokens=4096,
tools=tools,
messages=messages,
)
if response.stop_reason == "end_turn":
break
# Handle tool calls and continue the loop
messages.append({"role": "assistant", "content": response.content})
# ... execute tools and append tool_result messages
| Strategy | Savings | When to Use |
|---|---|---|
| Prompt caching | Up to 90% on cached tokens | Repeated system prompts or context |
| Batches API | 50% | Non-time-sensitive bulk processing |
| Haiku instead of Sonnet | ~75% | Simple tasks, classification, extraction |
| Shorter max_tokens | Variable | When you know output will be short |
| Streaming | None (same cost) | Better UX, same price |
import time
from anthropic import APIError, RateLimitError, APIConnectionError
try:
message = client.messages.create(...)
except RateLimitError:
# Back off and retry
time.sleep(60)
except APIConnectionError:
# Network issue, retry with backoff
pass
except APIError as e:
print(f"API error {e.status_code}: {e.message}")
# Required
export ANTHROPIC_API_KEY="your-api-key-here"
# Optional: set default model
export ANTHROPIC_MODEL="claude-sonnet-4-0"
Never hardcode API keys. Always use environment variables.
Weekly Installs
449
Repository
GitHub Stars
102.1K
First Seen
11 days ago
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex427
cursor373
gemini-cli369
github-copilot369
amp369
cline369
agent-browser 浏览器自动化工具 - Vercel Labs 命令行网页操作与测试
140,500 周安装