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

# Generate text

> Submit a generation from a mutation and read its answer in the continuation.

`ai.generate(ctx, key, generation, { once, then, within })` submits one
generation to the catalog entry's pack, in your mutation's transaction.
The continuation declares `result: ai.result` and decodes it with
`ai.answer(key, result)`.

```ts bijection/notes.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { mutation, t } from "@bijectionhq/bijection";
import { ai } from "./ai";
import { editor, notes, workspace } from "./schema";

export const summarize = mutation(
  { under: workspace, allow: [editor], args: { id: t.key(notes) } },
  async (ctx, { id }) => {
    const note = await ctx.get(notes(id));
    if (note === null) return ctx.refuse("Absent", "no such note.");
    await ai.generate(ctx, "triage", { messages: [{ role: "user", content: note.text }] }, {
      once: ["summary", id],
      then: summarized.with({ id }),
    });
    return null;
  },
);

export const summarized = mutation(
  { under: workspace, args: { id: t.key(notes), result: ai.result } },
  async (ctx, { id, result }) => {
    const answer = ai.answer("triage", result);
    if (answer.ok) await ctx.patch(notes(id), { summary: answer.value.text });
    return null;
  },
);
```

A generation is `{ system, messages, maxOutputTokens, temperature, output }`,
all but `messages` optional. Messages carry text, images and documents as
bytes (base64), never URLs a provider would fetch; the model must declare
the `images` or `documents` capability. `output: { name, schema }` asks for
one structured value, with `schema` from `jsonSchema(type)`. It is decoded
as `answer.structured` and must be checked before use: [typed
tasks](https://docs.bijection.com/models/tasks.md) do that for you.

`within` defaults to the pack's contract. `ai.request(key, generation)`
answers the operation and body a generation would send, without sending
it.

## Read the result

| Helper | Answers |
| - | - |
| `ai.answer(key, result)` | `Answer`: `{ text, structured, finishReason, usage, servedBy, costMicroUsd }` |
| `ai.vectors(key, result, count)` | One vector per input, in input order |
| `ai.ranking(key, result, count)` | `{ index, score }` per document, best first |

Each answers a `Result`. A refused task passes its code through:
`Unknown` (the call may have happened, and is never resent), `Expired`,
`Withdrawn` or `Failed`. An answer the library cannot decode is `Failed`.
`ai.cost(key, usage)` answers the list-price cost in micro-USD.


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