> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zerogen.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SDKs

> Call the ZeroGen API from TypeScript or JavaScript with the official library.

ZeroGen publishes an official library for TypeScript and JavaScript,
[`@zerogen/sdk`](https://www.npmjs.com/package/@zerogen/sdk). Its types come
from the API's [OpenAPI document](https://api.zerogen.com/v1/openapi.json),
and it follows the conventions in these docs for you:

* It sends an `Idempotency-Key` with every `POST`, and reuses it when it
  retries.
* It retries connection failures and errors whose `retryable` is `true`, and
  waits for `Retry-After` on a `429`.
* It waits for a generation to end with `Prefer: wait`.
* It pages through lists, and uploads a file in one call.

The library runs on servers: Node.js 20.3 or later, Deno, Bun, and edge
runtimes such as Cloudflare Workers. It has no dependencies. Its source is
[on GitHub](https://github.com/zerogeneration/zerogen-typescript).

In other languages, call the REST API directly. The
[API reference](https://docs.zerogen.com/api-reference/overview.md) and the OpenAPI document describe
every endpoint.

## Install

```bash theme={null}
npm install @zerogen/sdk
```

## Create a generation

Set your API key as `ZEROGEN_API_KEY`, then create a generation and wait for
it to end:

```ts theme={null}
import ZeroGen from "@zerogen/sdk";

const zerogen = new ZeroGen(); // Reads ZEROGEN_API_KEY.

const generation = await zerogen.generations.createAndWait({
  model: "openai/gpt-image-2/generate",
  prompt: "A lighthouse at dawn, in watercolor",
});

console.log(generation.status, generation.outputs);
```

`createAndWait` creates the generation with `Prefer: wait=60`, then reads it
with the same wait until it ends. It resolves for every final status,
including `failed`, so check `status` and each output's `status`. To return
without waiting, call `generations.create`, then `generations.get` or
`generations.waitFor` with the generation's ID. To stop waiting, pass an
`AbortSignal` as `signal`; the generation keeps running.

Each model takes its own inputs and parameters. Read a model's request schema
with `zerogen.models.get("openai/gpt-image-2/generate")`. For details, see
[Models](https://docs.zerogen.com/models.md).

## Upload an input

`uploads.upload` runs the three requests in
[Upload a file](https://docs.zerogen.com/uploads.md#upload-a-file) and resolves with the ready asset's
ID:

```ts theme={null}
import { openAsBlob } from "node:fs";

const upload = await zerogen.uploads.upload(await openAsBlob("storyboard.png"), {
  filename: "storyboard.png",
});

const edit = await zerogen.generations.createAndWait({
  model: "openai/gpt-image-2/edit",
  prompt: "Turn the sky into a sunset",
  inputs: [{ role: "source", asset: upload.assetId }],
});
```

It takes a `Blob`, `File`, `ArrayBuffer`, or `Uint8Array`, and reads the media
type from the file or from the filename's extension. For files up to 64 MiB,
it sends the file's SHA-256 digest, so a file the project already has is
reused instead of uploaded again.

## List

Iterate a list with `for await` to read every item on every page:

```ts theme={null}
for await (const model of zerogen.models.list({ capability: "video" })) {
  console.log(model.id);
}
```

Awaiting a list instead returns one page, with `data` and `nextCursor`.

## Handle errors

A request that ZeroGen refuses throws a `ZeroGenError`, which carries the
[error envelope](https://docs.zerogen.com/errors.md): `status`, `code`, `param`, `retryable`, `details`,
and the response's `requestId`. Branch on `code`:

```ts theme={null}
import ZeroGen, { ZeroGenError } from "@zerogen/sdk";

try {
  await zerogen.generations.create({
    model: "openai/gpt-image-2/generate",
    prompt: "A lighthouse at dawn, in watercolor",
  });
} catch (error) {
  if (error instanceof ZeroGenError && error.code === "insufficient_balance") {
    // Ask an admin to add funds.
  }
  throw error;
}
```

A request that gets no response, because the connection failed or timed out,
throws a `ZeroGenConnectionError`.

## Retries and idempotency

The library retries a request twice by default. It retries only connection
failures and errors whose `retryable` is `true`, and it doesn't wait for a
`Retry-After` longer than one minute. Each `POST` call gets a new
`Idempotency-Key`, which that call's retries reuse.

To retry safely across calls or processes, such as from a job queue, pass your
own key:

```ts theme={null}
await zerogen.generations.create(job.request, { idempotencyKey: job.id });
```

For details, see [Idempotency](https://docs.zerogen.com/idempotency.md).

## Configure the client

| Option | Default | Description |
| - | - | - |
| `apiKey` | `ZEROGEN_API_KEY` | The API key. |
| `baseURL` | `https://api.zerogen.com/v1` | The API's base URL. |
| `maxRetries` | `2` | Retries for each request. |
| `timeout` | `120000` | Milliseconds before an attempt is abandoned. A request that waits for a generation gets its wait added. |
| `fetch` | The global `fetch` | A `fetch` implementation to use instead. |
| `defaultHeaders` | None | Headers to send with every request. |

Every method also takes request options as its last argument: `signal`,
`timeout`, `maxRetries`, `idempotencyKey` for a `POST`, and `headers`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.