Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Build LLM-powered apps with the Anthropic Claude API or SDK across Python, TypeScript, Java, Go, Ruby, C#, and PHP.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
typescript/claude-api/batches.md
1# Message Batches API — TypeScript23The Batches API (`POST /v1/messages/batches`) processes Messages API requests asynchronously at 50% of standard prices.45## Key Facts67- Up to 100,000 requests or 256 MB per batch8- Most batches complete within 1 hour; maximum 24 hours9- Results available for 29 days after creation10- 50% cost reduction on all token usage11- All Messages API features supported (vision, tools, caching, etc.)1213---1415## Create a Batch1617```typescript18import Anthropic from "@anthropic-ai/sdk";1920const client = new Anthropic();2122const messageBatch = await client.messages.batches.create({23requests: [24{25custom_id: "request-1",26params: {27model: "claude-opus-4-7",28max_tokens: 16000,29messages: [30{ role: "user", content: "Summarize climate change impacts" },31],32},33},34{35custom_id: "request-2",36params: {37model: "claude-opus-4-7",38max_tokens: 16000,39messages: [40{ role: "user", content: "Explain quantum computing basics" },41],42},43},44],45});4647console.log(`Batch ID: ${messageBatch.id}`);48console.log(`Status: ${messageBatch.processing_status}`);49```5051---5253## Poll for Completion5455```typescript56let batch;57while (true) {58batch = await client.messages.batches.retrieve(messageBatch.id);59if (batch.processing_status === "ended") break;60console.log(61`Status: ${batch.processing_status}, processing: ${batch.request_counts.processing}`,62);63await new Promise((resolve) => setTimeout(resolve, 60_000));64}6566console.log("Batch complete!");67console.log(`Succeeded: ${batch.request_counts.succeeded}`);68console.log(`Errored: ${batch.request_counts.errored}`);69```7071---7273## Retrieve Results7475```typescript76for await (const result of await client.messages.batches.results(77messageBatch.id,78)) {79switch (result.result.type) {80case "succeeded":81console.log(82`[${result.custom_id}] ${result.result.message.content[0].text.slice(0, 100)}`,83);84break;85case "errored":86if (result.result.error.type === "invalid_request") {87console.log(`[${result.custom_id}] Validation error - fix and retry`);88} else {89console.log(`[${result.custom_id}] Server error - safe to retry`);90}91break;92case "expired":93console.log(`[${result.custom_id}] Expired - resubmit`);94break;95}96}97```9899---100101## Cancel a Batch102103```typescript104const cancelled = await client.messages.batches.cancel(messageBatch.id);105console.log(`Status: ${cancelled.processing_status}`); // "canceling"106```107