---
title: AI Generation
description: Generate text and images from your backend using Turn Zero Cloud’s AI route. See what calls charge to your account and how to handle refusals.
slug: /backend-packages/ai-generation
order: 7
visibility: public
redirects_from: [/backend-packages/ai-allowance]
---

# AI Generation

AI Generation lets your backend generate text and images with the platform’s provider key. Each call uses your account balance to pay the provider’s published price plus the markup on the [pricing page](https://dev.turnzero.ai/pricing). Your application receives no provider key and has no monthly AI allowance.

To start, take the package from the library ([Use the feature package library](/cloud/guides/use-the-library/)), write the transport in [The client](#the-client), and call `generateText(transport, { prompt })` from a route. [Call an AI model](/cloud/guides/call-an-ai-model/) gives the steps.

Read one application’s AI spend this month with `tzcloud_read_usage`, under `ai_allowance_usd_micros`. Read the account’s balance, pause state and monthly usage lines with `read_balance`. [Size and usage](/cloud/guides/plan-and-usage/) explains these reads. Read rates on the [pricing page](https://dev.turnzero.ai/pricing), or call `read_rate_card`.

At a glance:

- **Package:** the `ai_generation` library entry ([Use the feature package library](/cloud/guides/use-the-library/)).
- **[Settings your server reads](/cloud/concepts/the-settings-a-deployed-copy-receives/):** `TURNZERO_CLOUD_GATEWAY_URL`, or else `TURNZERO_CLOUD_API`, and `TURNZERO_CLOUD_APP_TOKEN`.
- **Import:** `import { generateText } from '@turnzero/ai_generation';`
- **The transport:** a function that sends each path to that origin with `authorization: Bearer <TURNZERO_CLOUD_APP_TOKEN>`. [The client](#the-client) has the smallest working call.
- **The call:** `generateText(transport, { prompt })` returns the answer’s `text`, usage and an `allowance` object whose members are null for a customer application.
- **Account pause:** a call can throw `AllowanceRefusal` with `refusal: 'account_paused'`. Follow [The boundary and the fallback](#the-boundary-and-the-fallback).

## Use it when

Use AI Generation when your backend needs to generate text or images and you want Turn Zero Cloud to hold the provider key. You can also use the platform’s key for some calls and your own key for others.

Choose the route for each call. This package’s route draws the account’s balance. A call through your own [declared upstream](/cloud/concepts/glossary/#declared-upstream), using the [Egress](/cloud/backend-packages/egress/) client, uses your stored key. [Call an external API with an API key](/cloud/guides/call-an-external-api-with-an-api-key/) sets up that route.

Your AI provider bills you for model use. Turn Zero charges data transfer for the request body bytes its gateway sends to your provider. Turn Zero adds no markup to your provider's charge.

The platform route supports text and image generation on any Gemini model its key can reach. Use `generateText` for text and `generateImage` for images. [Generate an image with AI](/cloud/guides/generate-an-image-with-ai/) shows one.

A request for audio or video output, paid grounding, a named `cachedContent` cache, or a separately priced provider tool is refused with `allowance_feature_refused`. Use your own key through Egress for those features or another provider.

## What it provides

- The function `generateText(transport, request, options)`, which [The client](#the-client) describes.
- The function `generateImage(transport, request, options)` returns an image's bytes and type. If you omit the model, it uses `DEFAULT_IMAGE_MODEL`. Its `usage` includes `imageTokens`, the image's token count. It sends one request and does not retry.
- An `allowance` object on each result. For a customer application, its `used`, `quota` and `resetsAt` members are null. `readStanding(headers)` reads those members from a response’s headers.
- A typed refusal, `AllowanceRefusal`, thrown for every response the gateway itself wrote, rather than passed on from the provider.
- A typed upstream error, `AllowanceUpstreamError`, thrown for a provider response with a non-success status. Its `quota` member is true where the provider rejected the call because it lacked capacity, the case your application may fall back on.
- A streamed form: pass `onText` in the options, and each text fragment arrives in order as the provider produces it. The returned `text` contains the whole answer.
- A [test double](/cloud/concepts/glossary/#test-double), `createAiGenerationDouble` at `@turnzero/ai_generation/testing`, which answers in place of the platform’s AI route. [Test with the double](#test-with-the-double) shows it in use.

Without `model`, `generateText` sends `DEFAULT_MODEL`, the reserved name `default`. The platform resolves it to its selected text model on each call, so a later selection takes effect without redeploying your application. The result's `model` remains `default`, the name the client sent.

On `default` calls, the client sends no thinking member, even if you set `thinkingBudget`; the platform selects the thinking level. To send a budget, name a Gemini model. `generateImage` keeps `DEFAULT_IMAGE_MODEL` (`gemini-3.1-flash-lite-image`). The route accepts `default` and any `gemini-` model the platform's key can access. It refuses other names with 403 `allowance_path_refused`.

You pay the model’s current rates plus the markup on the pricing page. If the platform has no rates for that model, it uses the current rates for its highest-priced model instead. Input tokens use the input rate. Text output and thinking tokens use the output rate; image output uses the image-output rate. Image tokens are counted once. Cached input uses the cached-input rate, or the input rate where the model has none.

The answer’s `usage` gives the provider’s `inputTokens` and `outputTokens`. These token counts do not report the account’s balance. Use `tzcloud_read_usage` to see what an application spent on AI this month. Use `read_balance` to see the account balance and monthly line items.

For customer applications, no allowance headers are returned. The package preserves the object shape with null members:

| Allowance member | Customer application |
| --- | --- |
| `allowance.used` | `null` |
| `allowance.quota` | `null` |
| `allowance.resetsAt` | `null` |

Unlimited applications receive the amount used before the call and the allowance limit, both in micro-dollars. The response also gives the start of the next UTC month. To get this response in a test, set `pricing: 'plans'`. These fields do not describe a customer application’s balance.

## Availability

Version 0.13.0 is the package's current version, and this page describes it. Until the library's next publish, `read_library` can return an earlier version, the one you can take. This page can describe a change that version lacks. The entry includes the compiled module, the `testing` subpath, its [product statement and detailed contract](/cloud/concepts/glossary/#product-statement-and-detailed-contract), and its integration guide.

The gateway you call must be able to read its model selection for `default`. Otherwise the call is refused 503 `allowance_default_unavailable` before reaching the provider. Name a Gemini model or wait for the platform's selection.

The platform’s [egress gateway](/cloud/concepts/glossary/#egress-gateway) applies its provider key and meters calls. A customer application’s calls draw the account’s balance and carry no allowance headers. A paused account’s call is refused with `account_paused`.

## Related feature packages

[Egress](/cloud/backend-packages/egress/) sends calls on your own stored keys through the same gateway. [Secrets](/cloud/backend-packages/secrets/) stores those keys. [Logging](/cloud/backend-packages/logging/) records what your backend does with an answer.

## The client

The package is published in the library as the npm package `@turnzero/ai_generation`, not on the npm registry; [Use the feature package library](/cloud/guides/use-the-library/#5-install-a-package-s-compiled-code) installs it with one line. The package builds no client object and keeps no state. Each call is one `generateText(transport, request, options)` or `generateImage(transport, request, options)`, over the transport function your application supplies. [Call an AI model](/cloud/guides/call-an-ai-model/) shows a complete call from a backend route.

Your `transport` function takes a gateway path and a request. It adds the platform's origin and your application's credential as the bearer, and returns the response. The [platform credential](/cloud/concepts/glossary/#platform-credential) that a deploy gives your copy is bound to its environment and takes no environment header. A call under a [minted token](/cloud/concepts/glossary/#minted-token) bound to the application gives the environment in the header `x-turnzero-cloud-environment`. The client adds `content-type` and no other header.

A deployed copy receives the origin as `TURNZERO_CLOUD_GATEWAY_URL` where the platform gives a separate one, and otherwise as `TURNZERO_CLOUD_API`. It receives the credential as `TURNZERO_CLOUD_APP_TOKEN` ([A deployed app's settings](/cloud/concepts/the-settings-a-deployed-copy-receives/)). So a transport reads the first of the two origins that is set, as [Call an AI model](/cloud/guides/call-an-ai-model/) shows.

This call, from a deployed copy's backend, sends one prompt and prints the answer, its transport reading the settings above. The guide shows the same call inside a server route. A test runs this sample over the package's test double and checks the answer and the request it sends.

```js
import { generateText } from '@turnzero/ai_generation';

// The platform's origin and this copy's credential, from the settings it receives.
const origin = process.env.TURNZERO_CLOUD_GATEWAY_URL ?? process.env.TURNZERO_CLOUD_API;
const transport = (path, init = {}) =>
  fetch(origin + path, { ...init, headers: { ...init.headers, authorization: `Bearer ${process.env.TURNZERO_CLOUD_APP_TOKEN}` } });

const answer = await generateText(transport, { prompt: 'Summarize the notes in one line.' });
console.log(answer.text);
```

### Direct HTTP requests

To call the route without `generateText`, send a `POST` to `/egress/v0/ai-allowance/v1beta/models/default:generateContent`. Use `TURNZERO_CLOUD_GATEWAY_URL` as the base address, or `TURNZERO_CLOUD_API` when the gateway setting is absent. Set `Content-Type: application/json` and `Authorization: Bearer <TURNZERO_CLOUD_APP_TOKEN>`, using the environment's credential only on that platform address.

The short request below uses `default` and sets no thinking budget, so the platform selects the thinking level. To name a Gemini model, replace `default` in the route with its name. A direct named-model request without a thinking budget leaves that choice to the provider; `generateText` instead sends zero where `thinkingBudget` is absent. Thinking tokens are charged at the output rate.

Starting on the text model's retirement day in UTC, the platform uses its default model for requests that name the retired model. You pay the price of the model that runs. The platform drops your thinking budget and level and uses its default thinking level if one is set.

Your application's log records `ai model substituted` at `warn`, with `asked_model`, `served_model` and `retired_on`. This line appears at most once per application and requested model each UTC day on each gateway replica.

If the default is unset, unread or names the same model, the request keeps its model name and thinking settings, and the provider answers it.

```json
{
  "contents": [
    { "role": "user", "parts": [{ "text": "Say hello in one short sentence." }] }
  ]
}
```

A successful answer can contain this candidate. This is an illustrative response, not a promised output:

```json
{
  "candidates": [
    {
      "content": { "role": "model", "parts": [{ "text": "Hello!" }] },
      "finishReason": "STOP",
      "index": 0
    }
  ]
}
```

Read generated text from `candidates[0].content.parts` entries with a `text` member; a response can include other fields, and may contain no text candidate. Direct calls use the provider's `contents` and `generationConfig` fields, rather than the package's `prompt` field. The platform adds the provider's key; do not supply one yourself.

On a non-streamed direct call, a gateway refusal has a JSON body with `contract_version` (a number), `error` (the refusal name), and `detail` (a string). Read `error` to distinguish `allowance_unavailable` from `account_paused`. [Failures](#failures) describes status codes, provider errors, and any extra fields. For one of Turn Zero's own unlimited applications, an `allowance_exhausted` body names its reset time `resets_at`; the package calls it `resetsAt`. [The boundary and the fallback](#the-boundary-and-the-fallback) explains the fallback policy, using the package's names. Its `AllowanceUpstreamError` is a package wrapper, not a field in a direct HTTP response.

A customer application’s answer carries none of `x-ai-allowance-used`, `x-ai-allowance-quota` or `x-ai-allowance-resets-at`. For an unlimited application, provider answers and `allowance_exhausted` carry these headers. They supply the three members in [What it provides](#what-it-provides). Other gateway refusals carry none.

Substitute a Gemini model for `default` as needed, following the [model pricing rule](#what-it-provides). For a streamed answer, use `:streamGenerateContent?alt=sse` instead of `:generateContent`. `ALLOWANCE_PATH_PREFIX` contains the start of the path. [Generate an image with AI](/cloud/guides/generate-an-image-with-ai/#3-send-the-request-from-a-route) shows an image call.

This request uses the same `default` route, gives a system instruction and one user prompt, and limits the answer to 128 tokens. It matches `generateText` with those fields and no model; the platform selects the thinking level:

```json
{
  "systemInstruction": {
    "parts": [
      {
        "text": "Answer in one sentence."
      }
    ]
  },
  "contents": [
    {
      "parts": [
        {
          "text": "Summarize the notes in one line."
        }
      ]
    }
  ],
  "generationConfig": {
    "maxOutputTokens": 128
  }
}
```

### Text request and result

The request takes `prompt` or `messages`, never both, and the other fields are optional.

| Request field | What it does |
| --- | --- |
| `prompt` | One user turn's text, in place of `messages`. |
| `messages` | The conversation's turns in order, each `{ role, content }`. `role` is `user` or `assistant`, and the last turn is the user's. |
| `system` | The system instruction, which the model reads separately from the turns. |
| `responseSchema` | A JSON Schema the answer must satisfy. The answer's `text` is then JSON: parse it, and check what matters to your application. |
| `maxOutputTokens` | The most output tokens the answer may hold. |
| `thinkingBudget` | The reasoning budget for a named-model call, zero when absent. A `default` call sends none even when given: the platform selects its thinking level. Thinking tokens count as output. |
| `model` | The model to call. Without it, `DEFAULT_MODEL` sends `default`, resolved to the platform’s selected text model on each call. |

Every turn you send counts as input on that call, so a long conversation draws more tokens on each call. Sending only the recent turns limits that draw. Do not add an answer with empty text to the conversation, because a turn's content must not be empty.

The options are `onText`, a function that receives each piece of text as it arrives, and `signal`, an `AbortSignal` that ends a call you no longer want. `generateText` passes `options.signal` to your transport as `init.signal`. Pass it to `fetch`, as the sample above does, or handle it in your transport to abort the HTTP request itself.

Cancellation rejects the call. When the package detects cancellation between streamed reads, it rejects with the signal's reason. Cancellation handled by your transport follows that transport's behavior. If your transport ignores the signal, the package can detect cancellation only between streamed reads.

The call returns `text`, `model`, `usage` with `inputTokens` and `outputTokens`, `finish` (the provider's reason the answer ended, or `null`), and `allowance`. In this text result, `model` is the name the client sent. If you left it out, the result says `default`.

### Image request and result

`generateImage(transport, request, options)` takes a non-empty `request.prompt` and an optional `request.model`, which defaults to `DEFAULT_IMAGE_MODEL`. Its only option is `signal`, an `AbortSignal`. Image calls have no streamed form.

It returns `{ image, model, usage, finish, blockReason, allowance }`. The first non-thinking image part of the first candidate becomes `image`, as `{ bytes, mimeType }`; where that candidate has none, `image` is `null`. `bytes` is a `Uint8Array`, and a missing type becomes `application/octet-stream`.

`usage` holds `inputTokens`, `outputTokens`, and `imageTokens`. The image tokens are part of the output count, not extra output tokens. `finish` and `blockReason` hold the provider's reasons, or `null` where it gave none.

A malformed prompt throws `TypeError` before anything is sent. Platform refusals throw `AllowanceRefusal`, and provider failures throw `AllowanceUpstreamError`. The function sends one request and retries nothing. [Generate an image with AI](/cloud/guides/generate-an-image-with-ai/) shows a complete route.

The function `readStanding(headers)` reads the allowance from the headers of any response of the route, whatever its status. It returns `{ used, quota, resetsAt }`: `used` and `quota` as numbers, and `resetsAt` as the header's time. Each is `null` where its header is absent, and `used` or `quota` also where its header is not a number.

### Failures

On a non-streamed direct HTTP call, a gateway refusal is a JSON body with `contract_version`, `error`, and `detail`. Read the refusal name from `error`; `AllowanceRefusal.refusal` is the package's name for that field. The provider's own error body is passed through unchanged. The provider's response has the `x-egress-upstream` header; a gateway refusal does not. For a provider error, treat HTTP 429 or `RESOURCE_EXHAUSTED` in the body as a capacity failure. The package reports this as `AllowanceUpstreamError` with `quota: true`.

A paused account’s call is refused with HTTP 429 and `error: "account_paused"`. Its `Retry-After` header gives the wait until the next UTC month. The pause ends when the account has Free Allowance available again or credit it can use. It carries no allowance headers. Do not repeatedly retry during that wait.

For an unlimited application, `allowance_exhausted` carries `used`, `quota` and `resets_at`. The amounts are micro-dollars and the time is the next UTC month’s start. Other gateway refusals need not carry those members.

The package reports these failures:

- An `AllowanceRefusal`, for a response the gateway wrote itself, with `refusal`, `status`, `detail`, `resetsAt`, and `allowance`.
- An `AllowanceUpstreamError`, for the provider's non-success response, with `status`, `body`, `quota`, and `allowance`.
- A `TypeError`, before anything is sent, for a malformed request: both `prompt` and `messages`, neither, or a malformed turn.

The AI route’s refusals, in `refusal`:

| Refusal | Status | Meaning |
| --- | --- | --- |
| `account_paused` | 429 | The account is paused until it has Free Allowance available again or credit it can use. `Retry-After` gives the wait until the next UTC month. |
| `allowance_exhausted` | 429 | An unlimited application has reached its allowance quantity. |
| `allowance_unavailable` | 503 | The platform has no allowance key available, or no model price in effect. |
| `allowance_default_unavailable` | 503 | A `default` call has no readable platform model selection. Name a Gemini model or wait for that selection. |
| `allowance_application_required` | 403 | The call used an account-wide credential, which cannot call the platform’s AI route. |
| `allowance_busy` | 429 | The application already has the most allowance calls in progress that the platform allows. |
| `allowance_path_refused` | 403 | The request named neither `default` nor a `gemini-` model, or a path other than the model's generate methods. |
| `allowance_feature_refused` | 400 | The request asked for a feature the allowance does not cover, such as audio or video output, or its body was not JSON. |
| `plan_quantity_unset` | 409 | An unlimited application has no `gemini-allowance` quantity set. |

Any other refusal name is one of the gateway's own, passed through with its status, and the [refusals page](/cloud/reference/refusals/) lists it.

Where your backend closes its connection before a call returns, the platform ends the call at the provider, streamed or not. A call already sent to the provider can end early in any of these ways, and each says what your backend receives:

- Your backend gives the call up: it receives no answer. On a streamed call, the text that already arrived stays delivered.
- The call runs past the platform's time limit: a call that does not stream fails with 504 `upstream_timeout`. A streamed call keeps the text already sent, then ends with a final `egress_error` event naming `upstream_timeout`. Either way, `generateText` throws `AllowanceRefusal` with that name.
- The provider's answer passes the platform's size limit: a call that does not stream fails with 502 `response_too_large`. A streamed call keeps the text sent within the limit, then ends with a final `egress_error` event naming `response_too_large`. Either way, `generateText` throws `AllowanceRefusal` with that name.

Such a call draws nothing if the provider had not begun its answer when the platform ended it, except for a Gemini 4 model. Other models draw nothing because the provider does not charge for that call. The provider can charge Gemini 4 calls that time out, so they draw the request’s input estimate and no output tokens. This rule follows the model that served the call, including when you chose `default` or a retired model name.

Where the provider had begun an answer with HTTP 200 to 299, the call uses its token counts if they reached the platform. This includes counts in streamed text or a whole answer over the size limit.

If no count reached the platform after that successful status, the call draws an estimate of input tokens: one for every four bytes of the request, rounded up. It draws no output tokens.

A call the provider had already answered with an error status draws nothing, as it would if it had finished. A call stopped before the platform sent it, such as a request over the size limit, draws nothing. These tokens are charged like those of any other call. `tzcloud_read_usage` records the application’s AI spend this month.

## The boundary and the fallback

An account pause stops the whole application. The router returns 429 `account_paused` for every request on the application's hostnames, including requests for the web client's shell files and sign-in routes. The platform also refuses scheduled runs and storage calls. It puts the application's running containers to sleep in the background. [When the account pauses](https://dev.turnzero.ai/turnzero/guides/balance-and-usage/#when-the-account-pauses) explains the account-wide stop.

Hosted application code can receive `account_paused` from the gateway only in work already running when the pause began. The router refuses new requests during the pause. The gateway also refuses every call from application code that starts locally during the pause.

Handle each failure by the `refusal` field. Read `detail` to understand the cause; do not parse it to identify the refusal:

- On `account_paused`, end the work without another outbound call or retry. Calls on your own declared upstream and key are refused too. The pause ends when the account has Free Allowance available again or credit it can use. `Retry-After` gives the wait until the next UTC month.
- On `allowance_unavailable`, read its `detail`. Use the fallback you chose while the platform restores the allowance route: answer without AI, or call your own declared upstream and key. A monthly reset does not fix this refusal.
- On `allowance_default_unavailable`, name a Gemini model or use your chosen fallback while the platform selects its default. A monthly reset does not select one.
- On an `AllowanceUpstreamError` whose `quota` is true, the provider is short of capacity for the platform's key. The platform has already sent the call again up to four times, over up to 15 seconds, before it responded to you, so a quick retry rarely helps. Retry it later at a slower cadence, waiting tens of seconds between attempts, or apply the same fallback.
- Treat every other upstream error as the provider's own. It reaches you with its body unchanged.

An unlimited application can receive `allowance_exhausted`. The last call the platform accepts may cost more than the allowance you have left. Wait for `resetsAt`, or use your own declared upstream and key. The provider bills those calls to your provider account. Platform staff can also restore allowance by adjusting its quantity.

## Test with the double

The factory `createAiGenerationDouble(options)` from `@turnzero/ai_generation/testing` responds in place of the platform route behind unchanged `generateText` and `generateImage` calls. Pass `double.transport` to either. For a transport that wraps global `fetch`, replace it with `double.fetch` in the test.

The default is `pricing: 'usage'`: answers carry no allowance headers and have no allowance boundary. The double’s meter still counts calls. Queue answers with `double.prime(...)` and read the meter with `standing()` or the call log with `calls`.

Without a `model` option, the double admits `default` and any `gemini-` name. A factory naming models admits those alone. It does not read the platform's model settings; script `allowance_default_unavailable` with status 503 to test that failure.

To test a paused account, set `paused: true`, or use `refuseNext('account_paused')` for one call. To test an unlimited application’s allowance boundary, set `pricing: 'plans'` and a `quota`. In that form, answers carry allowance headers and calls at the boundary are refused.

Without `prices` or `weights`, the meter counts tokens. `prices` supplies the test’s own input and output dollar rates per million tokens, so it counts micro-dollars. These are test settings, not published rates. A test runs the sample below over the double.

For an image call, prime `{ text: '', image: { mimeType, data } }`, with `data` in base64.

```js
import assert from 'node:assert/strict';
import { AllowanceRefusal, generateText } from '@turnzero/ai_generation';
import { createAiGenerationDouble } from '@turnzero/ai_generation/testing';

// Usage answers have no allowance headers; the test meter still counts tokens.
const double = createAiGenerationDouble();
double.prime({ text: 'Three short points.', usage: { input: 10, output: 4 } });

const answer = await generateText(double.transport, { prompt: 'Summarize the notes.' });
assert.equal(answer.text, 'Three short points.');
assert.equal(double.standing().used, 14);
assert.deepEqual(answer.allowance, { used: null, quota: null, resetsAt: null });
// Script one paused-account response without calling the provider.
double.refuseNext('account_paused');
await assert.rejects(generateText(double.transport, { prompt: 'Again.' }), (error) => error instanceof AllowanceRefusal && error.refusal === 'account_paused');
```

The double returns the refusals in [Failures](#failures). `pricing: 'plans'` enables `allowance_exhausted`; `paused: true` enables `account_paused`. These failures come from its own setup:

| Refusal | Cause | Remedy |
| --- | --- | --- |
| `account_paused` | The double was created with `paused: true`, or `refuseNext` scripted the refusal. | Use this response to check pause handling. Use an unpaused double for a success test. |
| `allowance_exhausted` | The double uses `pricing: 'plans'` and its meter reached `quota`. | Check the unlimited-application fallback, or reset the meter for another success test. |
| `allowance_unavailable`, `allowance_busy`, `plan_quantity_unset`, `allowance_application_required` | `keyHeld: false`, `credential: 'session'`, or a scripted refusal caused it. | Keep the default key and credential for success tests. Script the other refusals to check their handling. |
| `allowance_path_refused`, `allowance_feature_refused`, `gateway_refused` | The request named a model the double does not accept, asked for another feature, or left the route. | Pass `model` to the factory, and call `generateText` or `generateImage`. |
| `environment_required`, `environment_mismatch` | The environment header is missing or differs from the factory's `environment`. | Send the factory's `environment` on the transport. |
| `unknown_upstream` | The upstream's name held a NUL character (U+0000) or an unpaired UTF-16 surrogate, which the double reads as no name, as the gateway does. | Send the name without the character. |
| `no primed answer`, `TypeError` from `prime` | No answer was queued, or a queued answer has the wrong form. | Queue an answer with `prime` after `reset()`. |
