#### TypeScript SDK

# Files and batch

Examples use the `client` created in the [quickstart](/developers/sdk/typescript#quickstart).

## Files

Upload a document, image, or video once with `client.files.upload()` and reference it by ID wherever the API accepts a `file_id` (such as an `input_file` part or an image or video input). See [Files Overview](/developers/files) for file limits and supported types.

```typescript
import { openAsBlob } from 'node:fs';

const file = await client.files.upload({
  file: await openAsBlob('./report.pdf'),
  filename: 'report.pdf',
});

const response = await client.responses.create({
  model: 'grok-4.7',
  input: [
    {
      role: 'user',
      content: [
        { type: 'input_text', text: 'Summarize the key findings in this report.' },
        { type: 'input_file', file_id: file.id },
      ],
    },
  ],
});

console.log(response.toText());
```

A `File` supplies its own filename; a plain `Blob` (such as one from `openAsBlob()`) requires `filename`. Files persist until deleted, or you can set `expires_after` between 3,600 and 2,592,000 seconds (1 hour to 30 days) for automatic expiration.

List, download, share via [public URLs](/developers/files/public-urls), and delete stored files:

```typescript
import { writeFile } from 'node:fs/promises';

for await (const stored of client.files.list()) {
  console.log(stored.id, stored.filename, stored.bytes);
}

const content = await client.files.content(file.id);
await writeFile('report-copy.pdf', await content.bytes());

const { public_url } = await client.files.createPublicUrl(file.id, {
  expires_after: 86_400,
});
console.log(public_url);

await client.files.revokePublicUrl(file.id);
await client.files.delete(file.id);
```

`list()` returns the newest files first and automatically fetches subsequent pages during `for await` iteration. `content()` returns a `BinaryResponse`, so you can stream `content.body` or read it with `bytes()`, `text()`, `blob()`, or `arrayBuffer()`.

Anyone with a public URL can download the file without an API key. Only images, videos, and PDFs up to 50 MiB can have public URLs. Each file has at most one public URL: calling `createPublicUrl()` again returns the existing URL and updates its expiration if you pass a new `expires_after`. Without `expires_after`, the URL lasts until the file is deleted or revoked. After revoking, CDN-cached copies may remain briefly reachable.

## Batch API

Process large volumes of requests asynchronously at reduced cost using `client.batches`. Most batch requests complete within 24 hours. See the [Batch API guide](/developers/advanced-api-usage/batch-api) for pricing and quotas.

Create a batch and add requests to it:

```typescript
const batch = await client.batches.create({ name: 'feedback_sentiment' });

const feedback = [
  { id: 'feedback_001', text: 'The product exceeded my expectations!' },
  { id: 'feedback_002', text: 'Shipping took way too long.' },
];

await client.batches.requests.add(batch.batch_id, {
  batch_requests: feedback.map(item => ({
    batch_request_id: item.id,
    batch_request: {
      responses: {
        model: 'grok-4.7',
        input: [
          {
            role: 'system',
            content: 'Classify the sentiment as positive, negative, or neutral.',
          },
          { role: 'user', content: item.text },
        ],
      },
    },
  })),
});
```

Each `batch_request` wraps one request: `responses` accepts the same `CreateParams` as `client.responses.create()` (including the `store: false` default) and returns a `chat_get_completion` result, while `image_generation`, `image_edit`, `video_generation`, and `video_extension` match their REST endpoint bodies. Results arrive in any order, so assign each request a unique `batch_request_id` within the batch. Check the [Models page](/developers/models) to confirm Batch API support for a given model.

Wait for the batch to complete and iterate over the results:

```typescript
await client.batches.wait(batch.batch_id);

for await (const { batch_request_id, batch_result } of client.batches.results(batch.batch_id)) {
  if ('error' in batch_result) {
    console.error(batch_request_id, batch_result.error);
  } else {
    console.log(batch_request_id, batch_result.response);
  }
}
```

`wait()` polls every 5 seconds and rejects with `TimeoutError` after 24 hours (override with `interval`, `timeout`, or `signal`; durations are capped at 24 hours). For batches created from `input_file_id`, `wait()` keeps polling while the file loads until requests appear or the batch is cancelled or expires. Results become readable as individual requests finish. You can also inspect individual requests with `client.batches.requests.list()`, list team batches with `client.batches.list()`, or stop pending work with `client.batches.cancel()` (finished results remain available).
