AssistenteSessione

generate()

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.

POST /api/ai/models/:id/generatebilledno timeout
Using Python?

Switch any code block to Python: the choice applies to every page. Python SDK guide and resource reference.

Parâmetros

inputsarrayobrigatório

Cee che le da. Vedere Tipologies d'intput.

outputsarray

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.

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

Retorno

{
  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 }
}
{
    "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

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.

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

Non è un termine per la convocazione

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.

-Quel che è mantenut dopo

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

CódigoStatusQuando
inputs_required400Inputs mancantis o vazios.
discussion_not_found404Nessuna sessione di questo conto con que id.
context_too_large400Piu grande que la finestra del modele. Refused prima di ogni débito.
not_enough_credits402Cresciut ca non a sufficiènCredits, portando lo que era richiesto.
generation_failed502Il 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.

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;
}
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

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.