(
client: Anthropic,
requests: BatchRequest[],
options: BatchOptions = {},
)
| 57 | * Returns results keyed by customId for easy lookup. |
| 58 | */ |
| 59 | export async function submitBatch( |
| 60 | client: Anthropic, |
| 61 | requests: BatchRequest[], |
| 62 | options: BatchOptions = {}, |
| 63 | ): Promise<Map<string, BatchItemResult>> { |
| 64 | const { |
| 65 | pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, |
| 66 | timeoutMs = DEFAULT_TIMEOUT_MS, |
| 67 | operationName = 'batch', |
| 68 | } = options; |
| 69 | |
| 70 | if (requests.length === 0) { |
| 71 | return new Map(); |
| 72 | } |
| 73 | |
| 74 | if (requests.length > MAX_BATCH_SIZE) { |
| 75 | throw new Error( |
| 76 | `Batch size ${requests.length} exceeds API limit of ${MAX_BATCH_SIZE} for ${operationName}`, |
| 77 | ); |
| 78 | } |
| 79 | |
| 80 | // Submit the batch |
| 81 | let batch; |
| 82 | try { |
| 83 | batch = await client.messages.batches.create({ |
| 84 | requests: requests.map((r) => ({ |
| 85 | custom_id: r.customId, |
| 86 | params: r.params, |
| 87 | })), |
| 88 | }); |
| 89 | } catch (err) { |
| 90 | throw new Error( |
| 91 | `Batch submission failed for ${operationName}: ${err instanceof Error ? err.message : err}`, |
| 92 | ); |
| 93 | } |
| 94 | |
| 95 | logger.info( |
| 96 | { batchId: batch.id, requestCount: requests.length, operation: operationName }, |
| 97 | 'Batch submitted', |
| 98 | ); |
| 99 | |
| 100 | // Poll until complete or timeout |
| 101 | const completedBatch = await pollForCompletion(client, batch.id, { |
| 102 | pollIntervalMs, |
| 103 | timeoutMs, |
| 104 | operationName, |
| 105 | }); |
| 106 | |
| 107 | // Fetch and parse results |
| 108 | return collectResults(client, completedBatch, operationName); |
| 109 | } |
| 110 | |
| 111 | /** |
| 112 | * Poll a batch until processing_status is 'ended' or timeout. |
no test coverage detected