Generate an image with AI #
On this page
Prompt:
Have the backend draw a picture for each new recipe. I don't have a key for any AI service.
Also works:
- "Make a cover image using the platform's AI key."
- "Draw an avatar from each user's description."
Generate images from your backend, with AI calls charged to the account's balance. Choose an image model and send its request through the platform; no provider key is needed.
What your AI does #
- Installs the AI Generation package used for text calls.
- Writes the transport, the small function that sends each request to the platform. It reads the settings a deployed copy receives, as step 3's sample does.
- Calls the package's
generateImageover that transport. - Asks you which image model to use if the prompt does not say. It asks nothing else.
What you need #
- An application. Size and usage explains charges to its account.
- No provider account and no provider key.
Before your AI starts #
For your AI: Check the following before starting.
- A signed-in connection (Connect your AI assistant).
- The application's identifier, from
list_applications. - The current AI charge on the pricing page, or from
read_rate_card. - The backend's folder, the one that holds
package.json.
Steps #
1. Take the package #
Call read_library with contains: "ai_generation" to find the ai_generation library entry, then with entry: "ai_generation" to read it. Install it by following Use the feature package library. Image and text calls through this route draw the account's balance. Image calls use the same platform route as text calls, with no provider key.
The package's generateImage sends one image request through your transport and returns the picture. A request that names no model uses DEFAULT_IMAGE_MODEL. Give prompt as a nonempty string. A missing or empty prompt raises TypeError before the package sends a request.
2. Choose an image model #
The platform passes on a request for any model whose name begins with gemini-. It has a price for each of these four image models, charged by the tokens of the picture each one makes:
gemini-3.1-flash-imagegemini-3.1-flash-lite-imagegemini-nano-banana-2.1gemini-3-pro-image
Each picture is charged to the account's balance at Google's published price for its model, plus a markup. Read the current rates on the pricing page.
The platform also passes on a request for another gemini- image model the provider still serves. If the platform has no price for that model, it uses the priced model with the highest base output rate, taking that model's other rates too.
A request for audio or video output is refused with allowance_feature_refused.
3. Send the request from a route #
The package sends a POST to /egress/v0/ai-allowance/v1beta/models/<model>:generateContent on the platform's origin, its base web address. The transport adds the origin. It also sends the application's credential as the bearer token, as for a text call. The body holds the prompt and asks for image output with responseModalities: ['IMAGE'].
This server responds to POST /pictures with a picture drawn from the prompt in the request body, sent with its image type. It makes one request to the allowance gateway and cancels it if the incoming request is aborted. It returns HTTP 503 if the provider returns 429 or the platform refuses with allowance_busy. It returns HTTP 422 if the provider makes no picture.
// src/server.mjs: POST /pictures responds with a picture drawn from the prompt in the body.
import { createServer } from 'node:http';
import { AllowanceRefusal, AllowanceUpstreamError, generateImage } 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 MODEL = 'gemini-3.1-flash-image';
function requestSignal(req, res) {
const signal = Object.hasOwn(req, 'signal') ? req.signal : undefined;
if (signal) return signal;
// In a local run, abort when the response closes before it finishes.
const controller = new AbortController();
res.once('close', () => {
if (!res.writableFinished) controller.abort();
});
return controller.signal;
}
const port = Number(process.env.PORT ?? 8080);
createServer(async (req, res) => {
if (req.method === 'GET' && req.url === '/health') return res.writeHead(200).end('ok');
if (req.method !== 'POST' || req.url !== '/pictures') return res.writeHead(404).end();
const signal = requestSignal(req, res);
try {
req.setEncoding('utf8');
let prompt = '';
for await (const chunk of req) prompt += chunk;
if (prompt === '') return res.writeHead(400).end('a prompt is required');
signal.throwIfAborted();
const withSignal = (path, init) => transport(path, { ...init, signal });
const { image: picture } = await generateImage(withSignal, { prompt, model: MODEL });
signal.throwIfAborted();
if (!picture) return res.writeHead(422).end('no picture for this prompt');
res.writeHead(200, { 'content-type': picture.mimeType }).end(picture.bytes);
} catch (error) {
if (signal.aborted) return res.destroy();
if (error instanceof AllowanceRefusal) {
console.error({ name: error.name, status: error.status, refusal: error.refusal });
} else if (error instanceof AllowanceUpstreamError) {
console.error({ name: error.name, status: error.status });
} else {
console.error({ name: 'UnexpectedError' });
}
const providerBusy = error instanceof AllowanceUpstreamError && error.status === 429;
const allowanceBusy = error instanceof AllowanceRefusal && error.refusal === 'allowance_busy';
if (providerBusy || allowanceBusy) return res.writeHead(503).end('image generation is busy');
res.writeHead(502).end();
}
}).listen(port, () => console.log(`listening on ${port}`));
4. Read the picture from the answer #
generateImage answers with image, which holds the picture's bytes and its mimeType. It looks in the provider's first candidate, skips parts marked as thinking, and takes the first nonempty image there. It does not look in later candidates.
When the provider blocks a prompt or returns no usable picture in the first candidate, the answer has image: null. blockReason and finish give the provider's reasons when supplied. Either can be null.
A refusal from the platform itself throws AllowanceRefusal. Its refusal member names the refusal, such as allowance_busy, and detail explains it. A provider's non-success answer throws AllowanceUpstreamError, with its status and its body. On the route itself, an answer without the x-egress-upstream header is a refusal from the platform. Its JSON body names the refusal in error, such as allowance_busy, and explains it in detail.
5. Retry a busy answer #
The image model's provider can answer 429 RESOURCE_EXHAUSTED while its shared capacity is busy. The platform retries such a call itself, up to four more times, with increasing pauses, before the 429 reaches you. If the provider is still busy after those retries, the helper throws AllowanceUpstreamError with quota set to true.
The platform answers allowance_busy as an AllowanceRefusal when your application already has as many allowance calls in progress as the gateway copy handling the call allows. This clears when an in-progress call ends. The sample returns HTTP 503 for either busy response and lets the caller decide when to try again. If the incoming request is aborted, the transport cancels its pending gateway request.
For account_paused, follow Handle an account pause. Do not retry the call.
6. Know what a picture costs #
A picture's tokens are charged once, at the model's image-output rate. The prompt's tokens are charged at the model's input rate. AI Generation says how every call is counted.
Read the application’s AI spend this UTC month with tzcloud_read_usage, under ai_allowance_usd_micros. No allowance limit applies to this total. read_balance gives the account’s balance, pause state and monthly usage lines. Responses to customer applications' AI calls omit allowance headers.
7. Deploy #
Deploy as Deploy from your computer describes. The deploy gives the application the platform credential that the transport sends. That credential is bound to its environment, so the call needs no environment header.
Expected result #
POST /pictures responds with the picture’s bytes and image type, such as image/png. tzcloud_read_usage reports the application’s AI spend this month. The sample stops on account_paused. It also stops on allowance_exhausted, which applies only to Turn Zero's own applications on the unlimited plan. For an account pause, follow Handle an account pause.
Refusals #
See the refusals reference for other platform errors.
| Refusal | Status | Cause | Remedy |
|---|---|---|---|
account_paused |
429 | The account is paused until it has Free Allowance available again or credit it can use. | Follow Handle an account pause. Do not retry the call. |
allowance_exhausted |
429 | An unlimited application reached its allowance quantity. | Wait for the reset or use an upstream declared with your own stored key. The provider bills those calls to your provider account. This boundary does not apply to customer applications. |
allowance_busy |
429 | Your application already has as many allowance calls in progress as the gateway copy handling the call allows. | Retry after one of them ends. |
allowance_feature_refused |
400 | The request asked for audio or video output, or another feature the allowance does not cover. | Ask for image or text output only. |
allowance_path_refused |
403 | The request did not use a POST generate method with default or a gemini- model selector. |
Use a Gemini image model from step 2. The gateway accepts default as a selector. For image output, use generateImage with its image default or name an image model. |
Related #
- Call an AI model: text calls, the fallback, and the test double.
- AI Generation: the package's names, how calls are counted in dollars, and every refusal.
- Size and usage: application limits and charges to the account.
- A deployed app's settings: the origin and the credential the transport reads.