# catalogue()

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

`api.catalogue() → Promise<Price[]>`

Ogni modelle che il cont puè chiamare, con il suo prezzo real. Lee-lo in lugar de copiare una lista di prezzo in tuo codio.

Status: GET /api/ai/prices · free · the billing grid itself

Un appli che codifica un prezzo driva il giorno in cui un model è aggiunto, aposentat o repretata — e la deriva è invisibilisat fino a un utente è citat un numero e caricat un altro. Una che lis questo non driva.

## Una fila {#shape}

```javascript
{
  model: "gemini-3.5-flash",
  service: "text-to-text",
  provider: "gemini",
  unit: "1M tokens",
  credits: null,              // a flat price, when the unit has one
  creditsInput: 375,
  creditsOutput: 2250,
  creditsOutputVideo: null,
  videoOutputTokens: null,
  resolution: null,
  audio: null,
  deprecatedAfter: null,
  contextWindow: 1048576,     // token-billed rows only
  maxOutput: 65536,
  cachedInputRate: 0.25
}
```

## I campi {#fields}

| Name | Type | Requirement | Description |
| --- | --- | --- | --- |
| `model` | string |  | Il nome che passa come `model` in altre parti. |
| `service` | string |  | Un modelo appare una volta per servizio che serve. |
| `provider` | string |  | Informativa: si chiede un model, mai un provider. |
| `unit` | string |  | Se decide quale campo de credito aplica — vee [Units](#units). |
| `credits` | integer|null |  | Il prezzo fisso di una unit. `null` sulle files a beca-token. |
| `creditsInput · creditsOutput` | integer|null |  | Per milione di jetons, ogni direczion conta e raduna su suo. |
| `creditsOutputVideo · videoOutputTokens` | integer|null |  | Per un modele che sa rispondere con video: la cadenza di quel output, e il suo conteggio fisso. |
| `resolution` | string|null |  | Ce distingue due filas di un modele — un formato d'image, una definizion video. |
| `audio` | boolean|null |  | Se questa fila è quella con son. Un video con son è un prezzo differente. |
| `contextWindow` | integer|null |  | Tokens il modele accetta in un turn. Ride-token-billed solo. |
| `maxOutput` | integer|null |  | Il tectura di output che il provider accetta. |
| `cachedInputRate` | number|null |  | La parte del tasso d'input pagada per un token servit da cache del provider. |
| `deprecatedAfter` | string|null |  | Una data dopo la quale questa fila cessa di ser servit. Non null è il tuo avviso di migrare. |

## Unidades, e qual campo ler {#units}

Lectura del campo errat è il erro comune qui, perché un ramèu de gamèn e un ramèu de plètènèu sono la stessa forma con differentes metàs riempie in.

| unit | Legî | Conted comas |
| --- | --- | --- |
| 1M jetons | CréditsInput · creditsExetput | Per milione, ogni direzione arrotondat separatamente. |
| Imagem | i credits | Una immagine, a la risoluzion di quella fila. |
| Secundo | i credits | Un secundo de video, a que definizion e son. |
| 1K caracteres | i credits | Per mille caracteres di testo pronunciat. |
| minute | i credits | Per minuto di audio lect. |
| Canto | i credits | - Una pista. |
| appel | i credits | Un appello, qualunque fosse il suo tamaño. |

> **Nunca cadde con Ì Ì**
>
> Su una fila de stèm i credits è null, e credits . 100 silently deviene 100. Testa l'unit, poi lee il campo che nomes unit. Questo è l'un schema che produce un numero errat plutôt que un erro.

## I onze servis {#services}

Un service è un pair (input, output), e deriva da quello che si chiede piuttosto que dichiarat. Il medesimo modele quindi tiene diverse filas, una per par che può servire.

| servizio | Prende | Redae |
| --- | --- | --- |
| text-to-text | Texto | Texto |
| text-to-json | Text, plus un schema | Un oggetto che coincide con il schema |
| multimodal-a-texto | Textu con immagini, audio, video o documenta | Texto |
| Omnima | Input mixto | Sortitura, testo e media misto de un solo modelo |
| text-to-image | Texto, opcionalmente una foto di partenza | Una immagine |
| text-to-video | Texto, opcionalmente una foto di partenza | Un video |
| text-to-speech | Texto | Audio |
| Disparo a texto | Audio | Texto |
| text-to-musica | Texto | Una pista |
| text-a-redactio | Texto | Un vector |
| Recolocazione di testo | Una consulta e documenta | I documenti, reordinò |

## Quante fas retorn {#size}

80 filas, 28 modelli, 11 servizi, misurati oggi. La conta di filas supera la conta di modelli a causa delle varianti: un modello che serve tre servizi e viene in quattro talle è una dozzina de filas por sua mati.

> **A par del modele e la variante, mai il modele solo**
>
> Prendendo la prima fila per un modele da-te un prezzo che può appartenir a un'altra risoluzion, un altro service, o la versione senza son. Filtrare su quello che si sta per chiedere.

## Recettes {#recipes}

### Escolhe il modello più economico che sa rispondere in text

```javascript
const grid = await api.catalogue();

const cheapest = grid
  .filter((row) => row.service === "text-to-text" && !row.deprecatedAfter)
  .sort((a, b) => a.creditsInput - b.creditsInput)[0];

cheapest.model;        // what to pass as `model`
cheapest.maxOutput;    // the ceiling to stay under
```

### Estimare un shunt di testo prima di fare

L'estima è un plafond, non una prediczione: il costo real è misurato da quello che il fornitor informa, e costos de input cached meno.

```javascript
function estimateCredits(row, inputTokens, outputTokens) {
  if (row.unit !== "1M tokens") throw new Error(`not a token row: ${row.unit}`);
  const input = Math.ceil((inputTokens / 1_000_000) * row.creditsInput);
  const output = Math.ceil((outputTokens / 1_000_000) * row.creditsOutput);
  return input + output;
}

// What the same input costs once the provider is serving it from cache
function cachedInput(row, tokens) {
  return Math.ceil((tokens / 1_000_000) * row.creditsInput * row.cachedInputRate);
}
```

### Pret un video prima de generar un

Video è facturato dal secondo, e il secondo costa lo que la definizione e il costo sonoro. Quindi la fila che devi pret contra è quella che coincide con ambos.

```javascript
function videoCost(grid, model, { resolution, audio, seconds }) {
  const row = grid.find((r) =>
    r.model === model &&
    r.service === "text-to-video" &&
    r.resolution === resolution &&
    r.audio === audio,
  );
  if (!row) throw new Error("no row for that combination");
  return row.credits * seconds;
}
```

> **Un provider può restituire più di quanto tu chiesse**
>
> Un clip è talvolta un po 'piu longo di la durata richiesta, e i secondi facturati sono i secondi prodotès. Trat a per-segunda stima come un pavimento, e lasciare la sede in un budget che deve coprir uno.

### Construir un seleccionador de modelos

```javascript
const grid = await api.catalogue();

const byModel = new Map();
for (const row of grid) {
  const entry = byModel.get(row.model) || { model: row.model, services: new Set(), rows: [] };
  entry.services.add(row.service);
  entry.rows.push(row);
  byModel.set(row.model, entry);
}

// What one model can do, and what it costs to think with
for (const entry of byModel.values()) {
  const tokens = entry.rows.find((r) => r.unit === "1M tokens");
  console.log(
    entry.model,
    [...entry.services].join(" · "),
    tokens ? `${tokens.creditsInput} in / ${tokens.creditsOutput} out` : "",
    tokens?.contextWindow ?? "",
  );
}
```

### Vegar per un modele partindo

`deprecatedAfter` è l'unico advertit che si obteve in banda. Logging it transforme un futuro fallimento in una task datata.

```javascript
const leaving = (await api.catalogue()).filter((row) => row.deprecatedAfter);

for (const row of leaving) {
  console.warn(`${row.model} (${row.service}) stops being served after ${row.deprecatedAfter}`);
}

// And guard the one you depend on
const mine = grid.find((r) => r.model === MODEL && r.service === "text-to-text");
if (!mine) throw new Error(`${MODEL} is no longer in the catalogue`);
```

## Quante frequent l'ha lettura {#caching}

La grilla cambia quando i modelli o — rarmente, e mai mid-request. Lee a bott, tèlo, e rafòrnyalo in un programa di non per appello. Ciò che non devi fa is copiar in la fonte: poi un cambio diventa un deployment, e un citation errat in medio.

```javascript
let grid = null;
let readAt = 0;

export async function catalogue(api, maxAgeMs = 3_600_000) {
  if (!grid || Date.now() - readAt > maxAgeMs) {
    const fresh = await api.catalogue();
    if (fresh.length) { grid = fresh; readAt = Date.now(); }   // keep the last good one
  }
  if (!grid) throw new Error("no catalogue available");
  return grid;
}
```

> **Un array vazio è una risposta valida**
>
> Il metodo ripadè le filas che fu dat, e una lista vuota, invece de lançare. Codigo che indexes in esso, senza check breaks contra un server che serve nul — e daí que l'assistente sopra mantiene la grilla di ultima bona.

## Un modele che non è in grid {#missing}

Non c'è un repli implícito: chiedere un model che la grilla non porta per quel service è negat, con il model e il service nominat. Quel respinto è deliberat — una sostituzione taciturna farebbe cobrare un prezzo di un model per la risposta del outro.

- [Créditos](/pt/sdk/concepts/credits): Como un appello è pre-autorised, asegnò, e renied.
- [turn()](/pt/sdk/ref/models/turn): I apatrides rivere questi prezzi sono imputés.
- [Tipos de saída](/pt/sdk/concepts/outputs): Quale ogni servizio restitue, in SDK di forma di sprès.

```python
{
    "model": "gemini-3.5-flash",
    "service": "text-to-text",
    "provider": "gemini",
    "unit": "1M tokens",
    "credits": None,              # a flat price, when the unit has one
    "creditsInput": 375,
    "creditsOutput": 2250,
    "creditsOutputVideo": None,
    "videoOutputTokens": None,
    "resolution": None,
    "audio": None,
    "deprecatedAfter": None,
    "contextWindow": 1048576,     # token-billed rows only
    "maxOutput": 65536,
    "cachedInputRate": 0.25,
}
```

```python
grid = api.catalogue()

cheapest = min(
    (row for row in grid if row["service"] == "text-to-text" and not row["deprecatedAfter"]),
    key=lambda row: row["creditsInput"],
)

cheapest["model"]       # what to pass as model=
cheapest["maxOutput"]   # the ceiling to stay under
```

```python
import math

def estimate_credits(row, input_tokens, output_tokens):
    if row["unit"] != "1M tokens":
        raise ValueError(f"not a token row: {row['unit']}")
    return (math.ceil(input_tokens / 1_000_000 * row["creditsInput"])
            + math.ceil(output_tokens / 1_000_000 * row["creditsOutput"]))

# What the same input costs once the provider is serving it from cache
def cached_input(row, tokens):
    return math.ceil(tokens / 1_000_000 * row["creditsInput"] * row["cachedInputRate"])
```

```python
def video_cost(grid, model, *, resolution, audio, seconds):
    row = next((r for r in grid
                if r["model"] == model and r["service"] == "text-to-video"
                and r["resolution"] == resolution and r["audio"] == audio), None)
    if row is None:
        raise ValueError("no row for that combination")
    return row["credits"] * seconds
```

```python
grid = api.catalogue()

by_model = {}
for row in grid:
    entry = by_model.setdefault(row["model"], {"model": row["model"], "services": set(), "rows": []})
    entry["services"].add(row["service"])
    entry["rows"].append(row)

# What one model can do, and what it costs to think with
for entry in by_model.values():
    tokens = next((r for r in entry["rows"] if r["unit"] == "1M tokens"), None)
    print(
        entry["model"],
        " · ".join(sorted(entry["services"])),
        f"{tokens['creditsInput']} in / {tokens['creditsOutput']} out" if tokens else "",
        (tokens or {}).get("contextWindow") or "",
    )
```

```python
grid = api.catalogue()
leaving = [row for row in grid if row["deprecatedAfter"]]

for row in leaving:
    print(f"{row['model']} ({row['service']}) stops being served after {row['deprecatedAfter']}")

# And guard the one you depend on
mine = next((r for r in grid if r["model"] == MODEL and r["service"] == "text-to-text"), None)
if mine is None:
    raise RuntimeError(f"{MODEL} is no longer in the catalogue")
```

```python
import time

_grid = None
_read_at = 0.0

def catalogue(api, max_age=3600):
    global _grid, _read_at
    if _grid is None or time.monotonic() - _read_at > max_age:
        fresh = api.catalogue()
        if fresh:                       # keep the last good one
            _grid, _read_at = fresh, time.monotonic()
    if _grid is None:
        raise RuntimeError("no catalogue available")
    return _grid
```
