[ PROMPT_NODE_23886 ]
batches
[ SKILL_DOCUMENTATION ]
# 消息批量 API — TypeScript
批量 API (`POST /v1/messages/batches`) 以标准价格的 50% 异步处理消息 API 请求。
## 关键点
- 每个批次最多 100,000 个请求或 256 MB
- 大多数批次在 1 小时内完成;最长 24 小时
- 结果在创建后 29 天内可用
- 所有 Token 使用量享 50% 折扣
- 支持所有消息 API 功能(视觉、工具、缓存等)
---
## 创建批次
typescript
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const messageBatch = await client.messages.batches.create({
requests: [
{
custom_id: "request-1",
params: {
model: "claude-opus-4-7",
max_tokens: 16000,
messages: [
{ role: "user", content: "总结气候变化的影响" },
],
},
},
{
custom_id: "request-2",
params: {
model: "claude-opus-4-7",
max_tokens: 16000,
messages: [
{ role: "user", content: "解释量子计算基础" },
],
},
},
],
});
console.log(`批次 ID: ${messageBatch.id}`);
console.log(`状态: ${messageBatch.processing_status}`);
---
## 轮询完成状态
typescript
let batch;
while (true) {
batch = await client.messages.batches.retrieve(messageBatch.id);
if (batch.processing_status === "ended") break;
console.log(
`状态: ${batch.processing_status}, 处理中: ${batch.request_counts.processing}`,
);
await new Promise((resolve) => setTimeout(resolve, 60_000));
}
console.log("批次完成!");
console.log(`成功: ${batch.request_counts.succeeded}`);
console.log(`错误: ${batch.request_counts.errored}`);
---
## 获取结果
typescript
for await (const result of await client.messages.batches.results(
messageBatch.id,
)) {
switch (result.result.type) {
case "succeeded":
console.log(
`[${result.custom_id}] ${result.result.message.content[0].text.slice(0, 100)}`,
);
break;
case "errored":
if (result.result.error.type === "invalid_request") {
console.log(`[${result.custom_id}] 验证错误 - 请修复并重试`);
} else {
console.log(`[${result.custom_id}] 服务器错误 - 可安全重试`);
}
break;
case "expired":
console.log(`[${result.custom_id}] 已过期 - 请重新提交`);
break;
}
}
---
## 取消批次
typescript
const cancelled = await client.messages.batches.cance