关于 claude-api
面向 Anthropic TypeScript SDK 开发者的参考技能,侧重结构化输出和常见 API 错误预防。内容涵盖请求模式、模型变更、流式响应、缓存、工具调用与故障排查。
主要功能
- 01结构化输出与严格工具调用
- 02流式响应错误处理
- 03提示词缓存指南
- 04模型与 API 变更说明
- 05速率限制与错误恢复
适用场景
- 01校验 JSON 格式的 API 响应
- 02处理 SSE 流中的错误
- 03减少重复提示词处理
- 04排查速率限制与请求故障
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ ovachiever/ droid-tings --skill claude-api安装后在 Claude Code 中输入/claude-api确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
README.md.claude-plugin/plugin.jsonreferences/api-reference.mdprompt-caching-guide.mdrate-limits.mdtool-use-patterns.mdtop-errors.mdvision-capabilities.mdscripts/check-versions.shtemplates/basic-chat.tscloudflare-worker.tserror-handling.tsextended-thinking.tsnextjs-api-route.tsnodejs-example.tspackage.jsonprompt-caching.tsstreaming-chat.tstool-use-advanced.tstool-use-basic.tsvision-image.tswrangler.jsonc详细介绍
Claude API - 结构化输出与错误预防指南
软件包:@anthropic-ai/[email protected](2025 年 11 月 20 日) 重大变更:2025 年 10 月 - Claude 3.5/3.7 模型退役;2025 年 11 月 - 结构化输出 Beta 版 最后更新:2025-11-22
v0.69.0+ 新增内容(2025 年 11 月)
主要功能:
1. 结构化输出(v0.69.0,2025 年 11 月 14 日)- 至关重要 ⭐
保证符合 JSON 架构 - Claude 的响应严格遵循你的 JSON 架构,有两种模式:
JSON 输出(output_format) - 用于数据提取和格式化:
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Extract contact info: John Doe, [email protected], 555-1234' }],
betas: ['structured-outputs-2025-11-13'],
output_format: {
type: 'json_schema',
json_schema: {
name: 'Contact',
strict: true,
schema: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string' },
phone: { type: 'string' }
},
required: ['name', 'email', 'phone'],
additionalProperties: false
}
}
}
});
// Guaranteed valid JSON matching schema
const contact = JSON.parse(message.content[0].text);
console.log(contact.name); // "John Doe"
严格工具使用(strict: true) - 用于经过验证的函数参数:
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Get weather for San Francisco' }],
betas: ['structured-outputs-2025-11-13'],
tools: [{
name: 'get_weather',
description: 'Get current weather',
input_schema: {
type: 'object',
properties: {
location: { type: 'string' },
unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }
},
required: ['location'],
additionalProperties: false
},
strict: true // ← Guarantees schema compliance
}]
});
要求:
- Beta 标头:
structured-outputs-2025-11-13(通过betas数组) - 模型:仅限 Claude Sonnet 4.5、Claude Opus 4.1
- SDK:需要 v0.69.0+
限制:
- ❌ 不支持递归架构
- ❌ 不支持数值约束(
minimum、maximum) - ❌ 正则表达式支持有限(不支持反向引用/前瞻断言)
- ❌ 与引用和消息预填充不兼容
- ⚠️ 语法编译会增加首次请求的延迟(缓存 24 小时)
适用场景:
- 从非结构化文本中提取数据
- 格式化 API 响应
- 需要经过验证的工具输入的 Agent 工作流
- 消除 JSON 解析错误
2. 模型变更(2025 年 10 月)- 重大变更
已退役(会返回错误):
- ❌ Claude 3.5 Sonnet(所有版本)
- ❌ Claude 3.7 Sonnet - 已弃用(2025 年 10 月 28 日)
当前可用模型(2025 年 11 月):
| 模型 | ID | 上下文 | 适用场景 | 费用(每 MTok) |
|---|---|---|---|---|
| Claude Sonnet 4.5 | claude-sonnet-4-5-20250929 | 200k | 性能均衡 | $3/$15(输入/输出) |
| Claude Opus 4 | claude-opus-4-20250514 | 200k | 能力最强 | $15/$75 |
| Claude Haiku 4.5 | claude-3-5-haiku-20241022 | 200k | 接近前沿水平,速度快 | $1/$5 |
3. 上下文管理(2025 年 10 月 28 日)
清理思考块 - 自动清理思考块:
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 4096,
messages: [{ role: 'user', content: 'Solve complex problem' }],
betas: ['clear_thinking_20251015']
});
// Thinking blocks automatically managed
4. Agent Skills API(2025 年 10 月 16 日)
适用于 Office 文件(PowerPoint、Excel、Word、PDF)的预构建技能:
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Analyze this spreadsheet' }],
betas: ['skills-2025-10-02'],
// Requires code execution tool enabled
});
📚 文档:https://platform.claude.com/docs/en/build-with-claude/structured-outputs
流式响应(SSE)
至关重要的错误模式 - 错误会在初始的 200 响应之后发生:
const stream = anthropic.messages.stream({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello' }],
});
stream
.on('error', (error) => {
// Error can occur AFTER stream starts
console.error('Stream error:', error);
// Implement fallback or retry logic
})
.on('abort', (error) => {
console.warn('Stream aborted:', error);
});
原因:与常规 HTTP 错误不同,SSE 错误会在 200 OK 响应之后、数据流传输过程中发生,因此需要错误事件监听器。
提示词缓存(⭐ 节省 90% 费用)
至关重要的规则 - cache_control 必须放在最后一个块上:
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
system: [
{
type: 'text',
text: 'System instructions...',
},
{
type: 'text',
text: LARGE_CODEBASE, // 50k tokens
cache_control: { type: 'ephemeral' }, // ← MUST be on LAST block
},
],
messages: [{ role: 'user', content: 'Explain auth module' }],
});
// Monitor cache usage
console.log('Cache reads:', message.usage.cache_read_input_tokens);
console.log('Cache writes:', message.usage.cache_creation_input_tokens);
最低要求:
- Claude Sonnet 4.5:至少 1,024 个 Token
- Claude Haiku 4.5:至少 2,048 个 Token
- TTL 为 5 分钟(每次使用时刷新)
- 仅当内容完全相同时才共享缓存
工具使用(函数调用)
至关重要的模式:
严格工具使用(配合结构化输出):
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
betas: ['structured-outputs-2025-11-13'],
tools: [{
name: 'get_weather',
description: 'Get weather data',
input_schema: {
type: 'object',
properties: {
location: { type: 'string' },
unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }
},
required: ['location'],
additionalProperties: false
},
strict: true // ← Guarantees schema compliance
}],
messages: [{ role: 'user', content: 'Weather in NYC?' }]
});
工具结果模式 - tool_use_id 必须匹配:
const toolResults = [];
for (const block of response.content) {
if (block.type === 'tool_use') {
const result = await executeToolFunction(block.name, block.input);
toolResults.push({
type: 'tool_result',
tool_use_id: block.id, // ← MUST match tool_use block id
content: JSON.stringify(result),
});
}
}
messages.push({
role: 'user',
content: toolResults,
});
错误处理 - 处理工具执行失败:
try {
const result = await executeToolFunction(block.name, block.input);
toolResults.push({
type: 'tool_result',
tool_use_id: block.id,
content: JSON.stringify(result),
});
} catch (error) {
// Return error to Claude for handling
toolResults.push({
type: 'tool_result',
tool_use_id: block.id,
is_error: true,
content: `Tool execution failed: ${error.message}`,
});
}
视觉能力(图像理解)
至关重要的规则:
- 格式:JPEG、PNG、WebP、GIF(非动画)
- 最大大小:每张图像 5MB
- Base64 开销:大小增加约 33%
- 上下文影响:图像会计入 Token 限额
- 缓存:重复分析图像时可考虑使用
格式验证 - 编码前进行检查:
const validFormats = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
if (!validFormats.includes(mimeType)) {
throw new Error(`Unsupported format: ${mimeType}`);
}
扩展思考模式
⚠️ 模型兼容性:
- ❌ Claude 3.7 Sonnet - 已弃用(2025 年 10 月 28 日)
- ❌ Claude 3.5 Sonnet - 已退役(不受支持)
- ✅ Claude Sonnet 4.5 - 支持扩展思考
- ✅ Claude Opus 4 - 支持扩展思考
至关重要:
- 思考块不可缓存
- 需要较高的
max_tokens(思考过程会消耗 Token) - 预期会收到思考块前,请先检查模型
速率限制
关键模式 —— 遵循 retry-after 标头,并采用指数退避:
async function makeRequestWithRetry(
requestFn: () => Promise<any>,
maxRetries = 3,
baseDelay = 1000
): Promise<any> {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await requestFn();
} catch (error) {
if (error.status === 429) {
// CRITICAL: Use retry-after header if present
const retryAfter = error.response?.headers?.['retry-after'];
const delay = retryAfter
? parseInt(retryAfter) * 1000
: baseDelay * Math.pow(2, attempt);
console.warn(`Rate limited. Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
throw error;
}
}
}
throw new Error('Max retries exceeded');
}
速率限制标头:
anthropic-ratelimit-requests-limit- 允许的 RPM 总量anthropic-ratelimit-requests-remaining- 剩余请求数anthropic-ratelimit-requests-reset- 重置时间戳
错误处理
常见错误代码:
| 状态 | 错误类型 | 原因 | 解决方案 |
|---|---|---|---|
| 400 | invalid_request_error | 参数错误 | 验证请求正文 |
| 401 | authentication_error | API 密钥无效 | 检查环境变量 |
| 403 | permission_error | 无权使用此功能 | 检查账户等级 |
| 404 | not_found_error | 端点无效 | 检查 API 版本 |
| 429 | rate_limit_error | 请求过多 | 实现重试逻辑 |
| 500 | api_error | 内部错误 | 采用退避策略重试 |
| 529 | overloaded_error | 系统过载 | 稍后重试 |
关键:
- 流式错误会在初始的 200 响应之后发生
- 始终为数据流实现错误事件监听器
- 对 429 错误遵循
retry-after标头 - 为关键操作准备备用策略
已知问题预防
此技能可预防 12 个已记录的问题:
问题 #1:未采用退避策略的 429 速率限制错误
错误:429 Too Many Requests: Number of request tokens has exceeded your per-minute rate limit
来源:https://docs.claude.com/en/api/errors
发生原因:超出 RPM、TPM 或每日令牌限额
预防措施:实现指数退避,并遵循 retry-after 标头
问题 #2:流式 SSE 解析错误
错误:数据块不完整,SSE 事件格式错误 来源:常见 SDK 问题(GitHub #323) 发生原因:网络中断、事件解析不当 预防措施:使用 SDK 流式辅助工具,并实现错误事件监听器
问题 #3:提示词缓存未启用
错误:尽管设置了 cache_control 块,成本仍然很高
来源:https://platform.claude.com/docs/en/build-with-claude/prompt-caching
发生原因:cache_control 的位置不正确(必须放在末尾)
预防措施:始终将 cache_control 放在可缓存内容的最后一个块上
问题 #4:工具使用响应格式错误
错误:invalid_request_error: tools[0].input_schema is invalid
来源:API 验证错误
发生原因:JSON Schema 无效、缺少必填字段
预防措施:使用 JSON Schema 验证器验证架构,并进行全面测试
问题 #5:视觉图像格式问题
错误:invalid_request_error: image source must be base64 or url
来源:API 文档
发生原因:编码不正确、格式不受支持
预防措施:验证格式(JPEG/PNG/WebP/GIF),确保 base64 编码正确
问题 #6:计费令牌计数不匹配
错误:成本意外偏高、超出上下文窗口 来源:令牌计数差异 发生原因:未考虑特殊令牌和格式 预防措施:使用官方令牌计数器,并监控用量标头
问题 #7:系统提示词顺序问题
错误:系统提示词被忽略或覆盖 来源:API 行为 发生原因:系统提示词放在消息数组之后 预防措施:务必将系统提示词放在消息之前
问题 #8:超出上下文窗口(200k)
错误:invalid_request_error: messages: too many tokens
来源:模型限制
发生原因:长对话未进行裁剪
预防措施:裁剪消息历史,并使用缓存
问题 #9:在错误的模型上启用扩展思考
错误:响应中没有思考块 来源:模型能力 发生原因:使用已退役或已弃用的模型(3.5/3.7 Sonnet) 预防措施:仅在 Claude Sonnet 4.5 或 Claude Opus 4 上使用扩展思考
问题 #10:客户端代码中暴露 API Key
错误:CORS 错误、安全漏洞 来源:安全最佳实践 原因:从浏览器发起 API 调用 预防:仅在服务端调用,使用环境变量
问题 #11:混淆速率限制等级
错误:限制低于预期 来源:账户等级系统 原因:不了解等级提升机制 预防:在 Console 中查看当前等级;等级会随用量自动提升
问题 #12:缺少 Message Batches Beta 标头
错误:invalid_request_error: unknown parameter: batches
来源:Beta API 要求
原因:缺少 anthropic-beta 标头
预防:加入 anthropic-beta: message-batches-2024-09-24 标头
官方文档
- Claude API:https://platform.claude.com/docs/en/api
- Messages API:https://platform.claude.com/docs/en/api/messages
- 结构化输出:https://platform.claude.com/docs/en/build-with-claude/structured-outputs
- 提示词缓存:https://platform.claude.com/docs/en/build-with-claude/prompt-caching
- 工具使用:https://platform.claude.com/docs/en/build-with-claude/tool-use
- 视觉:https://platform.claude.com/docs/en/build-with-claude/vision
- 速率限制:https://platform.claude.com/docs/en/api/rate-limits
- 错误:https://platform.claude.com/docs/en/api/errors
- TypeScript SDK:https://github.com/anthropics/anthropic-sdk-typescript
- Context7 Library ID:/anthropics/anthropic-sdk-typescript
软件包版本
最新版本:@anthropic-ai/[email protected](2025 年 11 月 20 日)
{
"dependencies": {
"@anthropic-ai/sdk": "^0.70.1"
},
"devDependencies": {
"@types/node": "^20.0.0",
"typescript": "^5.3.0",
"zod": "^3.23.0"
}
}
Token 效率:
- 不使用 skill:约 8,000 个 token(基础设置、流式传输、缓存、工具、视觉、错误)
- 使用 skill:约 4,200 个 token(知识盲区 + 错误预防 + 关键模式)
- 节省:约 48%(约 3,800 个 token)
预防的错误:12 个已记录问题及其确切解决方案 核心价值:结构化输出(v0.69.0+)、模型弃用(2025 年 10 月)、提示词缓存边缘情况、流式错误模式、速率限制重试逻辑
上次验证:2025-11-22 | Skill 版本:2.0.0 | 更改:添加结构化输出(v0.69.0),更新模型表(弃用 3.5/3.7),新增上下文管理和 Agent skills API。移除基础教程(约 380 行)。重点关注知识盲区 + 错误预防 + 高级模式。