关于 claude-api
面向 TypeScript 开发者的 Claude API 实践指南,重点介绍结构化输出、工具调用、流式响应和提示词缓存。指南还整理模型变更、速率限制及常见错误的处理方式。
主要功能
- 01生成符合 JSON Schema 的结构化输出
- 02使用严格模式验证工具参数
- 03处理 SSE 流式响应和错误
- 04配置提示词缓存
- 05实现速率限制重试与错误处理
适用场景
- 01从非结构化文本提取字段
- 02为 API 响应生成固定格式
- 03构建需要验证工具输入的 Agent 工作流
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ jezweb/ claude-skills --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.mdrules/claude-api.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.ts详细介绍
Claude API - 结构化输出与错误预防指南
软件包:@anthropic-ai/[email protected] 重大变更:2025 年 10 月 - Claude 3.5/3.7 模型退役;2025 年 11 月 - 结构化输出 Beta 版 最后更新:2026-01-09
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 Opus 4.5、Claude Sonnet 4.5、Claude Opus 4(仅限最佳模型)
- SDK:需要 v0.69.0+
限制:
- ❌ 不支持递归架构
- ❌ 不支持数值约束(
minimum、maximum) - ❌ 正则表达式支持有限(不支持反向引用/前瞻断言)
- ❌ 与引用和消息预填充不兼容
- ⚠️ 语法编译会增加首次请求的延迟(缓存 24 小时)
性能特征:
- 首次请求:语法编译会增加 200-500ms 延迟
- 后续请求:延迟正常(语法缓存 24 小时)
- 缓存共享:仅适用于完全相同的架构(细微改动也会导致重新编译)
预热关键架构:
// Pre-compile schemas during server startup
const warmupMessage = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 10,
messages: [{ role: 'user', content: 'warmup' }],
betas: ['structured-outputs-2025-11-13'],
output_format: {
type: 'json_schema',
json_schema: YOUR_CRITICAL_SCHEMA
}
});
// Later requests use cached grammar
语义验证(关键):
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
messages: [{ role: 'user', content: 'Extract contact: John Doe' }],
betas: ['structured-outputs-2025-11-13'],
output_format: {
type: 'json_schema',
json_schema: contactSchema
}
});
const contact = JSON.parse(message.content[0].text);
// ✅ Format is guaranteed valid
// ❌ Content may be hallucinated
// ALWAYS validate semantic correctness
if (!isValidEmail(contact.email)) {
throw new Error('Hallucinated email detected');
}
if (contact.age < 0 || contact.age > 120) {
throw new Error('Implausible age value');
}
适用场景:
- 从非结构化文本中提取数据
- 格式化 API 响应
- 需要验证工具输入的 Agent 工作流
- 消除 JSON 解析错误
⚠️ SDK v0.71.1+ 弃用事项:直接访问 .parsed 属性已弃用。请查阅 SDK 文档,了解更新后的 API。
2. 模型变更(2025 年 10 月)- 重大变更
已退役(会返回错误):
- ❌ Claude 3.5 Sonnet(所有版本)
- ❌ Claude 3.7 Sonnet - 已弃用(2025 年 10 月 28 日)
可用模型(2026 年 1 月):
| 模型 | ID | 上下文 | 最适用于 | 费用(每 MTok) |
|---|---|---|---|---|
| Claude Opus 4.5 | claude-opus-4-5-20251101 | 200k | 旗舰模型 - 最佳推理、编码和 Agent 能力 | $5/$25(输入/输出) |
| 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-haiku-4-5-20250929 | 200k | 接近前沿水平,速度快 | $1/$5 |
注意:Claude 3.x 模型(3.5 Sonnet、3.7 Sonnet 等)已弃用。请使用 Claude 4.x+ 模型。
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 个令牌
- Claude Haiku 4.5:至少 2,048 个令牌
- 5 分钟 TTL(每次使用时刷新)
- 仅在内容完全相同时共享缓存
⚠️ AWS Bedrock 限制:Claude 4 系列在 AWS Bedrock 上不支持提示词缓存(仅 Claude 3.7 Sonnet 支持)。如需在 Claude 4 上使用缓存,请直接使用 Anthropic API。(GitHub Issue #1347)
工具使用(函数调用)
关键模式:
严格工具使用(带结构化输出):
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}`,
});
}
内容清理——处理 Unicode 边缘情况:
// U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) cause JSON parse failures
function sanitizeToolResult(content: string): string {
return content
.replace(/\u2028/g, '\n') // LINE SEPARATOR → newline
.replace(/\u2029/g, '\n'); // PARAGRAPH SEPARATOR → newline
}
const toolResult = {
type: 'tool_result',
tool_use_id: block.id,
content: sanitizeToolResult(result) // Sanitize before sending
};
视觉(图像理解)
关键规则:
- 格式: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 Opus 4.5——支持扩展思考(旗舰型号)
- ✅ 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标头 - 为关键操作准备回退策略
已知问题预防
此技能可预防已记录的 16 个问题:
问题 #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 或每日 token 限制
预防方法:实现指数退避,并遵循 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:计费时的 Token 计数不匹配
错误:费用意外偏高、超出上下文窗口 来源:Token 计数差异 原因:未将特殊 Token 和格式计入 预防:使用官方 Token 计数器,监控用量标头
问题 #7:系统提示词顺序问题
错误:系统提示词被忽略或覆盖 来源:API 行为 原因:系统提示词放在 messages 数组之后 预防:始终将系统提示词放在 messages 之前
问题 #8:超出上下文窗口(200k)
错误:invalid_request_error: messages: too many tokens
来源:模型限制
原因:长对话未进行精简
预防:精简消息历史,使用缓存
问题 #9:在错误的模型上启用扩展思考
错误:响应中没有思考块 来源:模型能力 原因:使用了已退役/弃用的模型(3.5/3.7 Sonnet) 预防:仅在 Claude Opus 4.5、Claude Sonnet 4.5 或 Claude Opus 4 上使用扩展思考
问题 #10:客户端代码中暴露 API 密钥
错误:CORS 错误、安全漏洞 来源:安全最佳实践 原因:从浏览器发起 API 调用 预防:仅在服务器端调用,使用环境变量
问题 #11:速率限制层级混淆
错误:限制低于预期 来源:账户层级系统 原因:不了解层级升级机制 预防:在 Console 中查看当前层级;层级会随用量自动提升
问题 #12:消息批处理缺少 Beta 标头
错误:invalid_request_error: unknown parameter: batches
来源:Beta API 要求
原因:缺少 anthropic-beta 标头
预防:加入 anthropic-beta: message-batches-2024-09-24 标头
问题 #13:使用 .withResponse() 时无法捕获流错误(已在 v0.71.2 中修复)
错误:使用 messages.stream().withResponse() 时出现未处理的 Promise 拒绝
来源:GitHub 问题 #856
原因:SDK 内部错误处理导致用户的 catch 代码块无法生效(v0.71.2 之前)
预防:升级到 v0.71.2+,或改用事件监听器
已在 v0.71.2+ 中修复:
try {
const stream = await anthropic.messages.stream({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello' }]
}).withResponse();
} catch (error) {
// Now properly catchable in v0.71.2+
console.error('Stream error:', error);
}
v0.71.2 之前的临时解决方法:
const stream = anthropic.messages.stream({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello' }]
});
stream.on('error', (error) => {
console.error('Stream error:', error);
});
问题 #14:MCP 工具连接导致 2 分钟超时
错误:约 121 秒后出现 Connection error / 499 Client disconnected
来源:GitHub 问题 #842
原因:MCP 服务连接管理与长时间运行的请求冲突,即使未主动使用 MCP 工具也会发生
预防:对于超过 2 分钟的请求,改用直接的 toolRunner,而非 MCP
症状:
- 不使用 MCP 时请求运行正常
- 注册 MCP 后恰好在约 121 秒时失败
- 控制面板显示:“Client disconnected (code 499)”
- 多位用户确认,流式和非流式请求均会出现此问题
临时解决方法:
// Don't use MCP for long requests
const message = await anthropic.beta.messages.toolRunner({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 4096,
messages: [{ role: 'user', content: 'Long task >2 min' }],
tools: [customTools] // Direct tool definitions, not MCP
});
注意:这是一个已知限制,目前没有官方修复方案。如果需要使用工具处理长时间运行的请求,请考虑调整架构。
问题 #15:结构化输出的幻觉风险
错误:JSON 格式有效,但内容不正确或存在幻觉 来源:结构化输出文档 原因:结构化输出保证格式符合要求,但不保证准确性 预防:务必验证语义是否正确,而不只是检查格式
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-5-20250929',
messages: [{ role: 'user', content: 'Extract contact: John Doe' }],
betas: ['structured-outputs-2025-11-13'],
output_format: {
type: 'json_schema',
json_schema: contactSchema
}
});
const contact = JSON.parse(message.content[0].text);
// ✅ Format is guaranteed valid
// ❌ Content may be hallucinated
// CRITICAL: Validate semantic correctness
if (!isValidEmail(contact.email)) {
throw new Error('Hallucinated email detected');
}
if (contact.age < 0 || contact.age > 120) {
throw new Error('Implausible age value');
}
问题 #16:工具结果中的 U+2028 行分隔符(来自社区)
错误:工具结果包含 U+2028 时,JSON 解析失败或出现静默错误 来源:GitHub 问题 #882 原因:U+2028 在 JSON 中有效,但不能出现在 JavaScript 字符串字面量中 预防:将工具结果传递给 SDK 前进行清理
function sanitizeToolResult(content: string): string {
return content
.replace(/\u2028/g, '\n') // LINE SEPARATOR → newline
.replace(/\u2029/g, '\n'); // PARAGRAPH SEPARATOR → newline
}
const toolResult = {
type: 'tool_result',
tool_use_id: block.id,
content: sanitizeToolResult(result)
};
官方文档
- Claude API:https://platform.claude.com/docs/en/api
- Messages API:https://platform.claude.com/docs/en/api/messages
- Structured Outputs:https://platform.claude.com/docs/en/build-with-claude/structured-outputs
- Prompt Caching: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 库 ID:/anthropics/anthropic-sdk-typescript
软件包版本
最新版本:@anthropic-ai/[email protected]
{
"dependencies": {
"@anthropic-ai/sdk": "^0.71.2"
},
"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)
预防的错误:16 个有记录的问题及其精确解决方案 核心价值:结构化输出(v0.69.0+)、模型弃用(2025 年 10 月)、提示词缓存边缘情况、流式传输错误模式、速率限制重试逻辑、MCP 超时解决方案、幻觉验证
上次验证时间:2026-01-20 | Skill 版本:2.2.0 | 变更:根据社区调研新增 4 个问题:流式传输错误处理(已在 v0.71.2 中修复)、MCP 超时解决方案、结构化输出幻觉验证、U+2028 清理;扩展结构化输出部分,补充性能特征和准确性注意事项;新增 AWS Bedrock 缓存限制