claude-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseClaude API (Anthropic Messages API)
Claude API(Anthropic Messages API)
Status: Production Ready | SDK: @anthropic-ai/sdk@0.70.1
状态:已就绪可用于生产环境 | SDK:@anthropic-ai/sdk@0.70.1
Quick Start (5 Minutes)
快速入门(5分钟)
Node.js
Node.js
typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
const message = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'Hello, Claude!' },
],
});
console.log(message.content[0].text);typescript
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
const message = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'Hello, Claude!' },
],
});
console.log(message.content[0].text);Cloudflare Workers
Cloudflare Workers
typescript
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'x-api-key': env.ANTHROPIC_API_KEY,
'anthropic-version': '2023-06-01',
'content-type': 'application/json',
},
body: JSON.stringify({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello!' }],
}),
});
const data = await response.json();
console.log(data.content[0].text);Load for complete setup with streaming, caching, and tools.
references/setup-guide.mdtypescript
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'x-api-key': env.ANTHROPIC_API_KEY,
'anthropic-version': '2023-06-01',
'content-type': 'application/json',
},
body: JSON.stringify({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello!' }],
}),
});
const data = await response.json();
console.log(data.content[0].text);如需了解包含流式传输、缓存和工具调用的完整设置,请查看 。
references/setup-guide.mdCritical Rules
重要规则
Always Do ✅
✅ 务必遵守
- Use environment variables for API keys (NEVER hardcode)
- Set max_tokens explicitly (required parameter)
- Pin model version (, not
claude-sonnet-4-5-20250929)claude-3-5-sonnet-latest - Enable prompt caching for repeated content (90% cost savings)
- Stream long responses () for better UX
stream: true - Handle errors - Implement retry logic for 429, 529 errors
- Validate inputs - Sanitize user messages before sending
- Monitor costs - Track token usage
- Set timeouts - Prevent hanging requests
- Use tool use properly - Return tool_result in follow-up message
- 使用环境变量存储API密钥(绝对不要硬编码)
- 显式设置max_tokens(必填参数)
- 固定模型版本(使用,而非
claude-sonnet-4-5-20250929)claude-3-5-sonnet-latest - 针对重复内容启用提示词缓存(可节省90%成本)
- 对长响应使用流式传输(设置以提升用户体验)
stream: true - 处理错误 - 为429、529错误实现重试逻辑
- 验证输入 - 在发送前清理用户消息
- 监控成本 - 跟踪令牌使用量
- 设置超时 - 防止请求挂起
- 正确使用工具调用 - 在后续消息中返回tool_result
Never Do ❌
❌ 绝对禁止
- Never expose API key in client-side code
- Never skip max_tokens - API will error without it
- Never ignore stop_reason - Check for ,
tool_use,end_turnmax_tokens - Never assume single content block - is an array
content - Never use outdated models - Pin to specific version
- Never skip error handling - API calls can fail
- Never mix message roles - Alternate user/assistant correctly
- Never ignore rate limits - Implement exponential backoff
- Never store API keys in logs or databases
- Never skip input validation - Prevent injection attacks
- 绝不在客户端代码中暴露API密钥
- 绝不省略max_tokens - 缺少该参数API会报错
- 绝不忽略stop_reason - 检查是否为、
tool_use或end_turnmax_tokens - 绝不假设content是单个块 - 是一个数组
content - 绝不使用过时模型 - 固定到特定版本
- 绝不跳过错误处理 - API调用可能失败
- 绝不混合消息角色 - 正确交替user/assistant角色
- 绝不忽略速率限制 - 实现指数退避机制
- 绝不将API密钥存储在日志或数据库中
- 绝不跳过输入验证 - 防止注入攻击
Top 3 Errors (Prevent 80% of Issues)
三大常见错误(可避免80%的问题)
Error #1: Rate Limit 429
错误 #1:速率限制 429
Symptom:
429 Too Many Requests: Number of request tokens has exceeded your per-minute rate limitSolution: Implement exponential backoff with retry-after header
typescript
async function handleRateLimit(requestFn, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await requestFn();
} catch (error) {
if (error.status === 429) {
const retryAfter = error.response?.headers?.['retry-after'];
const delay = retryAfter ? parseInt(retryAfter) * 1000 : 1000 * Math.pow(2, attempt);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
throw error;
}
}
}
}Prevention: Monitor rate limit headers, upgrade tier, implement backoff
症状:
429 Too Many Requests: Number of request tokens has exceeded your per-minute rate limit解决方案:结合retry-after头实现指数退避机制
typescript
async function handleRateLimit(requestFn, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await requestFn();
} catch (error) {
if (error.status === 429) {
const retryAfter = error.response?.headers?.['retry-after'];
const delay = retryAfter ? parseInt(retryAfter) * 1000 : 1000 * Math.pow(2, attempt);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
throw error;
}
}
}
}预防措施:监控速率限制头信息、升级套餐、实现退避机制
Error #2: Prompt Caching Not Activating
错误 #2:提示词缓存未激活
Symptom: High costs despite blocks,
cache_controlcache_read_input_tokens: 0Solution: Place on LAST block with >= 1024 tokens
cache_controltypescript
// ❌ Wrong - cache_control not at end
{
type: 'text',
text: DOCUMENT,
cache_control: { type: 'ephemeral' }, // Wrong position
},
{
type: 'text',
text: 'Additional text',
}
// ✅ Correct - cache_control at end
{
type: 'text',
text: DOCUMENT + '\n\nAdditional text',
cache_control: { type: 'ephemeral' }, // Correct position
}Prevention: Ensure content >= 1024 tokens, keep cached content identical, monitor usage
Load for complete caching strategy.
references/prompt-caching-guide.md症状:已设置块但成本仍居高不下,
cache_controlcache_read_input_tokens: 0解决方案:将放在最后一个令牌数≥1024的块上
cache_controltypescript
// ❌ 错误示例 - cache_control未放在末尾
{
type: 'text',
text: DOCUMENT,
cache_control: { type: 'ephemeral' }, // 位置错误
},
{
type: 'text',
text: 'Additional text',
}
// ✅ 正确示例 - cache_control放在末尾
{
type: 'text',
text: DOCUMENT + '\n\nAdditional text',
cache_control: { type: 'ephemeral' }, // 位置正确
}预防措施:确保内容令牌数≥1024、保持缓存内容完全一致、监控使用情况
如需完整缓存策略,请查看 。
references/prompt-caching-guide.mdError #3: Tool Use Response Format Errors
错误 #3:工具调用响应格式错误
Symptom:
invalid_request_error: tools[0].input_schema is invalidSolution: Valid tool schema with proper JSON Schema
typescript
// ✅ Valid tool schema
{
name: 'get_weather',
description: 'Get current weather',
input_schema: {
type: 'object', // Must be 'object'
properties: {
location: {
type: 'string', // Valid JSON Schema types
description: 'City' // Optional but recommended
}
},
required: ['location'] // List required fields
}
}
// ✅ Valid tool result
{
type: 'tool_result',
tool_use_id: block.id, // Must match tool_use id
content: JSON.stringify(result) // Convert to string
}Prevention: Validate schemas, match tool_use_id exactly, stringify results
Load + for all 12 errors.
references/tool-use-patterns.mdreferences/top-errors.md症状:
invalid_request_error: tools[0].input_schema is invalid解决方案:使用符合JSON Schema规范的有效工具架构
typescript
// ✅ 有效工具架构
{
name: 'get_weather',
description: 'Get current weather',
input_schema: {
type: 'object', // 必须为'object'
properties: {
location: {
type: 'string', // 有效JSON Schema类型
description: 'City' // 可选但推荐添加
}
},
required: ['location'] // 列出必填字段
}
}
// ✅ 有效工具结果
{
type: 'tool_result',
tool_use_id: block.id, // 必须与tool_use的id匹配
content: JSON.stringify(result) // 转换为字符串
}预防措施:验证架构、确保tool_use_id完全匹配、将结果转为字符串
如需了解全部12种错误,请查看 和 。
references/tool-use-patterns.mdreferences/top-errors.mdCommon Use Cases (Quick Patterns)
常见使用场景(快速示例)
Streaming Responses
流式响应
typescript
const stream = await client.messages.stream({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Write a story.' }],
});
for await (const event of stream) {
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
process.stdout.write(event.delta.text);
}
}Load:
templates/streaming-chat.tstypescript
const stream = await client.messages.stream({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Write a story.' }],
});
for await (const event of stream) {
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
process.stdout.write(event.delta.text);
}
}查看模板:
templates/streaming-chat.tsPrompt Caching (90% Cost Savings)
提示词缓存(节省90%成本)
typescript
const message = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
system: [
{
type: 'text',
text: 'Long system prompt...',
cache_control: { type: 'ephemeral' },
},
],
messages: [{ role: 'user', content: 'Question?' }],
});Cache lasts 5 minutes, 90% savings on cached tokens
Load: +
references/prompt-caching-guide.mdtemplates/prompt-caching.tstypescript
const message = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
system: [
{
type: 'text',
text: 'Long system prompt...',
cache_control: { type: 'ephemeral' },
},
],
messages: [{ role: 'user', content: 'Question?' }],
});缓存有效期5分钟,缓存令牌可节省90%成本
查看资源: +
references/prompt-caching-guide.mdtemplates/prompt-caching.tsTool Use (Function Calling)
工具调用(函数调用)
typescript
const message = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
tools: [{
name: 'get_weather',
description: 'Get weather for a location',
input_schema: {
type: 'object',
properties: { location: { type: 'string' } },
required: ['location'],
},
}],
messages: [{ role: 'user', content: 'Weather in SF?' }],
});
if (message.stop_reason === 'tool_use') {
const toolUse = message.content.find(b => b.type === 'tool_use');
// Execute tool and send result back...
}Load: +
references/tool-use-patterns.mdtemplates/tool-use-basic.tstypescript
const message = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
tools: [{
name: 'get_weather',
description: 'Get weather for a location',
input_schema: {
type: 'object',
properties: { location: { type: 'string' } },
required: ['location'],
},
}],
messages: [{ role: 'user', content: 'Weather in SF?' }],
});
if (message.stop_reason === 'tool_use') {
const toolUse = message.content.find(b => b.type === 'tool_use');
// 执行工具并返回结果...
}查看资源: +
references/tool-use-patterns.mdtemplates/tool-use-basic.tsVision (Image Understanding)
视觉功能(图像理解)
typescript
const message = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{
role: 'user',
content: [
{
type: 'image',
source: {
type: 'base64',
media_type: 'image/jpeg',
data: base64Image,
},
},
{ type: 'text', text: 'What is in this image?' },
],
}],
});Supports: JPEG, PNG, WebP, GIF (max 5MB)
Load: +
references/vision-capabilities.mdtemplates/vision-image.tstypescript
const message = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{
role: 'user',
content: [
{
type: 'image',
source: {
type: 'base64',
media_type: 'image/jpeg',
data: base64Image,
},
},
{ type: 'text', text: 'What is in this image?' },
],
}],
});支持格式:JPEG、PNG、WebP、GIF(最大5MB)
查看资源: +
references/vision-capabilities.mdtemplates/vision-image.tsExtended Thinking Mode
扩展思考模式
typescript
const message = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 4096,
thinking: {
type: 'enabled',
budget_tokens: 2000,
},
messages: [{ role: 'user', content: 'Solve complex problem...' }],
});
const thinking = message.content.find(b => b.type === 'thinking')?.thinking;
const answer = message.content.find(b => b.type === 'text')?.text;Load:
templates/extended-thinking.tstypescript
const message = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 4096,
thinking: {
type: 'enabled',
budget_tokens: 2000,
},
messages: [{ role: 'user', content: 'Solve complex problem...' }],
});
const thinking = message.content.find(b => b.type === 'thinking')?.thinking;
const answer = message.content.find(b => b.type === 'text')?.text;查看模板:
templates/extended-thinking.tsModel Versions (Current)
当前可用模型版本
Latest models:
- - Recommended (best performance)
claude-sonnet-4-5-20250929 - - Stable version
claude-sonnet-4-20250514 - - Previous generation
claude-3-7-sonnet-20250219 - - Legacy
claude-3-5-sonnet-20241022
Always pin to specific version (not suffix)
-latest最新模型:
- - 推荐使用(性能最佳)
claude-sonnet-4-5-20250929 - - 稳定版本
claude-sonnet-4-20250514 - - 上一代模型
claude-3-7-sonnet-20250219 - - 旧版模型
claude-3-5-sonnet-20241022
务必固定到特定版本(不要使用后缀)
-latestWhen to Load References
何时查看参考文档
Load references/setup-guide.md
when:
references/setup-guide.md查看 references/setup-guide.md
的场景:
references/setup-guide.md- First-time Claude API user needing complete setup walkthrough
- Setting up Node.js or Cloudflare Workers from scratch
- Need production deployment checklist and platform-specific tips
- Troubleshooting basic setup issues (API keys, authentication, environment)
- 首次使用Claude API,需要完整设置指南
- 从零开始搭建Node.js或Cloudflare Workers环境
- 需要生产部署清单和平台特定技巧
- 排查基础设置问题(API密钥、身份验证、环境配置)
Load references/prompt-caching-guide.md
when:
references/prompt-caching-guide.md查看 references/prompt-caching-guide.md
的场景:
references/prompt-caching-guide.md- Want to reduce costs by 90% on repeated content
- Using large system prompts, documents, or codebases in context
- Need detailed caching strategy with benchmarks and cost calculations
- Optimizing multi-turn conversations with conversation history caching
- Troubleshooting cache activation issues or cache misses
- 希望通过重复内容节省90%成本
- 在上下文使用大型系统提示词、文档或代码库
- 需要包含基准测试和成本计算的详细缓存策略
- 优化包含对话历史缓存的多轮对话
- 排查缓存激活问题或缓存未命中情况
Load references/tool-use-patterns.md
when:
references/tool-use-patterns.md查看 references/tool-use-patterns.md
的场景:
references/tool-use-patterns.md- Implementing function calling and tool definitions
- Need tool execution loop patterns and multi-turn tool use
- Want Zod validation examples for type-safe tools
- Troubleshooting tool use response format errors
- 实现函数调用和工具定义
- 需要工具执行循环模式和多轮工具调用示例
- 想要Zod验证示例以实现类型安全工具
- 排查工具调用响应格式错误
Load references/vision-capabilities.md
when:
references/vision-capabilities.md查看 references/vision-capabilities.md
的场景:
references/vision-capabilities.md- Processing images with Claude (OCR, analysis, description)
- Need image format requirements and validation logic
- Want vision use cases and best practices
- Combining vision with tools or prompt caching
- 使用Claude处理图像(OCR、分析、描述)
- 需要了解图像格式要求和验证逻辑
- 想要视觉功能使用场景和最佳实践
- 将视觉功能与工具调用或提示词缓存结合使用
Load references/api-reference.md
when:
references/api-reference.md查看 references/api-reference.md
的场景:
references/api-reference.md- Need complete API parameter reference and request/response schemas
- Looking up specific fields or content block types
- Want endpoint details, authentication headers, or model IDs
- Need streaming event types and SSE format details
- 需要完整的API参数参考和请求/响应架构
- 查询特定字段或内容块类型
- 了解端点详情、身份验证头或模型ID
- 需要流式事件类型和SSE格式详情
Load references/top-errors.md
when:
references/top-errors.md查看 references/top-errors.md
的场景:
references/top-errors.md- Encountering API errors (all 12 documented errors with solutions)
- Need error code reference (400, 401, 429, 529, etc.)
- Want comprehensive prevention strategies
- Implementing robust error handling and retry logic
- 遇到API错误(包含12种已记录错误及解决方案)
- 需要错误代码参考(400、401、429、529等)
- 想要全面的预防策略
- 实现健壮的错误处理和重试逻辑
Load references/rate-limits.md
when:
references/rate-limits.md查看 references/rate-limits.md
的场景:
references/rate-limits.md- Planning high-volume usage and scaling strategy
- Encountering 429 rate limit errors repeatedly
- Need tier limits information and upgrade path
- Optimizing request patterns to stay within limits
- 规划高容量使用和扩展策略
- 反复遇到429速率限制错误
- 需要了解套餐限制信息和升级路径
- 优化请求模式以符合限制要求
Using Bundled Resources
使用捆绑资源
References (references/)
参考文档(references/)
- setup-guide.md - Complete setup (Node.js + Cloudflare Workers + Next.js)
- api-reference.md - Complete API parameter reference + schemas
- prompt-caching-guide.md - 90% cost savings guide + benchmarks
- tool-use-patterns.md - Function calling patterns + Zod examples
- vision-capabilities.md - Image understanding guide + validation
- top-errors.md - All 12 errors with solutions + prevention
- rate-limits.md - Limits by tier + best practices
- setup-guide.md - 完整设置指南(Node.js + Cloudflare Workers + Next.js)
- api-reference.md - 完整API参数参考 + 架构
- prompt-caching-guide.md - 节省90%成本指南 + 基准测试
- tool-use-patterns.md - 函数调用模式 + Zod示例
- vision-capabilities.md - 图像理解指南 + 验证
- top-errors.md - 全部12种错误及解决方案 + 预防措施
- rate-limits.md - 各套餐限制 + 最佳实践
Templates (templates/)
模板(templates/)
- basic-chat.ts - Simple chat example
- streaming-chat.ts - Streaming implementation with SSE
- prompt-caching.ts - Caching example with benchmarks
- tool-use-basic.ts - Basic tool use pattern
- tool-use-advanced.ts - Advanced multi-turn tool patterns
- vision-image.ts - Vision example with validation
- extended-thinking.ts - Extended thinking mode
- error-handling.ts - Complete error handling
- nodejs-example.ts - Complete Node.js app
- cloudflare-worker.ts - Complete CF Worker
- nextjs-api-route.ts - Next.js API route
- package.json - Dependencies
- basic-chat.ts - 简单聊天示例
- streaming-chat.ts - 基于SSE的流式传输实现
- prompt-caching.ts - 缓存示例 + 基准测试
- tool-use-basic.ts - 基础工具调用模式
- tool-use-advanced.ts - 高级多轮工具调用模式
- vision-image.ts - 视觉功能示例 + 验证
- extended-thinking.ts - 扩展思考模式示例
- error-handling.ts - 完整错误处理示例
- nodejs-example.ts - 完整Node.js应用示例
- cloudflare-worker.ts - 完整Cloudflare Worker示例
- nextjs-api-route.ts - Next.js API路由示例
- package.json - 依赖清单
Platform Integration
平台集成
Node.js: → Use templates: ,
bun add @anthropic-ai/sdknodejs-example.tsbasic-chat.tsCloudflare Workers: Use fetch API → Use templates:
cloudflare-worker.tsNext.js: → Use templates:
bun add @anthropic-ai/sdknextjs-api-route.tsNode.js: → 使用模板:,
bun add @anthropic-ai/sdknodejs-example.tsbasic-chat.tsCloudflare Workers:使用fetch API → 使用模板:
cloudflare-worker.tsNext.js: → 使用模板:
bun add @anthropic-ai/sdknextjs-api-route.tsProduction Checklist
生产环境检查清单
- API key stored securely (environment variable)
- Error handling implemented (401, 429, 400, 529)
- Rate limiting with exponential backoff
- Prompt caching enabled for repeated content
- Streaming for long responses
- Input validation + output sanitization
- Monitoring and cost tracking
- Timeouts configured
- Model version pinned
- max_tokens set appropriately
- API密钥已安全存储(环境变量)
- 已实现错误处理(401、429、400、529)
- 已配置速率限制与指数退避
- 已为重复内容启用提示词缓存
- 已为长响应启用流式传输
- 已实现输入验证 + 输出清理
- 已配置监控和成本跟踪
- 已设置超时
- 已固定模型版本
- 已合理设置max_tokens
Related Skills
相关技能
- openai-api - OpenAI Chat Completions for comparison
- claude-agent-sdk - Higher-level Claude SDK
- ai-sdk-core - Vercel AI SDK (supports Claude)
- openai-api - 用于对比的OpenAI聊天补全API
- claude-agent-sdk - 更高阶的Claude SDK
- ai-sdk-core - Vercel AI SDK(支持Claude)
Official Documentation
官方文档
- Messages API: https://docs.anthropic.com/en/api/messages
- Prompt Caching: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
- Tool Use: https://docs.anthropic.com/en/docs/build-with-claude/tool-use
- Vision: https://docs.anthropic.com/en/docs/build-with-claude/vision
- Extended Thinking: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
Questions? Issues?
- Check for error solutions
references/top-errors.md - Review for complete setup
references/setup-guide.md - See for cost optimization
references/prompt-caching-guide.md - Load templates from for working examples
templates/
- Messages API:https://docs.anthropic.com/en/api/messages
- Prompt Caching:https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
- Tool Use:https://docs.anthropic.com/en/docs/build-with-claude/tool-use
- Vision:https://docs.anthropic.com/en/docs/build-with-claude/vision
- Extended Thinking:https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
有疑问?遇到问题?
- 查看获取错误解决方案
references/top-errors.md - 查看获取完整设置指南
references/setup-guide.md - 查看获取成本优化方案
references/prompt-caching-guide.md - 从加载可用模板获取工作示例
templates/