# Schema

Canonical URL: https://developers.iagenify.com/pt/sdk/ref/models/schema/
Language: pt

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

Status: set at creation · changes the default output · JSON Schema

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 {#setting}

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

## Cambia ciò che la sessione risponde per default {#default}

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

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

## Le descripzion non sono documentari {#descriptions}

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

| Campo | Senza una descripzion | Con un |
| --- | --- | --- |
| total | Ogni visita può differire. | «Imposto compreso» — liquidat. |
| data | Qualsias formats che il model like. | « ISO 8601» — parseable. |
| status | Texto libre, non delimitat. | Usa enum: l'enum è il contrat. |

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

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.

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

## Una forma per un solo appello {#per-call}

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

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

## Mantene il tamaño della risposta {#size}

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.

- [Tipos de saída](/pt/sdk/concepts/outputs): Tutto o chema che si può restituire, e quanto binarèt scritè.
- [generate()](/pt/sdk/ref/assistant-session/generate): Pregunta, e ce ne torna.

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

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

```python
{
    "status": {"type": "string", "enum": ["paid", "pending", "overdue"]},
    "confidence": {"type": "number", "description": "0 to 1. Below 0.5 means the document was unclear."},
}
```

```python
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")
```

```python
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"],
    }}],
)
```
