api.models

Schema

api.models.create({ schema })

Dai alla sessione un JSON Schema e risponde oggetti in lugar di prosa. Questo è ciò che trasforma un model in algo che il resto del vostro cod può chiamare.

set at creationchanges the default outputJSON Schema
Using Python?

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

Senza un schema si ottiene un SMS, e chi lo consume deve ler in inglese. Con uno, si ottiene un valore — e la differenza non è convenient, è se la funzione successiva può essere scritta in absoluto.

Ajustare un

const extractor = await api.models.create({
  model: "gemini-3.5-flash",
  settings: { temperature: 0 },
  schema: {
    type: "object",
    properties: {
      supplier: { type: "string" },
      total:    { type: "number", description: "Amount including tax" },
      currency: { type: "string", description: "ISO 4217, e.g. EUR" },
      dueDate:  { type: "string", description: "ISO 8601 date" },
      lines: {
        type: "array",
        items: {
          type: "object",
          properties: { label: { type: "string" }, amount: { type: "number" } },
          required: ["label", "amount"],
        },
      },
    },
    required: ["supplier", "total", "currency"],
  },
});

const { outputs } = await extractor.generate({
  inputs: [{ type: "text", content: "Extract this invoice." },
           { type: "file", url: "https://example.com/invoice.pdf" }],
});

outputs[0].content;   // an object, not a string
extractor = api.models.create(
    model="gemini-3.5-flash",
    settings={"temperature": 0},
    schema={
        "type": "object",
        "properties": {
            "supplier": {"type": "string"},
            "total": {"type": "number", "description": "Amount including tax"},
            "currency": {"type": "string", "description": "ISO 4217, e.g. EUR"},
            "dueDate": {"type": "string", "description": "ISO 8601 date"},
            "lines": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {"label": {"type": "string"}, "amount": {"type": "number"}},
                    "required": ["label", "amount"],
                },
            },
        },
        "required": ["supplier", "total", "currency"],
    },
)

outputs = extractor.generate(inputs=[
    {"type": "text", "content": "Extract this invoice."},
    {"type": "file", "url": "https://example.com/invoice.pdf"},
])["outputs"]

outputs[0]["content"]   # an object, not a string

Cambia ciò che la sessione risponde per default

Una sessione con un schema risponde JSON a meno che un call sollevit di altra cosa; una sessione senza un schema risponde text.

await extractor.generate({ inputs });                          // JSON — the schema
await extractor.generate({ inputs, outputs: [{ type: "text" }] }); // prose, this once
extractor.generate(inputs=inputs)                              # JSON — the schema
extractor.generate(inputs=inputs, outputs=[{"type": "text"}])  # prose, this once

Le descripzion non sono documentari

Sono letti dal modello, e sono dove l'ambiguità è resoluta. total solument invita a supunt a fisc; total con « Importe compreso l'imposto » non.

CampoSenza una descripzionCon un
totalOgni visita può differire.«Imposto compreso» — liquidat.
dataQualsias formats che il model like.« ISO 8601» — parseable.
statusTexto libre, non delimitat.Usa enum: l'enum è il contrat.
{
  status: { type: "string", enum: ["paid", "pending", "overdue"] },
  confidence: { type: "number", description: "0 to 1. Below 0.5 means the document was unclear." }
}
{
    "status": {"type": "string", "enum": ["paid", "pending", "overdue"]},
    "confidence": {"type": "number", "description": "0 to 1. Below 0.5 means the document was unclear."},
}
Chiede l'incertezza, non infernî-la

Un modele riempie ogni campo che è dato. Un numero di confidenza, o un campo nullable con « null quando il documenti non dice » , è come si dice una lettura da un palpedo — e costa un paio de gène.

Valida-lo de qualquer forma

La forma è richiesta, fortemente, e si deve ancora verificat prima d'agire su ella — del medès issèr a validèd una replica da n'importe quals services che non controli.

const invoice = outputs[0].content;

if (typeof invoice?.total !== "number" || !invoice.currency) {
  throw new Error("the extraction did not come back in the expected shape");
}
invoice = outputs[0]["content"]

if not isinstance(invoice, dict) or not isinstance(invoice.get("total"), (int, float)) or not invoice.get("currency"):
    raise ValueError("the extraction did not come back in the expected shape")

Una forma per un solo appello

Non è necessario aprire una sessione per ottenere una forma. Chiede per ella in l'appel — utile quando ogni questione vuole una diversa.

await assistant.generate({
  inputs: [{ type: "text", content: "Three risks of shipping on a Friday." }],
  outputs: [{ type: "json", schema: {
    type: "object",
    properties: { risks: { type: "array", items: { type: "string" } } },
    required: ["risks"],
  } }],
});
assistant.generate(
    inputs=[{"type": "text", "content": "Three risks of shipping on a Friday."}],
    outputs=[{"type": "json", "schema": {
        "type": "object",
        "properties": {"risks": {"type": "array", "items": {"type": "string"}}},
        "required": ["risks"],
    }}],
)

Mantene il tamaño della risposta

Il schema è inviat con ogni chiamata, quindi un grande è un costo permanente per risposta. Prego per i campi che userà; un schema con trenta campos optional che non legè mai è pagat per trenta volte.