# generate()

Canonical URL: https://developers.iagenify.com/sdk/ref/assistant-session/generate/
Language: en

`assistant.generate({ inputs, outputs }) → Promise<Result>`

Ask the session for something. This is the call that spends, and the one with no deadline — a long generation runs to the end.

Status: POST /api/ai/models/:id/generate · billed · no timeout

## Parameters {#parameters}

| Name | Type | Requirement | Description |
| --- | --- | --- | --- |
| `inputs` | array | required | What you are giving it. See [Input types](/sdk/concepts/inputs). |
| `outputs` | array |  | What you want back. Defaults to the session's shape — JSON when it has a schema, text otherwise. |

An array on its own is accepted as the inputs, which is the short form for the common case.

```javascript
await assistant.generate({ inputs: [{ type: "text", content: "Hello" }] });
await assistant.generate([{ type: "text", content: "Hello" }]);   // the same
```

## Returns {#returns}

```javascript
{
  ok: true,
  outputs: [{ type: "text", content: "…" }],
  usage: {
    credits: 3,            // what you were actually charged
    preAuthorized: 5,      // what was held before the call; the difference came back
    estimated: false,      // true when the provider reported no usage and it was estimated
    inputTokens: 1840,
    outputTokens: 77,
    cachedTokens: 1320,    // input served from cache, charged at a fraction
    thinkingTokens: 54
  },
  model: "gemini-3.5-flash",      // what you asked for
  servedModel: "gemini-3.5-flash", // what actually answered
  service: "text-to-text",
  settings: { },                   // on video and image: the definition, length and sound billed
  timing: { startTime, endTime, durationMs }
}
```

> **model and servedModel are two different facts**
>
> One is the intention, the other is what answered. They usually match; when they do not, servedModel is the one that explains the result and the cost.

## Reading the cost {#cost}

`usage.credits` is the real charge, settled after the call against what the provider reported. `preAuthorized` is what was held beforehand; anything unused came back. `estimated: true` means the provider reported nothing and the amount was derived — worth logging, because it is the one case where the figure is not measured.

```javascript
const { usage } = await assistant.generate({ inputs });

await ledger.record({
  user: userId,
  credits: usage.credits,
  estimated: usage.estimated,
  cached: usage.cachedTokens ?? 0,
  ms: /* from timing */ undefined,
});
```

## There is no deadline on this call {#timeout}

Deliberately. The server does not stop because you stopped listening — it finishes the work and bills it — so giving up after a minute would mean paying for an answer you never saw. A video takes minutes; text crosses a minute often enough.

- What bounds the work is the output ceiling imposed on the provider, not a client-side timer.
- Pass your own `timeout` on the client if you really want one, knowing what it does and does not stop.
- To show progress rather than leave the caller waiting with nothing, use a [streaming turn](/sdk/ref/models/turn/streaming).

## What is kept afterwards {#memory}

On a session with memory, both messages are stored — yours and the answer — with the model and the usage on the answer. Binary does not go into storage: a generated image or a file is kept by reference, not by its bytes.

> **Write generated media out yourself**
>
> The result hands you the bytes once. If you do not save them, the conversation will remember that a file was produced and will not be able to give it to you again.

## Errors {#errors}

| Code | Status | When |
| --- | --- | --- |
| inputs_required | 400 | inputs was missing or empty. |
| discussion_not_found | 404 | No session of this account with that id. |
| context_too_large | 400 | Bigger than the model's window. Refused before any debit. |
| not_enough_credits | 402 | Raised as NotEnoughCredits, carrying what was required. |
| generation_failed | 502 | The provider refused. The message is the provider's, redacted. |

> **discussion_not_found is the historic name**
>
> It is what a missing session answers here, and it is kept because integrations match on it. Elsewhere the same situation reads session_not_found.

```javascript
import { NotEnoughCredits, IaGenifyError } from "iagenify";

try {
  const { outputs } = await assistant.generate({ inputs });
  return outputs;
} catch (err) {
  if (err instanceof NotEnoughCredits) {
    return { error: `Needs ${err.required} credits, ${err.available} available.` };
  }
  if (err instanceof IaGenifyError && err.code === "context_too_large") {
    return { error: "This conversation is too long. Start a new one." };
  }
  if (err instanceof IaGenifyError && err.code === "generation_failed") {
    // The provider's own message, cleaned. Useful to you; usually not to your users.
    console.error("generation failed:", err.message);
    return { error: "That could not be generated." };
  }
  throw err;
}
```

`generation_failed` keeps the provider's message on purpose: it is the failure of your request — an unreadable image, an unsupported combination — and the detail is what lets you fix it. It has been cleaned of anything internal before it reaches you.

- [Input types](/sdk/concepts/inputs): Text, pictures, recordings, clips, passages — and three ways to supply each.
- [Output types](/sdk/concepts/outputs): What comes back, and writing binary out.
- [Credits](/sdk/concepts/credits): Pre-authorisation, settlement, and how a shortfall is refused.

```python
assistant.generate(inputs=[{"type": "text", "content": "Hello"}])
assistant.generate([{"type": "text", "content": "Hello"}])   # the same
```

```python
{
    "ok": True,
    "outputs": [{"type": "text", "content": "…"}],
    "usage": {
        "credits": 3,            # what you were actually charged
        "preAuthorized": 5,      # what was held before the call; the difference came back
        "estimated": False,      # True when the provider reported no usage and it was estimated
        "inputTokens": 1840,
        "outputTokens": 77,
        "cachedTokens": 1320,    # input served from cache, charged at a fraction
        "thinkingTokens": 54,
    },
    "model": "gemini-3.5-flash",        # what you asked for
    "servedModel": "gemini-3.5-flash",  # what actually answered
    "service": "text-to-text",
    "settings": {},                     # on video and image: the definition, length and sound billed
    "timing": {"startTime": ..., "endTime": ..., "durationMs": ...},
}
```

```python
result = assistant.generate(inputs=inputs)
usage = result["usage"]

ledger.record(
    user=user_id,
    credits=usage["credits"],
    estimated=usage.get("estimated"),
    cached=usage.get("cachedTokens", 0),
    ms=(result.get("timing") or {}).get("durationMs"),
)
```

```python
from iagenify import IaGenifyError, NotEnoughCredits

def ask(assistant, inputs):
    try:
        return assistant.generate(inputs=inputs)["outputs"]
    except NotEnoughCredits as error:
        return {"error": f"Needs {error.required} credits, {error.available} available."}
    except IaGenifyError as error:
        if error.code == "context_too_large":
            return {"error": "This conversation is too long. Start a new one."}
        if error.code == "generation_failed":
            # The provider's own message, cleaned. Useful to you; usually not to your users.
            print("generation failed:", error)
            return {"error": "That could not be generated."}
        raise
```
