# generate()

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

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

Chiede a sessione per qualcosa. Questo è l'appello che spende, e quello senza scadenza — una lunga generazion va jusqu'a fine.

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

## Parâmetros {#parameters}

| Name | Type | Requirement | Description |
| --- | --- | --- | --- |
| `inputs` | array | obrigatório | Cee che le da. Vedere [Tipologies d'intput](/pt/sdk/concepts/inputs). |
| `outputs` | array |  | Ce que si vuole indietro. Predefinit a forma della sessione — JSON quando ha un schema, testo altrimenti. |

Un array supròs è accettat come inputs, che è la forma breve per il cas comun.

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

## Retorno {#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 }
}
```

> **Modele e servie Modele sono due facts differentes**
>
> Una è la intenzione, l'altra è la risposta. Essi generalmente coinciden; quando non lo fa, servitModel è quello che explica il risultato e il costo.

## Lectura del costo {#cost}

`usage.credits` è la carica real, liquidata dopo la chiamata contro quello che il provider ha segnalat. `preAuthorized` è ciò che era tenuta anterioramente; è tornato tutto il inutilizato. `estimated: true` significa che il provider non ha segnalat nulla e la quantita è derivata — vale la pena registrar, perché è un caso in cui la cifra non è misurata.

```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,
});
```

## Non è un termine per la convocazione {#timeout}

Deliberatamente. Il server non s'imprime perché tu hai parato d'ascoltare — termina il lavoro e lo fa — per cui rinunciare dopo un minuto significava pagare per una risposta che non hai mai visto. Un video dura minutos; SMS passa un minuto con suficiente frequent.

- Qua li limite il lavoro è il textuo de saída imposto al provider, non un timer cliente-parte.
- Passa il tuo proprio `timeout` sul cliente se realmente lo vuoi, sabiendo ce fa e non stop.
- Per mostrare il progresso, invece de lasciare il chillante aguardando con nulla, use un [virare di streaming](/pt/sdk/ref/models/turn/streaming).

## -Quel che è mantenut dopo {#memory}

In una sessione con memoria, i due messaggi sono memorizzati — il tuo e la risposta — con il model e l'uso sulla risposta. Binary non entra in storage: una immagine generata o un file è mantenu per referenza, non da suoi bytes.

> **Scrivi tu stesso i media generati**
>
> Il risultato ti da i bytes una volta. Se non li salva, la conversazione si ricorda di che un file è stato prodotto e non sarà in grado di dar-lo a te di nuovo.

## Erros {#errors}

| Código | Status | Quando |
| --- | --- | --- |
| inputs_required | 400 | Inputs mancantis o vazios. |
| discussion_not_found | 404 | Nessuna sessione di questo conto con que id. |
| context_too_large | 400 | Piu grande que la finestra del modele. Refused prima di ogni débito. |
| not_enough_credits | 402 | Cresciut ca non a sufficiènCredits, portando lo que era richiesto. |
| generation_failed | 502 | Il provider ha rifiutat. Il messaggio è del provider, redatto. |

> **discussion_not_found è il nome storico**
>
> È il che una sessione mancante risponde qui, e è mantenut perché integrazionis coincident sobre ella. Altredèsonde la medèsi situazion lee 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` mantiene intenzionalmente il messaggio del provider: è il fallimento de sua richiesta — una immagine illegibile, una combinazione non supportata — e il detail è lo que le permite repará-lo. Ha stato pulit di tutto interno antes di raggiunger.

- [Tipos de entrada](/pt/sdk/concepts/inputs): Texto, immagini, registrazioni, clips, passaggi — e tre modos de fornir cada.
- [Tipos de saída](/pt/sdk/concepts/outputs): Cenès retorna, e scribe binar.
- [Créditos](/pt/sdk/concepts/credits): Pre-autorizazion, regolamento, e come un déficit è negato.

```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
```
