# Pareta SDKs — full documentation > Pareta is a verified-inference provider built for repeatable production AI workloads. Through one OpenAI-compatible endpoint and one model ID, `auto`, your application can access Pareta's fleet of open-weight specialists, including several distilled in-house. Pareta checks every result against the workload's quality bar and automatically escalates to a frontier model whenever the specialist path cannot meet it. You are charged only for the model that produces the final response. For workloads handled by Pareta specialists, serving costs can be 30–140× lower than the comparable frontier model, and you can verify the quality and economics on your own production data with the evals API. Every response carries the exact amount billed and an estimated frontier comparison. Authenticate with a `pareta_sk_` key from the dashboard or the `PARETA_API_KEY` environment variable. Pareta ships one SDK per language, all sharing these docs and the same `/v1` HTTP API: Python (`pip install pareta`, `from pareta import Pareta`); TypeScript/JavaScript (`npm install pareta`, `import { Pareta } from "pareta"`). This file concatenates the entire Pareta SDK documentation (guide + examples + reference, every language) for single-read agent consumption. Source: sdk/docs/ in the repo; browsable at https://docs.pareta.ai. --- # Installation & authentication The `pareta` package is the official client for [Pareta](https://pareta.ai), available for **Python** (`pip install pareta`) and **TypeScript/JavaScript** (`npm install pareta`). It runs metered OpenAI-compatible inference against `model="auto"` (the verified-inference path behind `auto` — not a fixed model; nothing to deploy, no model to pick), benchmarks auto against frontier models on your own data, and reads auto's cost and quality metrics — all from code. This page gets you installed, authenticated, and making a first call. A few platform truths to know up front, because they shape the whole API: - **GPUs are hidden.** You never pass a hardware knob. The serving stack behind `model="auto"` is Pareta's job, resolved per request. - **There is one model id.** `models.list()` returns exactly one entry — `"auto"`. Which model serves a request is Pareta's decision, made per request. - **Inference and evals are metered against your org balance.** A successful call debits credit; an empty balance raises `InsufficientCreditsError`. Top-up is browser-only — the SDK never touches billing. - **Inference is OpenAI-compatible.** The `/v1/chat/completions` endpoint speaks the OpenAI wire format, so you can use this SDK or the stock `openai` client interchangeably. ## Install `pareta` requires Python 3.10+ and depends only on `httpx`. Install it with whichever tool you already use: ```bash pip install pareta ``` ```bash uv add pareta ``` ```bash poetry add pareta ``` The package ships type hints (`py.typed`), so editors and `mypy` get full autocomplete on every method and response model. ### Optional extras: CLI and MCP server Two more interfaces ship as optional extras on the same Python package: ```bash pip install "pareta[cli]" # the `pareta` shell command pip install "pareta[mcp]" # the `pareta-mcp` Model Context Protocol server ``` The [CLI](cli.md) gives you the same surface as shell commands (`pareta chat`, `pareta evals run`, …); the [MCP server](mcp.md) exposes it to an AI agent (Claude Desktop, Cursor) as tools. Both authenticate from the same `PARETA_API_KEY`. Each installs a console script, so an isolated install with [`pipx`](https://pipx.pypa.io) (`pipx install "pareta[cli]"`) keeps it off your project's dependency tree while still putting the command on your PATH. ## Authenticate Every request is authenticated with a `pareta_sk_` secret key sent as a Bearer token. You mint keys in the [dashboard](https://app.pareta.ai) — key management is browser-only, and the SDK only ever *consumes* a key. It never creates, lists, or revokes them. ### Recommended: `from_env()` The cleanest path is to put your key in the environment and let the client read it. `from_env()` reads `PARETA_API_KEY` and the optional `PARETA_BASE_URL`: ```bash export PARETA_API_KEY="pareta_sk_..." ``` **Python** ```python from pareta import Pareta pa = Pareta.from_env() # reads PARETA_API_KEY (+ PARETA_BASE_URL) # List the model catalog — exactly one entry: "auto". for model in pa.models.list(): print(model.id, model.owned_by) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // reads PARETA_API_KEY (+ PARETA_BASE_URL) // List the model catalog — exactly one entry: "auto". for (const model of await pa.models.list()) { console.log(model.id, model.ownedBy); } ``` Keeping the key out of source is the point — `from_env()` means your code carries no secret. ### Explicit key You can also pass the key directly. The constructor is keyword-only: **Python** ```python from pareta import Pareta pa = Pareta(api_key="pareta_sk_...") ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = new Pareta({ apiKey: "pareta_sk_..." }); ``` If `api_key` is falsy and `PARETA_API_KEY` is unset, the client raises `ParetaError` at construction time with a message pointing you to mint a key: **Python** ```python import pareta try: pa = pareta.Pareta(api_key=None) # and PARETA_API_KEY unset except pareta.ParetaError as e: print(e) # missing API key. Pass api_key=… or set PARETA_API_KEY (mint a pareta_sk_ key in the dashboard). ``` **TypeScript** ```typescript import { Pareta, ParetaError } from "pareta"; try { const pa = new Pareta({ apiKey: undefined }); // and PARETA_API_KEY unset } catch (e) { if (e instanceof ParetaError) { console.log(e.message); // missing API key. Pass apiKey: … or use Pareta.fromEnv() with PARETA_API_KEY (mint a pareta_sk_ key in the dashboard). } } ``` ## Constructor options **Python** ```python Pareta( api_key: str | None = None, # pareta_sk_ key; falls back to nothing (from_env reads the env) base_url: str | None = None, # defaults to "https://api.pareta.ai" timeout=None, # defaults to httpx.Timeout(600.0, connect=10.0) max_retries: int = 2, # retries on 408/409/429/500/502/503/504 http_client: httpx.Client | None = None, # bring your own httpx.Client ) ``` **TypeScript** ```typescript new Pareta({ apiKey?: string, // pareta_sk_ key; falls back to nothing (fromEnv reads the env) baseURL?: string, // defaults to "https://api.pareta.ai" timeout?: number, // milliseconds; defaults to 600_000 maxRetries?: number, // default 2; retries on 408/409/429/500/502/503/504 fetch?: typeof fetch, // inject your own fetch implementation }); ``` - **`base_url`** defaults to the production API, `https://api.pareta.ai`, and is normalized (trailing slash stripped). Override it only to point at a non-prod environment; set `PARETA_BASE_URL` to do the same via `from_env()`. - **`max_retries`** (default 2) retries idempotent failures and rate limits with exponential backoff that honors a `Retry-After` header. See [Errors & retries](errors-and-retries.md). - **`http_client`** lets you supply a pre-configured `httpx.Client` (custom proxies, connection limits, transport). When you pass one, the SDK does not own it and `close()` will not shut it down. ## Manage the connection The client holds a pooled HTTP connection. Use it as a context manager so the pool is released cleanly: **Python** ```python from pareta import Pareta with Pareta.from_env() as pa: resp = pa.chat.completions.create( model="auto", # the one model id — Pareta routes the request messages=[{"role": "user", "content": "Extract the total from this invoice: ..."}], ) print(resp.choices[0].message.content) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); const resp = await pa.chat.completions.create({ model: "auto", // the one model id — Pareta routes the request messages: [{ role: "user", content: "Extract the total from this invoice: ..." }], }); console.log(resp.choices[0].message.content); ``` Outside a `with` block, call `pa.close()` when you are done. (`close()` is a no-op when you supplied your own `http_client`.) The TypeScript client holds no owned connection — it uses `fetch` per request, so there is nothing to close. ## Async client `AsyncPareta` mirrors `Pareta` exactly — same constructor, same `from_env()`, same resource namespaces — with awaitable methods and `aclose()` / `async with`: **Python** ```python import asyncio from pareta import AsyncPareta async def main(): async with AsyncPareta.from_env() as pa: resp = await pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Summarize this contract clause: ..."}], ) print(resp.choices[0].message.content) asyncio.run(main()) ``` **TypeScript** There is no `AsyncPareta` in TypeScript — there is one `Pareta` client and it is already async. Every I/O method returns a `Promise` you `await` (and streaming methods return an `AsyncIterable` you drive with `for await`). The same client works in sync-looking and concurrent code; there is no separate sync/async split to choose between. ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Summarize this contract clause: ..." }], }); console.log(resp.choices[0].message.content); ``` ## Your first metered call Inference debits your org balance on success. If the balance is empty, the call raises `InsufficientCreditsError` (402) — top up in the dashboard, which is the only place billing lives: **Python** ```python from pareta import Pareta, InsufficientCreditsError pa = Pareta.from_env() try: resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "What is the invoice number?"}], temperature=0, # extra OpenAI params pass straight through ) print(resp.choices[0].message.content) print(resp.usage.total_tokens, "tokens") except InsufficientCreditsError: print("Org out of credit — top up in the dashboard.") ``` **TypeScript** ```typescript import { Pareta, InsufficientCreditsError } from "pareta"; const pa = Pareta.fromEnv(); try { const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "What is the invoice number?" }], temperature: 0, // extra OpenAI params pass straight through }); console.log(resp.choices[0].message.content); console.log(resp.usage.totalTokens, "tokens"); } catch (e) { if (e instanceof InsufficientCreditsError) { console.log("Org out of credit — top up in the dashboard."); } else { throw e; } } ``` The `model` is `"auto"` — the only model id there is. One request, one debit, however many internal model calls Pareta's plan makes. See [Inference](./inference.md) for streaming and the full chat-completions surface. ## Zero-install alternative for inference You do not need this SDK to run inference at all. Because it's OpenAI-compatible, you can point the stock `openai` client at Pareta's `base_url` with the same `pareta_sk_` key and call `model="auto"` — there is nothing to set up first: **Python** ```python from openai import OpenAI client = OpenAI(api_key="pareta_sk_...", base_url="https://api.pareta.ai/v1") resp = client.chat.completions.create( model="auto", messages=[{"role": "user", "content": "What is the invoice number?"}], ) print(resp.choices[0].message.content) ``` **TypeScript** ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: "pareta_sk_...", baseURL: "https://api.pareta.ai/v1" }); const resp = await client.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "What is the invoice number?" }], }); console.log(resp.choices[0].message.content); ``` This is handy for inference-only workloads or dropping Pareta into an existing OpenAI codebase. The `pareta` SDK's distinct value is everything around that call that the OpenAI client cannot reach: benchmarking `"auto"` against frontier models on your own data and reading auto's metrics. ## Next steps - [Inference](./inference.md) — chat completions, streaming, and metering. - [Core concepts](./core-concepts.md) — tasks, `model="auto"`, and how requests are planned, routed, and billed. - [Evals](evaluation.md) — build eval sets and benchmark `"auto"` against frontier baselines. - [Errors & retries](errors-and-retries.md) — the typed exception hierarchy and retry policy. - [The `pareta` CLI](cli.md) — the same surface from your shell (`pip install "pareta[cli]"`). - [MCP server](mcp.md) — drive Pareta from an AI agent (Claude Code, Codex, Claude Desktop, Cursor) over MCP (`pip install "pareta[mcp]"`). - [The `/pareta` skill](skill.md) — a slash-command `SKILL.md` for Claude Code and Codex that drives the CLI. --- # Quickstart Pareta is one OpenAI-compatible endpoint with one model ID, `auto`, built for the tasks your application runs again and again. Send a request and Pareta selects the best-fit open-weight specialist when a deployed specialist holds the workload's quality bar, checks the result against that bar, and automatically escalates to a frontier model when the specialist path cannot meet it; when no deployed specialist holds the bar, a frontier model serves the request. You are billed once, for the model that produces the final response, and inference is metered against your org's balance. This page gets one production call working, then shows the pieces around it: streaming, metering, and benchmarking `auto` against frontier models on your own data. ## The 30-second version A support-ticket classifier: a fixed label set, one request per ticket, and `response_format` with a `json_schema` as the output contract. Pareta constrains decoding to the schema and validates the result before delivery, so `label` is one of yours — or the call fails with an error and is not billed (see [Structured outputs](inference.md#structured-outputs-response_format)). **Python** ```python import json from pareta import Pareta client = Pareta.from_env() # reads PARETA_API_KEY LABELS = ["billing", "refund", "login", "bug", "feature_request", "other"] TICKET_FORMAT = { # the output contract "type": "json_schema", "json_schema": { "name": "ticket_label", "schema": { "type": "object", "properties": {"label": {"type": "string", "enum": LABELS}}, "required": ["label"], "additionalProperties": False, }, }, } def classify(ticket: str) -> str: completion = client.chat.completions.create( model="auto", messages=[ {"role": "system", "content": "Classify the customer support ticket into exactly one label."}, {"role": "user", "content": ticket}, ], response_format=TICKET_FORMAT, ) return json.loads(completion.choices[0].message.content)["label"] print(classify("I was charged twice for my March invoice.")) # one of LABELS, e.g. "billing" ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const client = Pareta.fromEnv(); // reads PARETA_API_KEY const LABELS = ["billing", "refund", "login", "bug", "feature_request", "other"]; const TICKET_FORMAT = { // the output contract type: "json_schema", json_schema: { name: "ticket_label", schema: { type: "object", properties: { label: { type: "string", enum: LABELS } }, required: ["label"], additionalProperties: false, }, }, }; async function classify(ticket: string): Promise { const completion = await client.chat.completions.create({ model: "auto", messages: [ { role: "system", content: "Classify the customer support ticket into exactly one label." }, { role: "user", content: ticket }, ], response_format: TICKET_FORMAT, }); return JSON.parse(completion.choices[0].message.content ?? "{}").label; } console.log(await classify("I was charged twice for my March invoice.")); // one of LABELS, e.g. "billing" ``` That is the product. Everything below — benchmarking `auto` against frontier models on your own data and monitoring spend and estimated savings — exists to prove and operate that one call. Schema instructions written only in the prompt are not enforced; `response_format` with a `json_schema` is the contract. See [Structured outputs](inference.md#structured-outputs-response_format) for what is validated, JSON mode, and the limits. - **Prove it**: `client.evals` with `"auto"` among the candidates (see [Evaluation](evaluation.md)) — per-contender quality + cost on YOUR data. - **Watch it**: `client.auto.metrics()` — requests, success rate, spend, and estimated savings against frontier list prices. - **Compare it**: `client.auto.compare_frontier(...)` — one prompt against a frontier vendor, metered, for a side-by-side. The later sections on this page reuse `TICKET_FORMAT` from the example above. ## Install ```bash pip install pareta # or: uv add pareta / poetry add pareta ``` ## Authenticate Mint a `pareta_sk_` key in the dashboard (key management is browser-only) and export it. `Pareta.from_env()` reads `PARETA_API_KEY` (and an optional `PARETA_BASE_URL`). ```bash export PARETA_API_KEY="pareta_sk_..." ``` The SDK only ever consumes a key. It never creates, lists, or revokes them, and it never exposes your balance or payment methods. Topping up credit is browser-only. ## Find out how your data will be scored There is no model to pick and nothing to deploy — send any generation job to the model ID `auto`. The one lookup you'll ever do is for benchmarking: give `tasks.match` a plain-English description of your dataset and it tells you how an eval will score rows like yours: **Python** ```python from pareta import Pareta pa = Pareta.from_env() # reads PARETA_API_KEY m = pa.tasks.match("extract key fields from contracts") print(m.type) # "task" — a benchmarked task covers this if m.chosen: print(m.chosen.task_id) # e.g. "contract-key-fields" ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // reads PARETA_API_KEY const m = await pa.tasks.match("extract key fields from contracts"); console.log(m.matched); // true — a benchmarked task covers this console.log(m.chosen?.taskId); // e.g. "contract-key-fields" ``` `m.type` is one of four verdicts: `"task"` (a benchmarked task fits), `"capability"` (a general lane — chat, coding, vision, … — covers it), `"unsupported"` (Pareta does not cover this; a correct answer, not an error), or `"none"` (the router was unavailable and the lexical fallback found nothing confident). Whatever the verdict names, running the job is always the same call: `chat.completions.create(model="auto", ...)`. `pa.tasks.list()` and `pa.tasks.retrieve(task_id)` return the scoring definitions eval rows are validated against — see [tasks](../reference/tasks.md). ## Stream the response Pass `stream=True` to get an iterator of `ChatCompletionChunk`. The incremental text lives on `chunk.choices[0].delta.content` (it can be `None` on the first and last chunks, so guard it). Streaming is for free-text outputs such as the handoff summary below; a `response_format` response arrives as one validated chunk instead. **Python** ```python for chunk in pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Summarize this support ticket thread in two sentences for the agent handoff note:\n\n..."}], stream=True, ): print(chunk.choices[0].delta.content or "", end="", flush=True) print() ``` **TypeScript** ```typescript for await (const chunk of pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Summarize this support ticket thread in two sentences for the agent handoff note:\n\n..." }], stream: true, })) { process.stdout.write(chunk.choices[0].delta.content || ""); } console.log(); ``` Extra OpenAI parameters (`temperature`, `max_tokens`, `top_p`, and so on) pass straight through as keyword arguments. ## Cost and credit Every successful completion debits your org's balance — one debit per request, no matter how many internal model calls Pareta makes to serve it. If the balance is empty, the call raises `InsufficientCreditsError` (HTTP 402). Top-up is browser-only. **Python** ```python from pareta import InsufficientCreditsError try: resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "I was charged twice for my March invoice."}], response_format=TICKET_FORMAT, ) except InsufficientCreditsError: print("Out of credit — top up in the dashboard.") ``` **TypeScript** ```typescript import { InsufficientCreditsError } from "pareta"; try { const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "I was charged twice for my March invoice." }], response_format: TICKET_FORMAT, }); } catch (e) { if (e instanceof InsufficientCreditsError) { console.log("Out of credit — top up in the dashboard."); } else { throw e; } } ``` Evaluation runs are metered the same way (auto plus frontier compute). An `EvalRun` reports its billed total on `run.cost`, a `Decimal` in dollars floored to whole cents (so a sub-cent run reads `Decimal("0.00")`); the raw value is on `run.cost_micro_usd`. See [Evals](evaluation.md). ## Clean up There is nothing running on your account to stop — the serving fleet behind `auto` is Pareta's to operate. Cleanup is just closing the client (or using it as a context manager). **Python** ```python pa.close() ``` **TypeScript** ```typescript // No close() in TS: the client owns no connection (it uses the native fetch), // so there is nothing to release and no context-manager form to wrap it in. ``` **Python** ```python # Context-manager form closes the HTTP client for you. with Pareta.from_env() as pa: resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "I was charged twice for my March invoice."}], response_format=TICKET_FORMAT, ) ``` **TypeScript** ```typescript // No context manager in TS — just construct and use it; nothing to close. const pa = Pareta.fromEnv(); const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "I was charged twice for my March invoice." }], response_format: TICKET_FORMAT, }); ``` ## List what you can call `models.list()` returns the OpenAI-compatible model list. It has exactly one entry — `"auto"` — which is the point: the id you pass to `chat.completions.create(model=...)` is never a decision. **Python** ```python for m in pa.models.list(): print(m.id, m.owned_by) ``` **TypeScript** ```typescript for (const m of await pa.models.list()) { console.log(m.id, m.ownedBy); } ``` ## Async `AsyncPareta` mirrors the sync client; resource methods are `async def` and streams are async iterators. **Python** ```python import asyncio import json from pareta import AsyncPareta async def main(): async with AsyncPareta.from_env() as pa: resp = await pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "I was charged twice for my March invoice."}], response_format=TICKET_FORMAT, ) print(json.loads(resp.choices[0].message.content)["label"]) asyncio.run(main()) ``` **TypeScript** ```typescript // There is no AsyncPareta in TypeScript — the single `Pareta` client is already // async. Every I/O method returns a Promise (await it), and streams are async // iterables (`for await`). import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "I was charged twice for my March invoice." }], response_format: TICKET_FORMAT, }); console.log(JSON.parse(resp.choices[0].message.content ?? "{}").label); ``` ## Already using the OpenAI SDK? You do not need this SDK just to run inference. Use your Pareta API key, point the `openai` client at Pareta's base URL, and set the model ID to `auto`: **Python** ```python from openai import OpenAI client = OpenAI(api_key="pareta_sk_...", base_url="https://api.pareta.ai/v1") resp = client.chat.completions.create( model="auto", messages=[ {"role": "system", "content": "Classify the customer support ticket into exactly one label."}, {"role": "user", "content": "I was charged twice for my March invoice."}, ], response_format=TICKET_FORMAT, ) ``` **TypeScript** ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: "pareta_sk_...", baseURL: "https://api.pareta.ai/v1" }); const resp = await client.chat.completions.create({ model: "auto", messages: [ { role: "system", content: "Classify the customer support ticket into exactly one label." }, { role: "user", content: "I was charged twice for my March invoice." }, ], response_format: TICKET_FORMAT, }); ``` This SDK's unique value is everything around that call: benchmark `auto` on your own data (`evals`) and watch traffic and estimated savings (`auto.metrics()`) — from code. ## Next steps - [Core concepts](core-concepts.md) — the verified-inference path behind `auto`, the quality bar and escalation, how your data is scored, metering, and the eval → production funnel. - [Evals](evaluation.md) — benchmark `auto` against frontier baselines on your own data. - [Errors](errors-and-retries.md) — the `ParetaError` hierarchy and retry behavior. --- # Core concepts Pareta is one OpenAI-compatible endpoint with one model ID, **`auto`**, built for repeatable production workloads. This page covers the handful of ideas the rest of the SDK assumes you understand: the **verified-inference path behind `auto`** (how Pareta selects a specialist, checks the result against the workload's quality bar, and escalates), **one interface per data shape**, **tasks** (how evals score your data), **open-weight vs frontier** models, why **models** and **hardware** are hidden, how **metering** works, and the **funnel** that ties them together (prove `auto` on your data, ship it, watch the metrics). Every code block below is runnable as written. They all start from a client: **Python** ```python from pareta import Pareta pa = Pareta.from_env() # reads PARETA_API_KEY (+ optional PARETA_BASE_URL) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // reads PARETA_API_KEY (+ optional PARETA_BASE_URL) ``` `from_env()` is the path you want in almost every case. The explicit form is `Pareta(api_key="pareta_sk_...", base_url="https://api.pareta.ai")`; arguments are keyword-only. See [Authentication](installation.md) for key minting (browser-only) and [The client](../reference/client.md) for timeouts, retries, and the async `AsyncPareta` mirror. ## The verified-inference path behind `auto` Every request you send with the model ID `auto` takes the same path. Pareta **selects** the best-fit open-weight specialist for the workload (several are distilled in-house), **checks** the result against the workload's quality bar, and **automatically escalates** to a frontier model when the specialist path cannot meet it. When no deployed specialist holds the bar for a task, the request is served by a frontier model directly; a frontier-served response is returned as served. One request, one bill, for the model that produces the final response — routing, verification, retries, and non-serving attempts are included. "Checks" means output parsing and schema validation (including your `response_format`), constrained decoding where the task defines it, and model-graded checks on tasks where the specialist's measured quality calls for them. Verification is a quality gate, not a guarantee that an AI output can never be wrong. There is nothing to deploy and no model to pick — "which model?" is the question Pareta answers for you, per request. `models.list()` reflects that: it returns exactly one entry. **Python** ```python for m in pa.models.list(): print(m.id) # exactly one entry: "auto" ``` **TypeScript** ```typescript for (const m of await pa.models.list()) { console.log(m.id); // exactly one entry: "auto" } ``` Calling `auto` is plain chat — see [Inference is OpenAI-compatible](#inference-is-openai-compatible) below. The surfaces *around* that call live on `pa.auto`: - `auto.metrics()` — your org's `auto` traffic, rolled up: requests + success rate (30d), spend, hourly p50/p95/error buckets (7d), daily success cells (30d), and the estimated savings against frontier list prices. - `auto.compare_frontier(model=..., messages=...)` (TypeScript `auto.compareFrontier({ model, messages })`) — one prompt against a frontier vendor for a side-by-side with `"auto"`. Metered at the vendor's actual token cost; a failed vendor call bills $0. Allowed models: `gpt-5.5`, `gemini-3-5-flash`, `gemini-3-1-pro`, `claude-sonnet-4-6`. ## One interface per data shape You never choose a model anywhere on Pareta — you choose the **data shape**, and each shape has exactly one interface: | Your data | Interface | Behind it | |---|---|---| | messages in, text out | `chat.completions` with `model="auto"` | the verified-inference path behind `auto` | | a query + documents to rank | [`rerank`](../reference/rerank.md) | a Pareta reranking specialist | | text to turn into vectors | [`embeddings`](../reference/embeddings.md) | a Pareta open-weight embedding specialist | | audio in / audio out | [`audio`](../reference/audio.md) | the speech lanes | | a prompt to turn into an image | [`images`](../reference/images.md) | the image-generation lane | Within every shape, routing, model choice, and escalation are Pareta's job. The separate routes exist because vectors, ranked lists, images, and audio bytes don't fit the chat message contract — not because there is anything to navigate. Only the chat shape goes through `auto`'s route → verify → escalate loop and carries the `X-Pareta-*` receipt and diagnostics headers. Embeddings, reranking, images, and audio are **direct endpoints**: each is served by its own Pareta model at its own per-unit rate, outside that loop, and `auto` never routes a chat request to them. `model="auto"` belongs to `chat.completions` only — on the direct endpoints it has no meaning. ## Tasks: how evals score your data Internally, the quality bar behind `auto` comes from a catalog of benchmarked tasks — Pareta has measured open-weight and frontier models against each on real data. You don't navigate that catalog to use Pareta. You meet it in exactly one place: **benchmarking on your own data**, where a **task** says how your results are scored — the row shape your dataset must follow and the scorer that grades outputs against your labels. Every task has a stable `id` (e.g. `"contract-key-fields"`), a `default_scorer` (the function that grades a model's output — field-F1, nDCG@10, WER, judge panel), and a `has_blob_input` flag (true when the rows carry documents or images, not just text). **Python** ```python for task in pa.tasks.list(): print(task.id, task.default_scorer, "blob" if task.has_blob_input else "text") # Fetch one task, optionally with sample rows to see its input shape t = pa.tasks.retrieve("contract-key-fields", examples_n=3) print(t.id, t.default_scorer, t.has_blob_input) ``` **TypeScript** ```typescript for (const task of await pa.tasks.list()) { console.log(task.id, task.defaultScorer, task.hasBlobInput ? "blob" : "text"); } // Fetch one task, optionally with sample rows to see its input shape const t = await pa.tasks.retrieve("contract-key-fields", { examplesN: 3 }); console.log(t.id, t.defaultScorer, t.hasBlobInput); ``` Rather than reading the scorer list, describe your dataset in plain English and `tasks.match` tells you how it will be scored: **Python** ```python m = pa.tasks.match("vendor invoices with labeled line items and totals") if m.matched: print("grade with:", m.chosen.task_id) # the grading contract your eval will resolve to ``` **TypeScript** ```typescript const m = await pa.tasks.match("vendor invoices with labeled line items and totals"); if (m.matched && m.chosen) { console.log("grade with:", m.chosen.taskId); } ``` `match()` raises `ValueError` on an empty query. A no-match answer is a statement about *scoring* — no benchmarked task fits that description — not about serving: generation work always goes to `model="auto"`. See [Tasks](../reference/tasks.md) for the full matcher surface. ## Open-weight vs frontier models Two kinds of model stand behind every task: - **Open-weight** models are Pareta's specialists — the models `auto` selects between, including several distilled in-house. Pareta benchmarks them, serves them, and picks between them — you never call one directly or learn its identity. - **Frontier** models are hosted vendor models (OpenAI, Google, Anthropic, and so on). They play two roles: the model `auto` escalates to when the specialist path cannot meet the workload's quality bar (or serves directly when no deployed specialist holds the bar), and the **baseline** you measure `auto` against in evals. An eval shows, on *your* rows, whether `auto` meets the bar the frontier baseline sets, and what each contender costs. Frontier (vendor) ids appear in the clear — those are public products — in exactly two places: eval baselines and `auto.compare_frontier()`. To enumerate the frontier roster you can evaluate against (annotated for your eval set's bound grading contract via `task=eval_set.task_id`), use `evals.frontier_models`: **Python** ```python for fm in pa.evals.frontier_models(task=eval_set.task_id): print(fm.id, fm.vendor, "vision" if fm.vision else "text", "(benchmarked)" if fm.benchmarked else "") ``` **TypeScript** ```typescript for (const fm of await pa.evals.frontierModels("contract-key-fields")) { console.log(fm.id, fm.vendor, fm.vision ? "vision" : "text", fm.benchmarked ? "(benchmarked)" : ""); } ``` Passing `task=` annotates each model's `benchmarked` flag (measured on that task) and filters the roster by capability (for example, only vision-capable models are returned for document tasks). Feed the `id` values into an eval run's `frontier=` list. ## Models are hidden You never pick a model, and open-weight identities never cross the API. The only model id you send is `"auto"`; the only model ids you read back are `"auto"` and frontier vendor ids in eval and comparison results (`result.model_id`). This is a feature, not an omission. There are no open-model ids to look up, hard-code, or keep current — when Pareta promotes a better specialist behind a task, your requests get it on the next call, with no code change and no migration. ## Hardware is hidden You never choose a GPU, tensor-parallel degree, quantization scheme, or serving mode. The specialists behind `"auto"` run on serving classes Pareta resolves from its registry, and capacity — warm pools, autoscaling, cold starts — is Pareta's problem. The one place serving infrastructure surfaces in the SDK is `EndpointNotReadyError` (503): a serving backend behind auto is warming or briefly unavailable. The SDK retries 503s automatically, so you rarely see it. ## Inference is OpenAI-compatible Call `auto` through `chat.completions.create` with `model="auto"`. The request and response match the OpenAI chat schema, so the official `openai` client works against the same base URL and key. **Python** ```python resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Extract the contract effective date."}], temperature=0, # extra OpenAI params pass straight through ) print(resp.choices[0].message.content) print(resp.usage.total_tokens) ``` **TypeScript** ```typescript const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Extract the contract effective date." }], temperature: 0, // extra OpenAI params pass straight through }); console.log(resp.choices[0].message.content); console.log(resp.usage.totalTokens); ``` Streaming yields `ChatCompletionChunk` objects; the incremental text is on `chunk.choices[0].delta.content`: **Python** ```python for chunk in pa.chat.completions.create(model="auto", messages=[...], stream=True): print(chunk.choices[0].delta.content or "", end="") ``` **TypeScript** ```typescript for await (const chunk of pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Summarize this support ticket thread in two sentences:\n\n..." }], stream: true })) { process.stdout.write(chunk.choices[0].delta.content || ""); } ``` `create()` raises `ValueError` up front if `model` or `messages` is empty. See [Running inference](./inference.md) for streaming details and the async iterator form. ## Metering and billing Both inference and evals are **metered against your organization's balance**. - **Inference:** a successful `chat.completions.create()` debits the org balance **once per request**, for the model that produces the final response — no matter how many internal model calls Pareta makes to serve it. Routing, verification, retries, and non-serving attempts are included. - **Speech:** the `pa.audio` namespace (`pa.audio.transcriptions(...)`, `pa.audio.speech(...)`, Python-only) is billed **per minute** of audio — see [Audio](../reference/audio.md). - **Evals:** `evals.runs.create()` debits for the compute it spends: `"auto"` and any frontier baselines you include. A FAILED run is not charged. - **Frontier comparisons:** `auto.compare_frontier()` is metered at the vendor's actual token cost; a failed vendor call bills $0. - **Empty balance:** every path raises `InsufficientCreditsError` (HTTP 402). **Python** ```python from pareta import InsufficientCreditsError try: resp = pa.chat.completions.create(model="auto", messages=[{"role": "user", "content": "Extract the contract effective date."}]) except InsufficientCreditsError: print("Top up the org balance in the dashboard, then retry.") ``` **TypeScript** ```typescript import { InsufficientCreditsError } from "pareta"; try { const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Extract the contract effective date." }] }); } catch (e) { if (e instanceof InsufficientCreditsError) { console.log("Top up the org balance in the dashboard, then retry."); } else { throw e; } } ``` Topping up is **browser-only**. The SDK never exposes the balance, payment methods, or top-up. It only consumes credit and surfaces the 402 when there is none. ### Reading cost off an eval run An eval run reports what it cost. The SDK follows one money convention (`SDK_PLAN` §6): the **billed total is floored to whole cents** so the SDK never overstates a charge, while sub-cent precision stays available in micro-USD. - `run.cost` is a `Decimal` in dollars, floored to cents. A 5 µUSD run reads `Decimal("0.00")`. - `run.cost_micro_usd` is the raw integer (`1_000_000` = `$1.00`). - Per-item unit rates such as `result.mean_cost_micro_usd` stay in **micro-USD**. Flooring them to cents would erase the auto-vs-frontier comparison that is the whole point. **Python** ```python print(run.cost) # Decimal("0.42"): billed dollars, floored to cents print(run.cost_micro_usd) # 420715: raw micro-USD ``` **TypeScript** ```typescript console.log(run.cost); // "0.42": billed dollars (string), floored to cents console.log(run.costMicroUsd); // 420715: raw micro-USD ``` ## The proof funnel The pieces above compose into one path from "I have a job" to "auto is running it in production, cheaper." This is the recommended flow: ``` eval on YOUR data -> model="auto" in production -> watch the metrics ``` 1. **Eval** `"auto"` against frontier baselines on *your own* data. Public benchmarks are a starting point; your rows are the deciding vote. 2. **Ship** `model="auto"` — the same call, now carrying production traffic. 3. **Watch** `auto.metrics()` — requests, success rate, spend, estimated savings against frontier list prices. **Python** ```python from pareta import Pareta pa = Pareta.from_env() # 1. Evaluate "auto" against frontier baselines on YOUR rows. # Pass items + prompt to create the eval set inline — Pareta works out # the scoring from them — or use an existing set id. run = pa.evals.runs.create( prompt="extract the effective date from each contract", items=[ {"input": {"contract_text": "...your contract text..."}, "expected_output": {"effective_date": "2026-01-01"}}, # ...more rows... ], models=["auto"], frontier="benchmarked", # the benchmarked frontier baselines wait=True, # block until the run is terminal ) # 2. Read results (quality + cost), then ship the same call to production for r in sorted(run.results, key=lambda r: (r.quality_mean or 0), reverse=True): print(r.model_id, r.kind, r.quality_mean, r.mean_cost_micro_usd, f"n={r.n_succeeded}") print("eval cost:", run.cost) # Decimal dollars, floored to cents resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "...your contract text..."}], ) # 3. Watch it in production m = pa.auto.metrics() print(m["requests_30d"], m["success_rate_30d"], m["savings_vs_frontier_micro_usd_30d"]) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // 1. Evaluate "auto" against frontier baselines on YOUR rows. // Pass items + prompt to create the eval set inline — Pareta works out // the scoring from them — or use an existing set id. const run = await pa.evals.runs.create({ prompt: "extract the effective date from each contract", items: [ { input: { contract_text: "...your contract text..." }, expected_output: { effective_date: "2026-01-01" } }, // ...more rows... ], models: ["auto"], frontier: "benchmarked", // the benchmarked frontier baselines wait: true, // block until the run is terminal }); // 2. Read results (quality + cost), then ship the same call to production for (const r of [...run.results].sort((a, b) => (b.qualityMean ?? 0) - (a.qualityMean ?? 0))) { console.log(r.modelId, r.kind, r.qualityMean, r.meanCostMicroUsd, `n=${r.nSucceeded}`); } console.log("eval cost:", run.cost); // dollar string, floored to cents const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "...your contract text..." }], }); // 3. Watch it in production const m = await pa.auto.metrics(); console.log(m.requests_30d, m.success_rate_30d, m.savings_vs_frontier_micro_usd_30d); ``` A few notes on the eval call: - Provide **either** `eval_set=` (an existing set) **or** `items=... + prompt=...` to create one inline (`task=` is optional — pass it to pin a specific task). With neither, `create()` raises `ValueError`. - `frontier=` accepts `None`/`"none"` (no baselines), an explicit list of frontier ids, `"all"` (every frontier model for the task), or `"benchmarked"` (only the frontier models measured on this task, vision-filtered for document tasks). Keyword resolution needs to know the task; with `eval_set=`, the SDK looks the task up for you. - `wait=True` polls until the run reaches `"completed"` or `"failed"` (`run.is_terminal`), then returns the final `EvalRun`. For document tasks, attach binaries with `evals.sets.upload_document(...)` before running. For the full eval API (building sets, attaching documents, inline vs. existing sets, and polling semantics) see [Evaluating models](evaluation.md). For the catalog and matcher surface in depth, see [Tasks](../reference/tasks.md). ## Errors at a glance Every SDK error subclasses `ParetaError`. The status-mapped subclasses let you branch on what went wrong without inspecting status codes: | Exception | Status | When | |---|---|---| | `AuthenticationError` | 401 | bad or missing key | | `InsufficientCreditsError` | 402 | org out of credit (top up in the dashboard) | | `PermissionDeniedError` | 403 | the user lacks permission | | `NotFoundError` | 404 | unknown task or run | | `ConflictError` | 409 | transient contention (auto-retried) | | `RateLimitError` | 429 | throttled (auto-retried) | | `EndpointNotReadyError` | 503 | a serving backend behind auto is warming or briefly unavailable (auto-retried) | | `BadRequestError` | 400/422 | malformed request | | `APIConnectionError` / `APITimeoutError` | n/a | transport failure (auto-retried) | **Python** ```python import pareta try: resp = pa.chat.completions.create(model="auto", messages=[{"role": "user", "content": "Extract the contract effective date."}]) except pareta.EndpointNotReadyError: print("A backend is warming; retries are exhausted — try again shortly.") except pareta.InsufficientCreditsError: print("Out of credit. Top up in the dashboard.") except pareta.ParetaError as e: print("request failed:", e) ``` **TypeScript** ```typescript import { EndpointNotReadyError, InsufficientCreditsError, ParetaError } from "pareta"; try { const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Extract the contract effective date." }] }); } catch (e) { if (e instanceof EndpointNotReadyError) { console.log("A backend is warming; retries are exhausted — try again shortly."); } else if (e instanceof InsufficientCreditsError) { console.log("Out of credit. Top up in the dashboard."); } else if (e instanceof ParetaError) { console.log("request failed:", e); } else { throw e; } } ``` See [Error handling](errors-and-retries.md) for the full hierarchy, the `request_id` attribute for support, and the retry policy. --- # Running inference You run inference through `chat.completions.create`, which has the same shape as the OpenAI chat completions API. Pass `model="auto"`, a list of messages, and you get a `ChatCompletion` back. Set `stream=True` and you get an iterator of token deltas instead. Pareta is OpenAI-compatible on the wire, so you can run inference with this SDK, with the `openai` package, or with raw HTTP, whichever fits your stack. This SDK's extra value is the control plane (evals on your own data, auto metrics); for plain inference the two are interchangeable. A few platform truths that shape this page: - **There is no model to pick.** `model` is the literal string `"auto"`; Pareta selects the best-fit specialist behind it. Real open-weight model ids never reach you; the backend resolves them. You never pick a GPU. - **Inference is metered against your org balance.** A successful completion debits your balance — one debit per request, for the model that produces the final response, no matter how many internal model calls Pareta makes to serve it. If the balance is empty, the call raises `InsufficientCreditsError` (402). Top-up is browser-only; the SDK has no balance or payment surface. ## The model ID `auto` The model id for every request is the literal string `"auto"`. Pareta selects the best-fit open-weight specialist for the workload, checks the result against the workload's quality bar — output parsing and schema validation (including your `response_format`), constrained decoding where the task defines it, and model-graded checks on tasks configured for them — and automatically escalates to a frontier model when the specialist path cannot meet the bar. A task with no deployed specialist that holds the bar is served by a frontier model directly, and a frontier-served response is returned as served. Verification is a quality gate, not a guarantee that an AI output can never be wrong. One request, one debit, for the model that produces the final response; routing, verification, retries, and non-serving attempts are included, and a request that errors out bills $0. Streaming works the same way — the answer streams token by token, and the SSE stream carries `: pareta-progress ` comments (`planning` / `executing` / `answering`) you can surface as status. ```python completion = client.chat.completions.create( model="auto", messages=[{"role": "user", "content": "…"}], ) ``` Everything below — setup, streaming, async, errors — is that one call in different shapes. ## Setup Mint a `pareta_sk_` key in the dashboard, export it, and build the client from the environment: ```bash export PARETA_API_KEY=pareta_sk_... ``` **Python** ```python from pareta import Pareta pa = Pareta.from_env() # reads PARETA_API_KEY (+ optional PARETA_BASE_URL) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // reads PARETA_API_KEY (+ optional PARETA_BASE_URL) ``` `from_env()` is the recommended path. You can also pass the key explicitly: `Pareta(api_key="pareta_sk_...")`. The client is a context manager, so `with Pareta.from_env() as pa:` cleans up the HTTP connection for you. ## A basic completion Pass `model="auto"` and a non-empty `messages` list in OpenAI format. You get back a `ChatCompletion`. **Python** ```python from pareta import Pareta with Pareta.from_env() as pa: resp = pa.chat.completions.create( model="auto", # the only model id messages=[ {"role": "system", "content": "You extract structured fields from documents."}, {"role": "user", "content": "What is the invoice total?\n\nINVOICE\nTotal due: $4,210.00"}, ], ) print(resp.choices[0].message.content) print(resp.usage.total_tokens, "tokens") ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); const resp = await pa.chat.completions.create({ model: "auto", // the only model id messages: [ { role: "system", content: "You extract structured fields from documents." }, { role: "user", content: "What is the invoice total?\n\nINVOICE\nTotal due: $4,210.00" }, ], }); console.log(resp.choices[0].message.content); console.log(resp.usage.totalTokens, "tokens"); ``` `model` and `messages` are both required. The SDK raises `ValueError` before sending if `model` is falsy or `messages` is empty, so a malformed call fails fast without burning a request. ## The ChatCompletion shape `create()` returns a `ChatCompletion`. The fields mirror OpenAI: **Python** ```python resp.id # str | None resp.model # str | None: echoes "auto" resp.created # int | None: Unix timestamp resp.choices # list[Choice] resp.choices[0].index # int | None resp.choices[0].finish_reason # "stop", "length", ... resp.choices[0].message.role # "assistant" resp.choices[0].message.content # str | None: the generated text resp.usage.prompt_tokens # int | None resp.usage.completion_tokens # int | None resp.usage.total_tokens # int | None ``` **TypeScript** ```typescript resp.id // string | null resp.model // string | null: echoes "auto" resp.created // number | null: Unix timestamp resp.choices // Choice[] resp.choices[0].index // number | null resp.choices[0].finishReason // "stop", "length", ... resp.choices[0].message.role // "assistant" resp.choices[0].message.content // string | null: the generated text resp.usage.promptTokens // number | null resp.usage.completionTokens // number | null resp.usage.totalTokens // number | null ``` Every response object keeps the raw server JSON. If a field isn't surfaced as a typed property, reach it with `resp.to_dict()` or `resp["..."]`. Nothing the API returns is lost behind the typed layer. ## Passthrough parameters Any extra keyword you pass goes straight into the request body, so the full OpenAI parameter set is available without the SDK enumerating it: **Python** ```python resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Summarize this contract clause: ..."}], temperature=0.2, max_tokens=512, top_p=0.9, ) ``` **TypeScript** ```typescript const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Summarize this contract clause: ..." }], temperature: 0.2, max_tokens: 512, top_p: 0.9, }); ``` `temperature`, `max_tokens`, `top_p`, `stop`, `seed`, and friends all pass through unchanged. `max_tokens` (or `max_completion_tokens`) is a hard cap on the answer, and a lower value is always honored exactly. Without one, Pareta sizes the budget to the request, up to 4,096 tokens for an open-ended text answer. If you expect a longer answer, such as a long report or a full-file rewrite, send a larger `max_tokens`: it raises the budget to as much as 8,192 tokens on Pareta-hosted models (less when the input itself nearly fills the model's context). Structured outputs (`response_format`) get a larger budget of their own. An answer that runs out of budget ends with `finish_reason: "length"`, so check it before treating a long answer as complete. ## Structured outputs (`response_format`) `auto` supports OpenAI Structured Outputs: pass a `response_format` and the response `content` is a single JSON document that conforms to your schema, however the request was served. Pareta enforces the schema with constrained decoding on its own specialists, validates every answer against your schema before delivery, and escalates automatically when an answer doesn't conform. If no conformant answer can be produced at all, the request fails with an error and you are not billed — nonconformant JSON is never delivered. Schema instructions written only in the prompt ("reply with JSON matching …") are **not** enforced by specialists; `response_format` with a `json_schema` is the contract, and it is what constrains decoding. Send it on every request whose output your code parses. **Python** ```python resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Classify: 'refund my order'"}], response_format={ "type": "json_schema", "json_schema": { "name": "intent", "schema": { "type": "object", "properties": { "label": {"type": "string", "enum": ["refund", "billing", "other"]}, "confidence": {"type": "number"}, }, "required": ["label"], "additionalProperties": False, }, }, }, ) data = json.loads(resp.choices[0].message.content) # parses: validated against the schema before delivery ``` **TypeScript** ```typescript const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Classify: 'refund my order'" }], response_format: { type: "json_schema", json_schema: { name: "intent", schema: { type: "object", properties: { label: { type: "string", enum: ["refund", "billing", "other"] }, confidence: { type: "number" }, }, required: ["label"], additionalProperties: false, }, }, }, }); ``` `{"type": "json_object"}` (JSON mode) is also supported: the content is guaranteed to parse as JSON, with no schema check. A malformed `response_format` returns a 400 with a specific message — it is never silently ignored. Notes: - Nested objects, arrays, `enum`, `required`, and `additionalProperties: false` are all enforced. Schemas do **not** need to satisfy OpenAI's strict-mode restrictions (optional fields are fine). - The root schema must declare `"type": "object"` (same as OpenAI). Local `$ref`/`$defs` are supported; external `$ref` URLs are rejected with a 400. Schemas are capped at 50KB. - The `format` keyword (`date-time`, `email`, …) is **not** enforced — matching OpenAI, which also ignores `format` in structured outputs. Use `pattern` or `enum` when the shape matters. - With `response_format` set, `temperature` is not applied (structured serving runs at its canonical settings), and streamed responses deliver the JSON as a single buffered chunk after validation rather than token-by-token. - Clarifying questions are suppressed: a structured request always answers with schema-conformant JSON, never a prose question. ## Tool calling (`tools`) `model="auto"` supports OpenAI-compatible function calling. Pass a `tools` array and the response comes back with `tool_calls` whose `arguments` are valid JSON for the schema you declared. Pareta serves tool turns on open models trained for tool use, and escalates when the turn needs more capability than they have. You drive the loop. One request is one turn: Pareta returns either a final message or the tool calls it wants made. You execute them, append the results as `role: "tool"` messages, and call again. **Python** ```python tools = [{ "type": "function", "function": { "name": "get_stock_price", "description": "Get the current trading price for a ticker symbol.", "parameters": { "type": "object", "properties": {"symbol": {"type": "string"}}, "required": ["symbol"], }, }, }] messages = [{"role": "user", "content": "What is NVDA trading at?"}] resp = pa.chat.completions.create(model="auto", messages=messages, tools=tools) call = resp.choices[0].message.tool_calls[0] args = json.loads(call.function.arguments) # parses, guaranteed result = get_stock_price(**args) # your function messages += [ {"role": "assistant", "tool_calls": resp.choices[0].message.tool_calls}, {"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)}, ] final = pa.chat.completions.create(model="auto", messages=messages, tools=tools) print(final.choices[0].message.content) ``` **TypeScript** ```typescript const tools = [{ type: "function", function: { name: "get_stock_price", description: "Get the current trading price for a ticker symbol.", parameters: { type: "object", properties: { symbol: { type: "string" } }, required: ["symbol"], }, }, }]; let messages = [{ role: "user", content: "What is NVDA trading at?" }]; const resp = await pa.chat.completions.create({ model: "auto", messages, tools }); const call = resp.choices[0].message.tool_calls[0]; const args = JSON.parse(call.function.arguments); const result = await getStockPrice(args.symbol); messages = [ ...messages, { role: "assistant", tool_calls: resp.choices[0].message.tool_calls }, { role: "tool", tool_call_id: call.id, content: JSON.stringify(result) }, ]; const final = await pa.chat.completions.create({ model: "auto", messages, tools }); ``` `tool_choice` works as it does on OpenAI: `"auto"` (the default) lets the model decide, `"required"` forces some tool call, `"none"` forbids them, and `{"type": "function", "function": {"name": "..."}}` forces a specific one. `parallel_tool_calls` is passed through. Notes: - `tools` and `response_format` cannot be combined — the request returns a 400. The two guarantees are enforced by different machinery, and accepting both would silently drop the schema guarantee rather than honor it. - `stream=True` with `tools` returns a 400 today. Retry without it. - `n > 1` returns a 400. - If the serving model has been idle and is cold, the turn waits for it to start (this can take several minutes) and is answered by the frontier tier if it doesn't come up in time. Use a client timeout of at least 10 minutes, and send an `Idempotency-Key` header so an automatic client retry never bills the same turn twice: a retry with the same key and body gets the first attempt's response back (waiting for it if it is still running) instead of running the turn again ([details](../reference/http-api.md#idempotency-key)). A `503` with a `Retry-After` header means the serving model could not be reached at all; retry the call. - Billing is per turn, at the same rates as any other `auto` request: a turn answered by Pareta's open models bills at the published per-token rates, and a turn escalated to the frontier tier bills at that provider's list price. Every response carries the usual `X-Pareta-Billed` (exact debit) and `X-Pareta-Frontier-Would-Have-Cost` (estimated) headers plus the route diagnostics (`X-Pareta-Served-By`, `X-Pareta-Escalated`, `X-Pareta-Specialist`, `X-Pareta-Route-Version`), so a multi-turn tool loop shows its cost and its route turn by turn. ## Streaming Set `stream=True` and `create()` returns an iterator of `ChatCompletionChunk` objects instead of a single `ChatCompletion`. Each chunk carries a `delta` (not a `message`); the incremental text is at `chunk.choices[0].delta.content`. **Python** ```python with Pareta.from_env() as pa: stream = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Summarize this support ticket thread in two sentences for the agent handoff note:\n\n..."}], stream=True, ) for chunk in stream: print(chunk.choices[0].delta.content or "", end="", flush=True) print() ``` **TypeScript** ```typescript const pa = Pareta.fromEnv(); const stream = pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Summarize this support ticket thread in two sentences for the agent handoff note:\n\n..." }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0].delta.content || ""); } console.log(); ``` `ChatCompletionChunk` has the same schema as `ChatCompletion`; it exists as a distinct type only for hinting. Guard `delta.content` with `or ""`: the first and last chunks of a stream often carry role or finish metadata with no text. The stream is data-only SSE and always terminates on a `[DONE]` sentinel, which the SDK consumes for you, so the iterator simply ends. Note that retries only cover the initial handshake. Once tokens are flowing, a mid-stream drop raises immediately rather than silently resuming. ## Async `AsyncPareta` mirrors the sync client. Methods are `async def`; for streaming you `await` the call once, then `async for` over the chunks. **Python** ```python import asyncio from pareta import AsyncPareta async def main(): async with AsyncPareta.from_env() as pa: # Non-streaming resp = await pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "What is the invoice total?"}], ) print(resp.choices[0].message.content) # Streaming stream = await pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Summarize this support ticket thread in two sentences for the agent handoff note:\n\n..."}], stream=True, ) async for chunk in stream: print(chunk.choices[0].delta.content or "", end="", flush=True) print() asyncio.run(main()) ``` **TypeScript** ```typescript // There is no AsyncPareta in TypeScript — the one Pareta client is already // Promise-only. Every I/O method returns a Promise you `await`; streaming // returns an AsyncIterable you drive with `for await`. import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // Non-streaming const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "What is the invoice total?" }], }); console.log(resp.choices[0].message.content); // Streaming const stream = pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Summarize this support ticket thread in two sentences for the agent handoff note:\n\n..." }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0].delta.content || ""); } console.log(); ``` ## Reading the cost of a request Every completion tells you what it cost without any SDK: the `X-Pareta-Billed` response header is the exact debit in micro-USD, and `X-Pareta-Frontier-Would-Have-Cost` is an **estimate** of what a single frontier call on the same prompt would have cost (usage tokens × frontier list price). The difference is your estimated per-request savings. Streamed responses deliver the same two numbers as SSE comment lines just before `[DONE]`. See the [HTTP API reference](../reference/http-api.md) for details. ## Handling metering and not-ready errors Two error cases are specific to running inference. Both subclass `ParetaError`, so a single `except ParetaError` is a fine catch-all; the specific classes let you branch. **Python** ```python from pareta import ( Pareta, InsufficientCreditsError, # 402: org balance empty EndpointNotReadyError, # 503: a serving backend is warming / briefly unavailable ) with Pareta.from_env() as pa: try: resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "What is the invoice total?\n\nINVOICE\nTotal due: $4,210.00"}], ) print(resp.choices[0].message.content) except InsufficientCreditsError: # Balance hit zero. Top up in the dashboard (billing is browser-only); # the SDK exposes no balance or payment surface. print("Out of credit. Top up in the dashboard, then retry.") except EndpointNotReadyError: # A serving backend behind auto is warming. The SDK already retried # the 503 with backoff; wait briefly and retry the call. print("Backend warming — retry shortly.") ``` **TypeScript** ```typescript import { Pareta, InsufficientCreditsError, // 402: org balance empty EndpointNotReadyError, // 503: a serving backend is warming / briefly unavailable } from "pareta"; const pa = Pareta.fromEnv(); try { const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "What is the invoice total?\n\nINVOICE\nTotal due: $4,210.00" }], }); console.log(resp.choices[0].message.content); } catch (e) { if (e instanceof InsufficientCreditsError) { // Balance hit zero. Top up in the dashboard (billing is browser-only); // the SDK exposes no balance or payment surface. console.log("Out of credit. Top up in the dashboard, then retry."); } else if (e instanceof EndpointNotReadyError) { // A serving backend behind auto is warming. The SDK already retried // the 503 with backoff; wait briefly and retry the call. console.log("Backend warming — retry shortly."); } else { throw e; } } ``` Transient failures (429 rate limits, 5xx, connection timeouts) are retried automatically with exponential backoff, `max_retries` times (default 2). You only see `RateLimitError` or `APITimeoutError` after retries are exhausted. See [Errors](errors-and-retries.md) for the full hierarchy. ## Using the OpenAI SDK instead Because Pareta is one OpenAI-compatible endpoint, you don't need this SDK to *call* it. Use your Pareta API key, point the OpenAI client at Pareta's base URL, and set the model ID to `auto`. Note the `/v1` suffix the OpenAI client expects: **Python** ```python from openai import OpenAI client = OpenAI(api_key="pareta_sk_...", base_url="https://api.pareta.ai/v1") resp = client.chat.completions.create( model="auto", messages=[{"role": "user", "content": "What is the invoice total?"}], ) print(resp.choices[0].message.content) ``` **TypeScript** ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: "pareta_sk_...", baseURL: "https://api.pareta.ai/v1" }); const resp = await client.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "What is the invoice total?" }], }); console.log(resp.choices[0].message.content); ``` Tooling that discovers model ids by listing keeps working too: `models.list()` (`GET /v1/models`) returns exactly one entry, `"auto"` — there is only one model id to call. Field details in the [models reference](../reference/models.md). Streaming, `temperature`, `max_tokens`, `response_format`, and `tools` behave as described on this page; the sections above state what is supported and what returns a 400, and the [HTTP API reference](../reference/http-api.md) covers the rest of the route map. Metering still applies: a zero balance returns a 402, which the `openai` client surfaces as its own status error. Reach for the Pareta SDK when you want typed errors and the control plane: [running evals](evaluation.md) on your own data and reading auto's metrics ([core concepts](core-concepts.md)). --- # Evaluating on your own data Benchmarks tell you which model wins on someone else's data. This page is about the only number that matters: how `model="auto"` scores on *your* rows. Upload your data and say what you want done with each item — one sentence, like a prompt. Pareta works out how to score the results and shows you before anything runs. Then it runs `"auto"` and the frontier baselines you name on the same items and returns per-contender quality with confidence intervals and cost. No GPUs to size, no scorer to wire up, no judge to host. An eval set is your rows plus that one sentence (the `prompt` parameter) — required, because the same rows can mean different jobs and only you know which. Each row is a JSON object with two keys, both JSON objects themselves: `{"input": {...}, "expected_output": {...}}` — the input the model sees and the gold answer the scorer grades against. Everything about scoring is derived from your words and your data; there is nothing to configure. The shape is always the same: 1. Upload your rows + say what you want done (`evals.sets.create`). 2. Kick off an **eval run** with `"auto"` as the candidate and frontier baselines to beat (`evals.runs.create`), optionally waiting for it to finish. 3. Read `run.results` to compare quality and cost; read `run.cost` for the bill. ## Benchmark Pareta itself: `"auto"` as a contender The candidate is the literal string `"auto"`, and the eval runs Pareta's verified-inference path behind `auto` against every item — the same planning, routing, and verification that serves your production traffic, scored by the same scorer as the baselines. The per-contender result rows (quality mean + CI, mean cost per item) are the product's core claim, measured on your data: ```python run = client.evals.runs.create( eval_set=my_set, models=["auto"], # the contender: the verified-inference path behind `auto` frontier=["gpt-5.5"], # the frontier baseline to beat ) ``` A completed run's rows let you read the verdict directly: overlapping quality CIs at lower cost = meets the frontier baseline's bar; higher mean without overlap = ahead. Auto's failures count as errors (not skips) — availability is part of what a benchmark should measure. ## A complete run, top to bottom **Python** ```python from pareta import Pareta pa = Pareta.from_env() # reads PARETA_API_KEY (and optional PARETA_BASE_URL) run = pa.evals.runs.create( prompt="extract the effective and termination dates from each contract", items=[ {"input": {"contract_text": "Effective as of January 1, 2026, ..."}, "expected_output": {"effective_date": "2026-01-01"}}, {"input": {"contract_text": "This Agreement terminates on 2027-12-31 ..."}, "expected_output": {"termination_date": "2027-12-31"}}, ], models=["auto"], # the contender frontier="benchmarked", # baselines already benchmarked on this task wait=True, # block until the run is terminal ) print(run.status) # "completed" print(f"billed ${run.cost}") # Decimal dollars, floored to cents for r in run.results: print(f"{r.model_id:16} {(r.kind or ''):8} q={r.quality_mean:.3f} " f"[{r.quality_ci_low:.3f}, {r.quality_ci_high:.3f}] " f"~{r.mean_cost_micro_usd} uUSD/item " f"({r.n_succeeded} ok, {r.error_count} err)") ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // reads PARETA_API_KEY (and optional PARETA_BASE_URL) const run = await pa.evals.runs.create({ prompt: "extract the effective and termination dates from each contract", items: [ { input: { contract_text: "Effective as of January 1, 2026, ..." }, expected_output: { effective_date: "2026-01-01" } }, { input: { contract_text: "This Agreement terminates on 2027-12-31 ..." }, expected_output: { termination_date: "2027-12-31" } }, ], models: ["auto"], // the contender frontier: "benchmarked", // baselines already benchmarked on this task wait: true, // block until the run is terminal }); console.log(run.status); // "completed" console.log(`billed $${run.cost}`); // dollar string, floored to cents for (const r of run.results) { console.log( `${r.modelId} ${r.kind ?? ""} q=${r.qualityMean} ` + `[${r.qualityCiLow}, ${r.qualityCiHigh}] ` + `~${r.meanCostMicroUsd} uUSD/item ` + `(${r.nSucceeded} ok, ${r.errorCount} err)`, ); } ``` That single call created the eval set inline, started the run, polled it to completion, and returned aggregates per contender. Everything below unpacks the pieces so you can vary them. `models=` is always `["auto"]` — individual open-weights models are not part of the eval surface; they stay behind auto's routing. Frontier (vendor) ids are in the clear, and `frontier=` chooses which of them get scored alongside. ## Step 1: build an eval set An eval set is your rows plus what you want done with them. Create one explicitly when you want to reuse it across several runs: **Python** ```python eval_set = pa.evals.sets.create( prompt="extract the effective and termination dates from each contract", items=[ {"input": {"contract_text": "Effective as of January 1, 2026, ..."}, "expected_output": {"effective_date": "2026-01-01"}}, {"input": {"contract_text": "This Agreement terminates on 2027-12-31 ..."}, "expected_output": {"termination_date": "2027-12-31"}}, ], name="Q2 contracts sample", # optional; defaults to "sdk eval set (N items)" ) print(eval_set.id) # pass this to runs.create(eval_set=...) print(eval_set.scoring_strategy) # how it will be scored print(eval_set.prompt) # what you asked for, stored on the set print(eval_set.item_count) # 2 ``` **TypeScript** ```typescript const evalSet = await pa.evals.sets.create({ prompt: "extract the effective and termination dates from each contract", items: [ { input: { contract_text: "Effective as of January 1, 2026, ..." }, expected_output: { effective_date: "2026-01-01" } }, { input: { contract_text: "This Agreement terminates on 2027-12-31 ..." }, expected_output: { termination_date: "2027-12-31" } }, ], name: "Q2 contracts sample", // optional; defaults to "sdk eval set (N items)" }); console.log(evalSet.id); // pass this to runs.create({ evalSet: ... }) console.log(evalSet.scoringStrategy); // how it will be scored console.log(evalSet.prompt); // what you asked for, stored on the set console.log(evalSet.itemCount); // 2 ``` `prompt` and `items` are both required (the SDK raises if either is missing or empty). If what you asked for doesn't line up with what's in the data — you asked for summaries but the rows look like classification labels — `create` refuses with suggestions instead of guessing. (`task=` exists to pin a specific scoring setup; most callers never need it.) ### Preview the scoring first: `propose_contract` To see how a set will be scored before creating anything, call `propose_contract`. It's stateless (nothing is persisted): **Python** ```python proposal = pa.evals.propose_contract( prompt="extract the effective and termination dates from each contract", items=[{"input": {"contract_text": "..."}, "expected_output": {"effective_date": "2026-01-01"}}], ) print(proposal.bound_task) # how create would score this, or None if you must choose for p in proposal.proposals: print(p.task_id, p.confidence, p.evidence.get("validated_n"), "/", p.evidence.get("total_n")) ``` **TypeScript** ```typescript const proposal = await pa.evals.proposeContract({ prompt: "extract the effective and termination dates from each contract", items: [{ input: { contract_text: "..." }, expected_output: { effective_date: "2026-01-01" } }], }); console.log(proposal.boundTask); // how create would score this, or null if you must choose ``` If your data doesn't fit any of Pareta's built-in scorers, a judge panel grades each answer against what you asked for (reported as a win rate vs gpt-5.5) — so any dataset works. Pareta proposes this rather than assuming it; you confirm with `task="custom-eval"`. The rows go up as JSONL on the wire — one `{"input": {...}, "expected_output": {...}}` object per line. To pull sample rows in a shape Pareta already knows how to score, use `tasks.retrieve(task_id, examples_n=...)` — see the [tasks reference](../reference/tasks.md). Manage sets like any other resource: **Python** ```python pa.evals.sets.list() # -> list[EvalSet] pa.evals.sets.retrieve(eval_set.id) # -> EvalSet pa.evals.sets.delete(eval_set.id) # -> None ``` **TypeScript** ```typescript await pa.evals.sets.list(); // -> EvalSet[] await pa.evals.sets.retrieve(evalSet.id); // -> EvalSet await pa.evals.sets.delete(evalSet.id); // -> void ``` ### Document and image tasks Some tasks score over documents (PDFs, scanned invoices, images) rather than plain text. A task tells you this via `task.has_blob_input == True`. For those, each row references a binary that you attach after creating the set, one field at a time: **Python** ```python eval_set = pa.evals.sets.create( prompt="extract the total and vendor from each invoice", task="invoice-extraction", # optional pin — Pareta normally binds the grading contract from your prompt items=[ {"expected_output": {"total": "1240.00", "vendor": "Katana ML"}}, # the doc is attached next {"expected_output": {"total": "89.50", "vendor": "Acme"}}, ], ) # Attach the PDF for row 0's `document` field. pa.evals.sets.upload_document( eval_set.id, "invoices/katana-0001.pdf", # path, raw bytes, or a binary file-like object idx=0, # 0-based row index field_name="invoice", # the task's blob input field (see gold_schema/input_schema on tasks.retrieve) ) pa.evals.sets.upload_document(eval_set.id, "invoices/acme-0002.pdf", idx=1, field_name="invoice") ``` **TypeScript** ```typescript const evalSet = await pa.evals.sets.create({ prompt: "extract the total and vendor from each invoice", task: "invoice-extraction", // optional pin — Pareta normally binds the grading contract from your prompt items: [ { expected_output: { total: "1240.00", vendor: "Katana ML" } }, // the doc is attached next { expected_output: { total: "89.50", vendor: "Acme" } }, ], }); // Attach the PDF for row 0's `document` field. await pa.evals.sets.uploadDocument( evalSet.id, "invoices/katana-0001.pdf", // path, Blob, or bytes { idx: 0, // 0-based row index fieldName: "invoice", // the task's blob input field (see input_schema on tasks.retrieve) }, ); await pa.evals.sets.uploadDocument(evalSet.id, "invoices/acme-0002.pdf", { idx: 1, fieldName: "invoice" }); ``` `upload_document` collapses the whole upload dance into one call. Files under 5 MiB go up inline; larger files get a signed URL and stream straight to storage. It accepts a path (`str`/`Path`), raw `bytes`, or any object with `.read()`; anything else raises `TypeError`. The MIME type is guessed from the filename and can be overridden with `mime=`: **Python** ```python with open("invoices/scan.tiff", "rb") as f: pa.evals.sets.upload_document(eval_set.id, f, idx=2, field_name="invoice", mime="image/tiff") ``` **TypeScript** ```typescript import { readFile } from "node:fs/promises"; const bytes = await readFile("invoices/scan.tiff"); await pa.evals.sets.uploadDocument(evalSet.id, bytes, { idx: 2, fieldName: "invoice", mime: "image/tiff" }); ``` Frontier baselines on document tasks are automatically vision-filtered — you never accidentally score a contract scan against a text-only model. ## Step 2: run the eval `evals.runs.create` is the workhorse. You can drive an existing set, or create one inline in the same call. **Python** ```python # Against an existing set run = pa.evals.runs.create(eval_set=eval_set.id, models=["auto"], frontier="benchmarked", wait=True) # Inline: create the set and run it in one shot run = pa.evals.runs.create( prompt="extract the key fields from each contract", items=[{"input": {"contract_text": "..."}, "expected_output": {...}}], models=["auto"], frontier="benchmarked", wait=True, ) ``` **TypeScript** ```typescript // Against an existing set let run = await pa.evals.runs.create({ evalSet: evalSet.id, models: ["auto"], frontier: "benchmarked", wait: true }); // Inline: create the set and run it in one shot run = await pa.evals.runs.create({ prompt: "extract the key fields from each contract", items: [{ input: { contract_text: "..." }, expected_output: {} }], models: ["auto"], frontier: "benchmarked", wait: true, }); ``` You must pass **either** `eval_set=` **or** `items=… + prompt=…` (with `task=` optional); the SDK raises `ValueError` if you give neither. `models` is required — pass `["auto"]`; `frontier=` names the baselines it is measured against. Each run is **metered**: the org balance is debited for the compute across auto and the frontier baselines. If the balance is empty, `create` raises `InsufficientCreditsError` (402). Top-up is browser-only — the SDK never exposes balance or payment methods. See [Errors and metering](errors-and-retries.md). ### Choosing frontier baselines `frontier=` controls which vendor models get scored alongside `"auto"`, so the report shows you exactly how much quality (and cost) you're trading. It accepts a keyword or an explicit list, resolved SDK-side: | `frontier=` | Baselines scored | | --- | --- | | `None` or `"none"` (default `None`) | none — `"auto"` alone | | `"all"` | every frontier model available for the task | | `"benchmarked"` | frontier models Pareta has already benchmarked on the task (vision-filtered for document tasks) | | `["gpt-5.5", "claude-sonnet-4-6"]` | exactly these frontier model ids | **Python** ```python # Just auto, no baseline run = pa.evals.runs.create(eval_set=eval_set.id, models=["auto"], frontier="none", wait=True) # Everything in the frontier pool for the task run = pa.evals.runs.create(eval_set=eval_set.id, models=["auto"], frontier="all", wait=True) # A hand-picked baseline run = pa.evals.runs.create(eval_set=eval_set.id, models=["auto"], frontier=["gpt-5.5"], wait=True) ``` **TypeScript** ```typescript // Just auto, no baseline let run = await pa.evals.runs.create({ evalSet: evalSet.id, models: ["auto"], frontier: "none", wait: true }); // Everything in the frontier pool for the task run = await pa.evals.runs.create({ evalSet: evalSet.id, models: ["auto"], frontier: "all", wait: true }); // A hand-picked baseline run = await pa.evals.runs.create({ evalSet: evalSet.id, models: ["auto"], frontier: ["gpt-5.5"], wait: true }); ``` The `"all"` and `"benchmarked"` keywords resolve against your eval set (or a pinned `task=`). If the SDK can't resolve them it raises `ValueError`, and an unrecognized keyword (anything other than `"all"`/`"benchmarked"`/`"none"`) raises `ValueError` too. To see and pin the roster yourself, list it first: **Python** ```python roster = pa.evals.frontier_models(task=eval_set.task_id) for m in roster: print(m.id, m.vendor, "vision" if m.vision else "text", "benchmarked" if m.benchmarked else "-") # Pin two of them explicitly ids = [m.id for m in roster if m.benchmarked][:2] run = pa.evals.runs.create(eval_set=eval_set.id, models=["auto"], frontier=ids, wait=True) ``` **TypeScript** ```typescript const roster = await pa.evals.frontierModels("contract-key-fields"); for (const m of roster) { console.log(m.id, m.vendor, m.vision ? "vision" : "text", m.benchmarked ? "benchmarked" : "-"); } // Pin two of them explicitly const ids = roster.filter((m) => m.benchmarked).map((m) => m.id).slice(0, 2); const run = await pa.evals.runs.create({ evalSet: evalSet.id, models: ["auto"], frontier: ids, wait: true }); ``` `frontier_models()` annotates `benchmarked` and applies the capability filter only when you pass `task=`. Without a task it returns the full roster, unannotated. ### Waiting, or not By default `create` returns as soon as the run is queued, so you can poll on your own schedule: **Python** ```python run = pa.evals.runs.create(eval_set=eval_set.id, models=["auto"]) print(run.status) # "running" (or queued) run = pa.evals.runs.retrieve(run.id) # refetch full state while not run.is_terminal: run = pa.evals.runs.retrieve(run.id) ``` **TypeScript** ```typescript let run = await pa.evals.runs.create({ evalSet: evalSet.id, models: ["auto"] }); console.log(run.status); // "running" (or queued) run = await pa.evals.runs.retrieve(run.id); // refetch full state while (!run.isTerminal) { run = await pa.evals.runs.retrieve(run.id); } ``` Or let the SDK block for you. `wait=True` polls `runs.retrieve` every `poll_interval` seconds (default 3.0) until the run is terminal, up to `timeout` seconds (default 900.0), then returns the final `EvalRun`. If the deadline passes first it raises `ParetaError`. You can also poll an already-started run with the same semantics: **Python** ```python run = pa.evals.runs.create(eval_set=eval_set.id, models=["auto"]) run = pa.evals.runs.wait(run.id, poll_interval=5.0, timeout=1800.0) ``` **TypeScript** ```typescript let run = await pa.evals.runs.create({ evalSet: evalSet.id, models: ["auto"] }); run = await pa.evals.runs.wait(run.id, { pollInterval: 5.0, timeout: 1800.0 }); ``` `is_terminal` is true when `status` is `"completed"` or `"failed"`. On failure, read `run.error_detail` for the message. ## Step 3: read the results A terminal `EvalRun` carries one `EvalResult` per contender in `run.results` — `"auto"` plus each frontier baseline — and the bill. **Python** ```python run = pa.evals.runs.retrieve(run_id) if run.status == "failed": print("run failed:", run.error_detail) else: auto = next(r for r in run.results if r.model_id == "auto") print(f"auto: q={auto.quality_mean:.3f} @ ~{auto.mean_cost_micro_usd} uUSD/item") for r in run.results: print(r.model_id, r.kind, r.quality_mean, r.quality_ci_low, r.quality_ci_high, r.mean_cost_micro_usd, r.n_succeeded, r.error_count) ``` **TypeScript** ```typescript const run = await pa.evals.runs.retrieve(runId); if (run.status === "failed") { console.log("run failed:", run.errorDetail); } else { const auto = run.results.find((r) => r.modelId === "auto")!; console.log(`auto: q=${auto.qualityMean} @ ~${auto.meanCostMicroUsd} uUSD/item`); for (const r of run.results) { console.log( r.modelId, r.kind, r.qualityMean, r.qualityCiLow, r.qualityCiHigh, r.meanCostMicroUsd, r.nSucceeded, r.errorCount, ); } } ``` Each `EvalResult` has: - `model_id` — `"auto"` for Pareta's row; the vendor id for each frontier baseline. - `kind` — `"frontier"` on the baseline rows. Filter on it to separate the contender from what it is measured against. - `quality_mean`, `quality_ci_low`, `quality_ci_high` — mean score in `[0, 1]` with a 95% confidence interval. Use the interval: two contenders whose CIs overlap are not meaningfully different on this sample, so add rows before declaring a winner. - `exact_match` — classification contracts only: the percentage of items whose predicted label(s) exactly matched the gold. **On classification runs, treat this as the primary quality number.** There, `quality_mean` is the dataset-level macro-F1 — the published-leaderboard aggregate, which counts a class only when it appears in both the golds and the predictions. That is the right metric at leaderboard scale, but on a small set it can overstate quality badly (misses whose confused classes never collide simply drop out of the average). `exact_match` has no such failure mode. - `mean_cost_micro_usd` — average cost per item in **micro-USD** (1,000,000 = $1.00). This stays in micro-USD on purpose: flooring sub-cent unit rates to whole cents would erase the auto-vs-frontier cost gap that the whole exercise is about. - `n_succeeded`, `error_count` — how many items scored vs. errored for that contender. - `per_item` — the per-item rows, each an `EvalItemResult` with `idx`, `score`, `error`, and `prediction` (the model's raw output, truncated). Reach for `prediction` when a `score` is surprisingly low — it's the actual answer, so you can see *why* it lost points without re-running the eval. ### What the run cost The run total comes back two ways. `run.cost` is what you're billed — a `Decimal` in dollars, **floored to whole cents** (the SDK never rounds a charge up). `run.cost_micro_usd` is the raw integer for precise accounting. **Python** ```python print(run.cost) # Decimal('0.07') -> dollars, floored to cents print(run.cost_micro_usd) # 74211 -> raw micro-USD ``` **TypeScript** ```typescript console.log(run.cost); // "0.07" -> dollar string, floored to cents console.log(run.costMicroUsd); // 74211 -> raw micro-USD ``` A run that costs less than a cent reads `Decimal("0.00")` on `run.cost` while still carrying its true micro-USD value on `run.cost_micro_usd`. The same money convention applies everywhere in the SDK; see [Errors and metering](errors-and-retries.md) for the full picture. Every response object also keeps the raw server JSON: `run.to_dict()`, `result.to_dict()`, and `eval_set.to_dict()` give you lossless access to anything not yet surfaced as a typed field. ## Async Every method has an async twin on `AsyncPareta` with the same signatures. Run evals concurrently and await the results: **Python** ```python import asyncio from pareta import AsyncPareta async def main(): async with AsyncPareta.from_env() as pa: run = await pa.evals.runs.create( prompt="extract the key fields from each contract", items=[{"input": {"contract_text": "..."}, "expected_output": {...}}], models=["auto"], frontier="benchmarked", wait=True, ) for r in run.results: print(r.model_id, r.kind, r.quality_mean) print("billed", run.cost) asyncio.run(main()) ``` **TypeScript** In TypeScript there is no separate async client — `Pareta` is already Promise-only, so every I/O method is just `await`ed. Concurrency is `Promise.all`: ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); const run = await pa.evals.runs.create({ prompt: "extract the key fields from each contract", items: [{ input: { contract_text: "..." }, expected_output: {} }], models: ["auto"], frontier: "benchmarked", wait: true, }); for (const r of run.results) { console.log(r.modelId, r.kind, r.qualityMean); } console.log("billed", run.cost); // Fan several runs out concurrently with Promise.all: const [a, b] = await Promise.all([ pa.evals.runs.create({ evalSet: setA, models: ["auto"], frontier: "benchmarked", wait: true }), pa.evals.runs.create({ evalSet: setB, models: ["auto"], frontier: "benchmarked", wait: true }), ]); ``` `await pa.evals.runs.wait(runId)` and `await pa.evals.frontierModels(task)` work the same way. Document uploads are async too: `await pa.evals.sets.uploadDocument(...)`. ## From eval to production There is no deploy step. The routing that just won your eval is the same routing that serves `model="auto"` in production — keep sending it your traffic: **Python** ```python resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Extract the effective date from: ..."}], ) print(resp.choices[0].message.content) ``` **TypeScript** ```typescript const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Extract the effective date from: ..." }], }); console.log(resp.choices[0].message.content); ``` Inference is OpenAI-compatible and metered the same way evals are — one debit per request, no matter how many internal model calls auto's plan makes. To watch the production side of the story — requests, success rate, spend, and the projected savings vs frontier — poll `auto.metrics()`. See [Running inference](./inference.md) and [Cost & quality monitoring](../examples/cost-and-metrics.md). ## See also - [The tasks reference](../reference/tasks.md) — task ids, schemas, and sample rows. - [Running inference](./inference.md) — the OpenAI-compatible `model="auto"` chat surface. - [Cost & quality monitoring](../examples/cost-and-metrics.md) — read run costs and watch live auto traffic with `auto.metrics()`. - [Errors and metering](errors-and-retries.md) — `InsufficientCreditsError`, the money convention, and the exception hierarchy. --- # Errors, retries & timeouts Every failure the SDK can raise is a subclass of `ParetaError`, so one `except` clause catches everything, and a more specific clause catches exactly the case you care about. The client also retries transient failures for you (network blips, 429s, 5xx) with exponential backoff before giving up. This page is the map: which exception means what, what is retried automatically, and how to tune the timeout and retry budget. Import the exceptions straight from the package: **Python** ```python from pareta import ( Pareta, ParetaError, # base class for everything below APIConnectionError, # never reached the server (DNS/TCP/TLS) APITimeoutError, # subclass of APIConnectionError APIStatusError, # any non-2xx from the server BadRequestError, # 400, 422 AuthenticationError, # 401 PermissionDeniedError, # 403 InsufficientCreditsError, # 402 — org out of balance NotFoundError, # 404 ConflictError, # 409 RateLimitError, # 429 EndpointNotReadyError, # 503 — a backend behind auto warming/briefly down ) ``` **TypeScript** ```typescript import { Pareta, ParetaError, // base class for everything below APIConnectionError, // never reached the server (DNS/TCP/TLS) APITimeoutError, // subclass of APIConnectionError APIStatusError, // any non-2xx from the server BadRequestError, // 400, 422 AuthenticationError, // 401 PermissionDeniedError, // 403 InsufficientCreditsError, // 402 — org out of balance NotFoundError, // 404 ConflictError, // 409 RateLimitError, // 429 EndpointNotReadyError, // 503 — a backend behind auto warming/briefly down } from "pareta"; ``` ## The hierarchy ``` ParetaError ├── APIConnectionError request never reached the server │ └── APITimeoutError timed out before any response └── APIStatusError server returned a non-2xx status ├── BadRequestError 400, 422 ├── AuthenticationError 401 ├── InsufficientCreditsError 402 ├── PermissionDeniedError 403 ├── NotFoundError 404 ├── ConflictError 409 ├── RateLimitError 429 └── EndpointNotReadyError 503 ``` `ParetaError` is also raised directly (not as an `APIStatusError`) in two non-HTTP cases: constructing a client with no API key, and an `evals.runs.wait()` poll loop that exceeds its `timeout`. See [Timeouts](#timeouts) below. ## Status code to exception The server is FastAPI, so error bodies are `{"detail": ""}` with an HTTP status. The SDK maps the status to the most specific subclass so you catch by meaning, not by sniffing integers. | Status | Exception | What it means | |--------|-----------|---------------| | 400, 422 | `BadRequestError` | Request validation failed (bad params, malformed body), or an `Idempotency-Key` reused with a different request within 24 hours (422; send a new key) | | 400 · `input_modality_unsupported` / `input_required` | `BadRequestError` | The workload `auto` matched needs an input the request did not carry — a document/image or an audio file (or another input the planner flagged). Attach it and retry. Only structured requests (`response_format`) get this error; a plain prose request receives a clarification message instead. Not billed. | | 401 | `AuthenticationError` | API key missing or invalid | | 402 | `InsufficientCreditsError` | Org is out of balance; top up in the dashboard | | 403 | `PermissionDeniedError` | Authenticated, but not allowed to do this | | 404 | `NotFoundError` | Task / eval set / run id does not exist | | 409 | `ConflictError` | Conflict (transient lock/contention), or a request with the same `Idempotency-Key` is still running after 9 minutes. Retried automatically with the same key, honoring `Retry-After` | | 413 | `APIStatusError` | Request body over 30 MB; not retried | | 429 | `RateLimitError` | Rate limited: over the concurrency ceiling (8 requests in flight per serving instance; `Retry-After: 5`) or the rate ceiling (120 requests per minute; `Retry-After: 15`). Nothing is served or billed; honor `Retry-After` (the SDK does) | | 502 | `APIStatusError` | No serving path could complete the request, or a structured request produced no schema-conformant answer; not billed; retried automatically | | 503 | `EndpointNotReadyError` | A serving backend behind `auto` is warming or briefly unavailable, or the `Idempotency-Key` check is briefly unavailable. Retried automatically with the same key | | other 5xx | `APIStatusError` | Generic server error | ## Reading an `APIStatusError` Every `APIStatusError` carries the fields you need to log and debug. `request_id` comes from the `x-request-id` response header and is the fastest thing to quote in a support thread. **Python** ```python from pareta import Pareta, APIStatusError with Pareta.from_env() as pa: try: pa.tasks.retrieve("nonexistent-task") except APIStatusError as e: print(e.status_code) # 404 print(e.detail) # server's `detail` string (or raw body) print(e.request_id) # "req_…" — quote this in bug reports print(e.response) # the underlying httpx.Response, for advanced use ``` **TypeScript** ```typescript import { Pareta, APIStatusError } from "pareta"; const pa = Pareta.fromEnv(); try { await pa.tasks.retrieve("nonexistent-task"); } catch (e) { if (e instanceof APIStatusError) { console.log(e.status); // 404 console.log(e.detail); // server's `detail` string (or raw body) console.log(e.requestId); // "req_…" — quote this in bug reports console.log(e.response); // the underlying fetch Response, for advanced use } } ``` `str(e)` is the server's `detail` message when present, otherwise `HTTP `. ## The errors worth catching Most code only needs to handle a handful of these explicitly. The rest are fine to let bubble up to a top-level `except ParetaError`. ### `InsufficientCreditsError` (402) — out of balance Both inference and evals are metered against your org's balance. A successful [`chat.completions.create()`](./inference.md) debits the balance; an [`evals.runs.create()`](evaluation.md) debits for the auto and frontier compute it runs. When the balance can't cover the call, you get a 402. Top-up is browser-only — the SDK exposes no balance or payment surface — so the right move is to surface a clear message pointing at the dashboard. **Python** ```python from pareta import Pareta, InsufficientCreditsError with Pareta.from_env() as pa: try: resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Extract the parties."}], ) except InsufficientCreditsError: raise SystemExit("Org balance is empty. Top up at https://app.pareta.ai") ``` **TypeScript** ```typescript import { Pareta, InsufficientCreditsError } from "pareta"; const pa = Pareta.fromEnv(); try { const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Extract the parties." }], }); } catch (e) { if (e instanceof InsufficientCreditsError) { throw new Error("Org balance is empty. Top up at https://app.pareta.ai"); } throw e; } ``` ### `NotFoundError` (404) — wrong id A stale or mistyped task id, eval set id, or run id. **Python** ```python from pareta import Pareta, NotFoundError with Pareta.from_env() as pa: try: task = pa.tasks.retrieve("nonexistent-task") except NotFoundError: match = pa.tasks.match("extract key fields from contracts") # recover the real id if match.chosen: task = pa.tasks.retrieve(match.chosen.task_id) ``` **TypeScript** ```typescript import { Pareta, NotFoundError } from "pareta"; const pa = Pareta.fromEnv(); let task; try { task = await pa.tasks.retrieve("nonexistent-task"); } catch (e) { if (e instanceof NotFoundError) { const match = await pa.tasks.match("extract key fields from contracts"); // recover the real id if (match.chosen?.taskId) task = await pa.tasks.retrieve(match.chosen.taskId); } else { throw e; } } ``` ### `EndpointNotReadyError` (503) — a backend is still warming `auto` routes each request across serving backends that Pareta manages. Occasionally the one your request needs is warming up (a cold start) or briefly unavailable, and the request surfaces a 503. The SDK already retries 503 a couple of times (see [Automatic retries](#automatic-retries)), which absorbs most warm-ups; if it still surfaces, there is nothing to start or fix on your side — wait briefly and re-issue the request. **Python** ```python import time from pareta import Pareta, EndpointNotReadyError with Pareta.from_env() as pa: try: resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "ping"}], ) except EndpointNotReadyError: time.sleep(10) # still warming after the SDK's own retries resp = pa.chat.completions.create( # same request, second pass model="auto", messages=[{"role": "user", "content": "ping"}], ) ``` **TypeScript** ```typescript import { Pareta, EndpointNotReadyError } from "pareta"; const pa = Pareta.fromEnv(); const request = () => pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "ping" }], }); let resp; try { resp = await request(); } catch (e) { if (e instanceof EndpointNotReadyError) { await new Promise((r) => setTimeout(r, 10_000)); // still warming after the SDK's own retries resp = await request(); // same request, second pass } else { throw e; } } ``` ### `RateLimitError` (429) — slow down Already retried automatically, honoring the server's `Retry-After`. You only see it after the retry budget is exhausted. Back off and try again later. **Python** ```python from pareta import Pareta, RateLimitError with Pareta.from_env() as pa: try: pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "hi"}], ) except RateLimitError as e: print(f"Still rate limited after retries (request {e.request_id}); back off.") ``` **TypeScript** ```typescript import { Pareta, RateLimitError } from "pareta"; const pa = Pareta.fromEnv(); try { await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "hi" }], }); } catch (e) { if (e instanceof RateLimitError) { console.log(`Still rate limited after retries (request ${e.requestId}); back off.`); } else { throw e; } } ``` ### `AuthenticationError` (401) vs missing key A 401 means the key reached the server and was rejected (wrong or revoked). That is distinct from constructing a client with *no* key at all, which fails fast client-side with a plain `ParetaError` before any request goes out: **Python** ```python import pareta try: pa = pareta.Pareta(api_key="") # or PARETA_API_KEY unset with from_env() except pareta.ParetaError as e: print(e) # "missing API key. Pass api_key=… or set PARETA_API_KEY …" ``` **TypeScript** ```typescript import { Pareta, ParetaError } from "pareta"; try { const pa = new Pareta({ apiKey: "" }); // or PARETA_API_KEY unset with Pareta.fromEnv() } catch (e) { if (e instanceof ParetaError) { console.log(e.message); // "missing API key. Pass apiKey: … or use Pareta.fromEnv() …" } } ``` ## Pre-flight `ValueError` / `TypeError` Some mistakes never become an HTTP call. The SDK validates the obvious ones up front and raises the standard Python exception — not a `ParetaError` — because they are programming errors, not server responses: - [`chat.completions.create()`](./inference.md) raises `ValueError` if `model` or `messages` is empty. - [`tasks.match()`](../reference/tasks.md) raises `ValueError` if `query` is empty. - [`evals.sets.create()`](evaluation.md) raises `ValueError` if `items` or `prompt` is empty. - [`evals.runs.create()`](evaluation.md) raises `ValueError` if neither `eval_set=` nor `items=` (with `prompt=`) is supplied, and `ValueError`/`TypeError` if `frontier=` is an unparseable keyword or a frontier keyword can't be resolved to a task. - [`evals.sets.upload_document()`](evaluation.md) raises `TypeError` if `file` is not a path, bytes, or a binary file-like object. These are fine to let crash in development; they signal a bug in the call, not a runtime condition to recover from. ## Automatic retries The client retries transient failures for you before raising. You usually do not need a retry loop of your own. **What is retried:** status codes `408, 409, 429, 500, 502, 503, 504`, plus connection-level errors that happen *between* attempts. The default budget is `max_retries=2` (so up to three attempts total). **Backoff:** if the server sent a `Retry-After` header, the SDK waits that many seconds (capped at 30s). Otherwise it uses exponential backoff with jitter: `min(0.5 * 2**attempt, 8.0) + random(0, 0.25)` seconds, so roughly 0.5s, then 1s, capped at 8s. **What is not retried:** stable 4xx (400, 401, 402, 403, 404, 422) raise immediately — retrying a bad request or an empty balance won't help. Connection errors on the very first attempt are surfaced as `APIConnectionError` / `APITimeoutError` once the budget is exhausted. Tune the budget per client. Set `max_retries=0` to disable retries entirely: **Python** ```python from pareta import Pareta # More aggressive: up to 6 attempts on transient failures. pa = Pareta.from_env(max_retries=5) # No retries — fail fast and handle it yourself. strict = Pareta.from_env(max_retries=0) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; // More aggressive: up to 6 attempts on transient failures. const pa = Pareta.fromEnv({ maxRetries: 5 }); // No retries — fail fast and handle it yourself. const strict = Pareta.fromEnv({ maxRetries: 0 }); ``` ### Streaming and retries Retries apply only to the initial handshake (connect and status line). Once SSE bytes are flowing — token chunks from a streamed [chat completion](./inference.md) — a mid-stream drop raises immediately, because the stream cannot be safely resumed. Catch it and restart the request from the top if you need to. **Python** ```python from pareta import Pareta, APIConnectionError with Pareta.from_env() as pa: try: for chunk in pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Summarize the contract."}], stream=True, ): piece = chunk.choices[0].delta.content if piece: print(piece, end="", flush=True) except APIConnectionError: print("\n[stream dropped — re-issue the request to retry]") ``` **TypeScript** ```typescript import { Pareta, APIConnectionError } from "pareta"; const pa = Pareta.fromEnv(); try { const stream = pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Summarize the contract." }], stream: true, }); for await (const chunk of stream) { const piece = chunk.choices[0].delta.content; if (piece) process.stdout.write(piece); } } catch (e) { if (e instanceof APIConnectionError) { console.log("\n[stream dropped — re-issue the request to retry]"); } else { throw e; } } ``` ## Timeouts The default per-request timeout is `httpx.Timeout(600.0, connect=10.0)`: 600 s overall, 10 s to establish the connection (TypeScript: a single 600 000 ms budget). A request that exceeds it raises `APITimeoutError` (a subclass of `APIConnectionError`) after the retry budget is spent. Override it with any `httpx.Timeout` (or a bare float): **Python** ```python import httpx from pareta import Pareta, APITimeoutError # 120s overall, 5s to connect — handy for long generations. pa = Pareta.from_env(timeout=httpx.Timeout(120.0, connect=5.0)) with pa: try: pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Write a long summary."}], max_tokens=4096, ) except APITimeoutError: print("Request timed out; consider streaming or a larger timeout.") ``` **TypeScript** ```typescript import { Pareta, APITimeoutError } from "pareta"; // 120s overall (one budget — there's no separate connect timeout in TS). const pa = Pareta.fromEnv({ timeout: 120_000 }); try { await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Write a long summary." }], max_tokens: 4096, }); } catch (e) { if (e instanceof APITimeoutError) { console.log("Request timed out; consider streaming or a larger timeout."); } else { throw e; } } ``` ### Eval-run wait timeout [`evals.runs.create(wait=True)`](evaluation.md) and `evals.runs.wait()` are different: they poll the run to completion. The `timeout` parameter there bounds the *whole poll loop* (default 900s), not a single HTTP request. If the run hasn't reached a terminal status (`completed` or `failed`) by the deadline, the poll helper raises a plain `ParetaError` — the run keeps going server-side, so you can re-`retrieve()` it later by id. **Python** ```python from pareta import Pareta, ParetaError with Pareta.from_env() as pa: try: run = pa.evals.runs.create( prompt="extract the key fields from each contract", items=[{"input": {"contract_text": "..."}, "expected_output": {...}}], models=["auto"], frontier="benchmarked", wait=True, timeout=600.0, # give up waiting after 10 minutes poll_interval=5.0, ) print(run.status, run.cost) # e.g. "completed" Decimal("0.42") except ParetaError as e: print(e) # "eval run … did not finish within 600s" — poll later with runs.retrieve(id) ``` **TypeScript** ```typescript import { Pareta, ParetaError } from "pareta"; const pa = Pareta.fromEnv(); try { const run = await pa.evals.runs.create({ prompt: "extract the key fields from each contract", items: [{ input: { contract_text: "..." }, expected_output: {} }], models: ["auto"], frontier: "benchmarked", wait: true, timeout: 600, // give up waiting after 10 minutes pollInterval: 5, }); console.log(run.status, run.cost); // e.g. "completed" "0.42" } catch (e) { if (e instanceof ParetaError) { console.log(e.message); // "eval run … did not finish within 600s" — poll later with runs.retrieve(id) } else { throw e; } } ``` Note that a run finishing with `status == "failed"` is *not* an exception — it's a terminal state you read off the returned `EvalRun` (`run.is_terminal` is True, `run.error_detail` carries the message). Only the wait *timeout* raises. ## Async `AsyncPareta` raises the exact same exception classes; wrap `await` calls in the same `try`/`except`. Retries, backoff, and timeouts behave identically — backoff just uses `asyncio.sleep` under the hood. **Python** ```python import asyncio from pareta import AsyncPareta, InsufficientCreditsError, EndpointNotReadyError async def main(): async with AsyncPareta.from_env() as pa: try: resp = await pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Extract the parties."}], ) print(resp.choices[0].message.content) except InsufficientCreditsError: print("Top up your org balance in the dashboard.") except EndpointNotReadyError: print("A backend behind auto is still warming — retry shortly.") asyncio.run(main()) ``` **TypeScript** ```typescript // There is no AsyncPareta in TypeScript — the single `Pareta` client is already // async: every I/O method returns a Promise, so you just `await` it. The same // exception classes, retries, backoff, and timeouts apply unchanged. import { Pareta, InsufficientCreditsError, EndpointNotReadyError } from "pareta"; async function main() { const pa = Pareta.fromEnv(); try { const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Extract the parties." }], }); console.log(resp.choices[0].message.content); } catch (e) { if (e instanceof InsufficientCreditsError) { console.log("Top up your org balance in the dashboard."); } else if (e instanceof EndpointNotReadyError) { console.log("A backend behind auto is still warming — retry shortly."); } else { throw e; } } } main(); ``` ## A layered handler A practical pattern: catch the few cases you can act on, then fall back to the base class so nothing escapes unhandled. **Python** ```python from pareta import ( Pareta, InsufficientCreditsError, EndpointNotReadyError, RateLimitError, APITimeoutError, ParetaError, ) with Pareta.from_env() as pa: try: resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Extract the parties."}], ) print(resp.choices[0].message.content) except InsufficientCreditsError: print("Out of balance — top up in the dashboard.") except EndpointNotReadyError: print("A backend is still warming — wait briefly, then retry.") except RateLimitError: print("Rate limited after retries — back off and try again.") except APITimeoutError: print("Timed out — raise the timeout or stream the response.") except ParetaError as e: print(f"Unexpected SDK error: {e}") # request_id is on APIStatusError subclasses ``` **TypeScript** ```typescript import { Pareta, InsufficientCreditsError, EndpointNotReadyError, RateLimitError, APITimeoutError, ParetaError, } from "pareta"; const pa = Pareta.fromEnv(); try { const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Extract the parties." }], }); console.log(resp.choices[0].message.content); } catch (e) { if (e instanceof InsufficientCreditsError) { console.log("Out of balance — top up in the dashboard."); } else if (e instanceof EndpointNotReadyError) { console.log("A backend is still warming — wait briefly, then retry."); } else if (e instanceof RateLimitError) { console.log("Rate limited after retries — back off and try again."); } else if (e instanceof APITimeoutError) { console.log("Timed out — raise the timeout or stream the response."); } else if (e instanceof ParetaError) { console.log(`Unexpected SDK error: ${e.message}`); // requestId is on APIStatusError subclasses } else { throw e; } } ``` ## See also - [Inference](./inference.md) — OpenAI-compatible chat completions and streaming - [Evals](evaluation.md) — eval sets, runs, `wait`, and `run.cost` - [Tasks](../reference/tasks.md) — the benchmark catalog and `match()` --- # Async usage `AsyncPareta` is the asyncio-native client. It mirrors the synchronous [`Pareta`](./quickstart.md) client method-for-method: same constructor, same resource namespaces (`chat`, `models`, `tasks`, `evals`, `auto`, `audio`), same return types. The difference is that request methods are coroutines you `await`, streams are async iterators you drive with `async for`, and many independent calls can run concurrently under one event loop instead of blocking one after another. Reach for it when you are inside an async app (FastAPI, an aiohttp worker, a Discord bot) or when you want to fan out work: run a batch of prompts against `model="auto"` without waiting on each round trip, or kick off several eval runs at once. ## The client Build it from the environment, exactly like the sync client. `from_env()` reads `PARETA_API_KEY` and the optional `PARETA_BASE_URL`. **Python** ```python import asyncio from pareta import AsyncPareta async def main(): pa = AsyncPareta.from_env() # reads PARETA_API_KEY try: models = await pa.models.list() for m in models: print(m.id, m.owned_by) finally: await pa.aclose() asyncio.run(main()) ``` **TypeScript** In TypeScript there is one client and it is already async — every I/O method returns a Promise you `await`. There is no `AsyncPareta`, no event loop to manage, and no `aclose()`: the client holds no owned connection. ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // reads PARETA_API_KEY const models = await pa.models.list(); for (const m of models) { console.log(m.id, m.ownedBy); } ``` `models.list()` returns the same `ModelList` as the sync path: exactly one entry, `"auto"` — the only model id you pass to `chat.completions.create(model=...)`. ### Lifecycle: prefer `async with` The client owns an `httpx.AsyncClient` and you must release it. Use `async with` and cleanup is automatic; otherwise call `await pa.aclose()` in a `finally`. **Python** ```python import asyncio from pareta import AsyncPareta async def main(): async with AsyncPareta.from_env() as pa: models = await pa.models.list() print([m.id for m in models]) # ['auto'] # the underlying HTTP client is closed here asyncio.run(main()) ``` **TypeScript** The TypeScript client owns no connection, so there is nothing to release — no `async with`, no `aclose()`. Build it once and use it; native `fetch` manages its own pooling. If you need a custom transport (tests, a polyfill), pass `fetch:`. ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); const models = await pa.models.list(); console.log([...models].map((m) => m.id)); // ["auto"] // nothing to close ``` The async lifecycle methods are `await pa.aclose()`, `async with` (which calls `__aenter__` / `__aexit__`). There is no sync `close()` on the async client. If you pass your own `http_client=httpx.AsyncClient(...)`, the SDK will not close it for you; that one is yours to manage. You can also pass `api_key=`, `base_url=`, `timeout=`, and `max_retries=` directly, same as the sync client: **Python** ```python from pareta import AsyncPareta pa = AsyncPareta(api_key="pareta_sk_...", max_retries=4) ``` **TypeScript** The constructor takes a single options object with camelCase keys. Note `timeout` is in **milliseconds** here (Python's httpx is seconds). ```typescript import { Pareta } from "pareta"; const pa = new Pareta({ apiKey: "pareta_sk_...", maxRetries: 4 }); ``` ## Await every request method Every resource method that hits the API is a coroutine. Await it. **Python** ```python import asyncio from pareta import AsyncPareta async def main(): async with AsyncPareta.from_env() as pa: # inference (OpenAI-compatible) completion = await pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Extract the total due."}], temperature=0, ) print(completion.choices[0].message.content) print(completion.usage.total_tokens, "tokens") # scoring preview match = await pa.tasks.match("pull key fields out of contracts") if match.matched: print("task:", match.chosen.task_id, match.chosen.confidence) # auto rollup (requests, success, spend, projected savings) metrics = await pa.auto.metrics() print(metrics["requests_30d"], "requests in 30d") # eval roster, annotated for the previewed grading contract frontier = await pa.evals.frontier_models(task=match.chosen.task_id) print([f.id for f in frontier]) asyncio.run(main()) ``` **TypeScript** Every method already returns a Promise, so `await` is all you need — no coroutine wrapper, no event loop. `chat.completions.create` takes an options object; extra OpenAI params (`temperature`) pass through verbatim. ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // inference (OpenAI-compatible) const completion = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Extract the total due." }], temperature: 0, }); console.log(completion.choices[0].message.content); console.log(completion.usage.totalTokens, "tokens"); // scoring preview const match = await pa.tasks.match("pull key fields out of contracts"); if (match.matched) { console.log("task:", match.chosen.taskId, match.chosen.confidence); } // auto rollup (requests, success, spend, projected savings) const metrics = await pa.auto.metrics(); console.log(metrics.requests_30d, "requests in 30d"); // eval roster const frontier = await pa.evals.frontierModels("contract-key-fields"); console.log(frontier.map((f) => f.id)); ``` `chat.completions.create()` is metered: a successful completion debits your org balance — one debit per request, no matter how many internal model calls auto's plan makes. If the balance is empty it raises `InsufficientCreditsError` (402). Top-up is browser-only; the SDK does not expose balance or payment. See [Errors](errors-and-retries.md) and [Billing](core-concepts.md). ## Streaming with `async for` Streaming chat works in two steps. First `await` the `create(stream=True)` call to get the async iterator, then drive it with `async for`. Each chunk is a `ChatCompletionChunk`; the incremental text is `chunk.choices[0].delta.content` (which can be `None` on non-content frames, so guard it). **Python** ```python import asyncio from pareta import AsyncPareta async def main(): async with AsyncPareta.from_env() as pa: stream = await pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Summarize this clause."}], stream=True, ) async for chunk in stream: delta = chunk.choices[0].delta.content if delta: print(delta, end="", flush=True) print() asyncio.run(main()) ``` **TypeScript** With `stream: true` the call returns an `AsyncIterable` directly — no separate await for the handshake. Drive it with `for await`. The incremental text is `chunk.choices[0].delta.content`, which can be `null` on non-content frames, so guard it. ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); const stream = pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Summarize this clause." }], stream: true, }); for await (const chunk of stream) { const delta = chunk.choices[0].delta.content; if (delta) process.stdout.write(delta); } console.log(); ``` The stream ends on the wire's `[DONE]` sentinel; the async iterator simply stops. Retries apply only to the initial handshake. Once bytes are flowing, a mid-stream drop raises immediately rather than silently resuming. ## Running many calls concurrently This is the reason to go async. Independent calls can run at the same time under one event loop with `asyncio.gather`, instead of serializing on each network round trip. Reuse one client across all of them so they share the connection pool. ### Fan out inference over a batch **Python** ```python import asyncio from pareta import AsyncPareta PROMPTS = [ "Extract the invoice total.", "Extract the due date.", "Extract the vendor name.", "Extract the PO number.", ] async def classify(pa: AsyncPareta, prompt: str) -> str: completion = await pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": prompt}], temperature=0, ) return completion.choices[0].message.content async def main(): async with AsyncPareta.from_env() as pa: results = await asyncio.gather( *(classify(pa, p) for p in PROMPTS) ) for prompt, answer in zip(PROMPTS, results): print(prompt, "->", answer) asyncio.run(main()) ``` **TypeScript** In TypeScript every call is already a Promise, so concurrency is just `Promise.all` over the calls you kick off — no `asyncio.gather`, no separate async API. Reuse one client so they share the connection pool. ```typescript import { Pareta } from "pareta"; const PROMPTS = [ "Extract the invoice total.", "Extract the due date.", "Extract the vendor name.", "Extract the PO number.", ]; const pa = Pareta.fromEnv(); async function classify(prompt: string): Promise { const completion = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: prompt }], temperature: 0, }); return completion.choices[0].message.content; } const results = await Promise.all(PROMPTS.map((p) => classify(p))); PROMPTS.forEach((prompt, i) => console.log(prompt, "->", results[i])); ``` Each of those `create()` calls is metered independently and debits the org balance on success. If your balance runs out mid-batch, the in-flight calls that have not yet been billed raise `InsufficientCreditsError`. With `gather`, the first exception propagates and cancels the rest; pass `return_exceptions=True` if you would rather collect partial results and inspect failures per item. **Python** ```python results = await asyncio.gather( *(classify(pa, p) for p in PROMPTS), return_exceptions=True, ) for prompt, result in zip(PROMPTS, results): if isinstance(result, Exception): print(prompt, "FAILED:", result) else: print(prompt, "->", result) ``` **TypeScript** `Promise.all` rejects on the first failure, just like `gather`. The equivalent of `return_exceptions=True` is `Promise.allSettled`, which collects a `{ status, value | reason }` per item. ```typescript const settled = await Promise.allSettled(PROMPTS.map((p) => classify(p))); PROMPTS.forEach((prompt, i) => { const result = settled[i]; if (result.status === "rejected") { console.log(prompt, "FAILED:", result.reason); } else { console.log(prompt, "->", result.value); } }); ``` ### Mix resources in one gather `gather` does not care that the coroutines hit different routes. Kick off an inference call, a scoring preview, and your org's auto rollup in one shot: **Python** ```python import asyncio from pareta import AsyncPareta async def main(): async with AsyncPareta.from_env() as pa: completion, match, metrics = await asyncio.gather( pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Extract the parties."}], ), pa.tasks.match("pull key fields out of contracts"), pa.auto.metrics(), ) print(completion.choices[0].message.content) if match.matched: print("task:", match.chosen.task_id) print("requests (30d):", metrics["requests_30d"]) asyncio.run(main()) ``` **TypeScript** `Promise.all` is heterogeneous too — the tuple keeps each result's type. ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); const [completion, match, metrics] = await Promise.all([ pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Extract the parties." }], }), pa.tasks.match("pull key fields out of contracts"), pa.auto.metrics(), ]); console.log(completion.choices[0].message.content); if (match.matched) { console.log("task:", match.chosen?.taskId); } console.log("requests (30d):", metrics.requests_30d); ``` ### Run several eval runs in parallel `evals.runs.create(..., wait=True)` polls `runs.retrieve()` until the run is terminal using `asyncio.sleep`, so it never blocks the loop. That makes benchmarking `"auto"` on several of your datasets — one run per eval set — a natural `gather`. Passing `prompt=` + `items=` creates the eval set and the run in one call. **Python** ```python import asyncio from pareta import AsyncPareta JOBS = { "extract the payment amount from each contract": [ {"input": {"contract_text": "Acme Corp agrees to pay $5,000 net 30."}, "expected_output": {"amount": "5000"}}, {"input": {"contract_text": "Total due: $1,200 by 2026-07-01."}, "expected_output": {"amount": "1200"}}, ], "extract the total from each invoice": [ {"input": {"text": "INVOICE #4471 ... TOTAL $1,240.00 ..."}, "expected_output": {"total": "1240.00"}}, ], } async def main(): async with AsyncPareta.from_env() as pa: # one run per dataset: "auto" against the task's frontier baselines runs = await asyncio.gather( *( pa.evals.runs.create( prompt=prompt, items=items, models=["auto"], frontier="benchmarked", wait=True, ) for prompt, items in JOBS.items() ) ) for run in runs: print(run.id, run.status, "cost", run.cost) # run.cost is a Decimal in dollars for r in run.results: print(" ", r.model_id, r.kind, r.quality_mean) asyncio.run(main()) ``` **TypeScript** `runs.create({ ..., wait: true })` polls `runs.retrieve()` until terminal, so the fan-out is a natural `Promise.all`. Note `run.cost` is a fixed-2dp dollar **string** here (`run.costMicroUsd` is the raw integer). ```typescript import { Pareta } from "pareta"; const JOBS: Record>> = { "extract the payment amount from each contract": [ { input: { contract_text: "Acme Corp agrees to pay $5,000 net 30." }, expected_output: { amount: "5000" } }, { input: { contract_text: "Total due: $1,200 by 2026-07-01." }, expected_output: { amount: "1200" } }, ], "extract the total from each invoice": [ { input: { text: "INVOICE #4471 ... TOTAL $1,240.00 ..." }, expected_output: { total: "1240.00" } }, ], }; const pa = Pareta.fromEnv(); // one run per dataset: "auto" against the task's frontier baselines const runs = await Promise.all( Object.entries(JOBS).map(([prompt, items]) => pa.evals.runs.create({ prompt, items, models: ["auto"], frontier: "benchmarked", wait: true }), ), ); for (const run of runs) { console.log(run.id, run.status, "cost", run.cost); // run.cost is a dollar string for (const r of run.results) { console.log(" ", r.modelId, r.kind, r.qualityMean); } } ``` Eval runs are metered against the org balance for the compute used (`"auto"` plus any frontier baselines), and raise `InsufficientCreditsError` on an empty balance. `run.cost` is a `Decimal` in dollars, floored to whole cents (so a sub-cent run reads `Decimal("0.00")`); `run.cost_micro_usd` is the raw integer micro-USD if you need the exact figure. See [Evals](evaluation.md) and [Billing](core-concepts.md). The `frontier=` keywords pick the vendor baselines. In the async client, `"all"` and `"benchmarked"` resolve the roster by awaiting `evals.frontier_models()` SDK-side, so they need a task to resolve against (a pinned `task=`, or the eval set's own task — including the one Pareta worked out for an inline `items=… + prompt=…` create): **Python** ```python run = await pa.evals.runs.create( eval_set=eval_set.id, # an existing set from evals.sets.create(...) models=["auto"], frontier="benchmarked", # or "all", or an explicit list of frontier ids, or None wait=True, ) ``` **TypeScript** `"all"` and `"benchmarked"` resolve the roster SDK-side via `evals.frontierModels()`, so they need a task to resolve against (from `task` or looked up from the eval set). ```typescript const run = await pa.evals.runs.create({ evalSet: evalSet.id, // an existing set from evals.sets.create(...) models: ["auto"], frontier: "benchmarked", // or "all", an explicit list of frontier ids, or null wait: true, }); ``` ### Polling a run yourself If you started a run with `wait=False`, await `runs.wait()` later, or poll `runs.retrieve()` on your own schedule. `wait()` accepts `poll_interval` (default 3.0s) and `timeout` (default 900s), and raises `ParetaError` if the run does not reach a terminal status in time. **Python** ```python run = await pa.evals.runs.create(eval_set=eval_set.id, models=["auto"]) print("queued:", run.id, run.status) # ... do other work ... final = await pa.evals.runs.wait(run.id, poll_interval=5.0, timeout=600.0) print(final.status, final.is_terminal, final.cost) ``` **TypeScript** `runs.wait(id, { pollInterval, timeout })` takes seconds (defaults 3 / 900) and throws `ParetaError` if the run does not finish in time. The run id is positional; the schedule is an options object. ```typescript const run = await pa.evals.runs.create({ evalSet: evalSet.id, models: ["auto"] }); console.log("queued:", run.id, run.status); // ... do other work ... const final = await pa.evals.runs.wait(run.id, { pollInterval: 5, timeout: 600 }); console.log(final.status, final.isTerminal, final.cost); ``` ## Bounding concurrency `gather` launches everything at once. For large batches, cap the in-flight count with an `asyncio.Semaphore` so you do not trip rate limits (which surface as `RateLimitError`, 429; the client already retries those with backoff up to `max_retries`). **Python** ```python import asyncio from pareta import AsyncPareta async def main(): sem = asyncio.Semaphore(5) # at most 5 concurrent requests async with AsyncPareta.from_env() as pa: async def one(prompt: str) -> str: async with sem: completion = await pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": prompt}], ) return completion.choices[0].message.content prompts = [f"Extract field {i}." for i in range(100)] answers = await asyncio.gather(*(one(p) for p in prompts)) print(len(answers), "done") asyncio.run(main()) ``` **TypeScript** `Promise.all` launches everything at once too. There is no built-in semaphore, so cap concurrency by draining a shared work queue from a fixed pool of workers — at most `LIMIT` requests are in flight at any time. ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); const LIMIT = 5; // at most 5 concurrent requests const prompts = Array.from({ length: 100 }, (_, i) => `Extract field ${i}.`); async function one(prompt: string): Promise { const completion = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: prompt }], }); return completion.choices[0].message.content; } const answers: (string | null)[] = new Array(prompts.length); let next = 0; async function worker() { while (next < prompts.length) { const i = next++; answers[i] = await one(prompts[i]); } } await Promise.all(Array.from({ length: LIMIT }, () => worker())); console.log(answers.length, "done"); ``` ## Errors The async client raises the exact same exception hierarchy as the sync client; the only difference is that errors surface out of an awaited call or an `async for`. Catch them the usual way. **Python** ```python from pareta import ( AsyncPareta, InsufficientCreditsError, EndpointNotReadyError, RateLimitError, ParetaError, ) async def safe_call(pa: AsyncPareta): try: return await pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "hi"}], ) except InsufficientCreditsError: print("org balance is empty; top up in the dashboard") except EndpointNotReadyError: print("a backend behind auto is briefly unavailable; retry in a moment") except RateLimitError: print("rate limited even after retries") except ParetaError as e: print("pareta error:", e) ``` **TypeScript** Same exception hierarchy, surfaced out of an awaited call (or a `for await`). JavaScript has one `catch` clause, so branch on `instanceof` — most specific first, since the subclasses all extend `ParetaError`. ```typescript import { Pareta, InsufficientCreditsError, EndpointNotReadyError, RateLimitError, ParetaError, } from "pareta"; async function safeCall(pa: Pareta) { try { return await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "hi" }], }); } catch (e) { if (e instanceof InsufficientCreditsError) { console.log("org balance is empty; top up in the dashboard"); } else if (e instanceof EndpointNotReadyError) { console.log("a backend behind auto is briefly unavailable; retry in a moment"); } else if (e instanceof RateLimitError) { console.log("rate limited even after retries"); } else if (e instanceof ParetaError) { console.log("pareta error:", e); } else { throw e; } } } ``` Pre-flight validation (empty `model`/`messages`, empty `items`, an unparseable `frontier`) raises `ValueError`/`TypeError` when you `await` the call — the check runs at the top of the coroutine, before any network I/O (not when the coroutine object is first created). See [Errors](errors-and-retries.md) for the full mapping. ## Sync and async, side by side | Concern | `Pareta` (sync) | `AsyncPareta` (async) | |---|---|---| | Build | `Pareta.from_env()` | `AsyncPareta.from_env()` | | Cleanup | `pa.close()` / `with pa:` | `await pa.aclose()` / `async with pa:` | | Request method | `pa.models.list()` | `await pa.models.list()` | | Streaming chat | `for chunk in pa.chat.completions.create(stream=True)` | `stream = await pa...create(stream=True)` then `async for chunk in stream` | | Wait on a run | `pa.evals.runs.wait(run_id)` | `await pa.evals.runs.wait(run_id)` | | Auto metrics | `pa.auto.metrics()` | `await pa.auto.metrics()` | | Concurrency | thread pool / one at a time | `asyncio.gather`, one event loop | Same metering, same OpenAI-compatible inference, same hidden models and GPUs. Once you have the sync flow in [Quickstart](./quickstart.md), the async version is the same calls with `await` in front and `async for` over the streams. --- # Configuration Every Pareta call goes through one client object. Configuration is just how you build that client: which API key it sends, which API root it points at, how patient it is on slow or flaky requests, and (optionally) what HTTP stack it rides on. This page covers all of it for both `Pareta` (sync) and `AsyncPareta` (async). The short version: set `PARETA_API_KEY` and use `Pareta.from_env()`. Everything below is for when the defaults are not enough. **Python** ```python from pareta import Pareta pa = Pareta.from_env() print(pa.models.list()) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); console.log(await pa.models.list()); ``` ## The fast path: `from_env()` `from_env()` reads two environment variables and builds the client for you: - `PARETA_API_KEY` — your `pareta_sk_…` key (required) - `PARETA_BASE_URL` — optional API-root override (defaults to production; set it only when routing through a self-hosted proxy or gateway) ```bash export PARETA_API_KEY="pareta_sk_…" ``` **Python** ```python from pareta import Pareta pa = Pareta.from_env() ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); ``` `from_env()` forwards any extra keyword arguments straight to the constructor, so you can keep the key in the environment while overriding everything else in code: **Python** ```python pa = Pareta.from_env(max_retries=5, timeout=120.0) ``` **TypeScript** ```typescript // timeout is milliseconds in TS (120 seconds → 120_000). const pa = Pareta.fromEnv({ maxRetries: 5, timeout: 120_000 }); ``` There is no separate async client in TypeScript — there is one `Pareta` class and every I/O method returns a `Promise` you `await`: **Python** ```python from pareta import AsyncPareta pa = AsyncPareta.from_env() ``` **TypeScript** ```typescript import { Pareta } from "pareta"; // Same client; await the calls (e.g. await pa.models.list()). const pa = Pareta.fromEnv(); ``` Prefer `from_env()` over hardcoding keys. It keeps `pareta_sk_…` secrets out of source control and lets the same code run directly against Pareta or through a proxy by flipping one environment variable. ## Constructor parameters Both clients take the same arguments: **Python** ```python from pareta import Pareta pa = Pareta( api_key="pareta_sk_…", base_url="https://api.pareta.ai", timeout=600.0, max_retries=2, http_client=None, ) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = new Pareta({ apiKey: "pareta_sk_…", baseURL: "https://api.pareta.ai", timeout: 600_000, // milliseconds maxRetries: 2, // fetch: customFetch, // bring your own fetch instead of http_client }); ``` | Parameter | Type | Default | What it does | |-----------|------|---------|--------------| | `api_key` | `str \| None` | `None` | Your `pareta_sk_…` key. Sent as a Bearer token. Required. | | `base_url` | `str \| None` | `"https://api.pareta.ai"` | API root. Override only to route through a self-hosted proxy or gateway. | | `timeout` | `httpx.Timeout \| float \| None` | `httpx.Timeout(600.0, connect=10.0)` | Per-request timeout. | | `max_retries` | `int` | `2` | Automatic retries on transient failures. | | `http_client` | `httpx.Client \| httpx.AsyncClient \| None` | `None` | Bring your own httpx client (proxies, custom transports, connection pools). | `AsyncPareta` is identical except `http_client` takes an `httpx.AsyncClient`. ## `api_key` The key is the one required piece of configuration. Pass it explicitly or via `PARETA_API_KEY`; the SDK sends it as `Authorization: Bearer ` on every request. **Python** ```python from pareta import Pareta pa = Pareta(api_key="pareta_sk_…") ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = new Pareta({ apiKey: "pareta_sk_…" }); ``` If the key is missing or empty (and the env var is unset when using `from_env()`), the constructor raises `ParetaError` before any network call: **Python** ```python from pareta import Pareta, ParetaError try: pa = Pareta(api_key="") except ParetaError as e: print(e) # missing API key. Pass api_key=… or set PARETA_API_KEY # (mint a pareta_sk_ key in the dashboard). ``` **TypeScript** ```typescript import { Pareta, ParetaError } from "pareta"; try { const pa = new Pareta({ apiKey: "" }); } catch (e) { if (e instanceof ParetaError) { console.log(e.message); // missing API key. Pass apiKey: … or use Pareta.fromEnv() with PARETA_API_KEY // (mint a pareta_sk_ key in the dashboard). } } ``` Mint keys in the dashboard. If the key is present but rejected by the server, you get a `401` as `AuthenticationError` on the first request, not at construction time. See [Errors](errors-and-retries.md) for the full exception hierarchy. ## `base_url` `base_url` is the API root. There is one Pareta API, `https://api.pareta.ai`, and `base_url` defaults to it; the value is normalized with a trailing-slash strip, so `https://api.pareta.ai/` and `https://api.pareta.ai` behave identically. Override it only when your requests go through a self-hosted proxy or an AI gateway that forwards to Pareta. **Python** ```python from pareta import Pareta # Default — base_url omitted. pa = Pareta(api_key="pareta_sk_…") # Through your own proxy or gateway — pass it explicitly, or set PARETA_BASE_URL. pa = Pareta( api_key="pareta_sk_…", base_url="https://pareta-gateway.internal.example.com", ) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; // Default — baseURL omitted. const pa = new Pareta({ apiKey: "pareta_sk_…" }); // Through your own proxy or gateway — pass it explicitly, or set PARETA_BASE_URL. const gateway = new Pareta({ apiKey: "pareta_sk_…", baseURL: "https://pareta-gateway.internal.example.com", }); ``` Via the environment, no code change needed: ```bash export PARETA_API_KEY="pareta_sk_…" export PARETA_BASE_URL="https://pareta-gateway.internal.example.com" ``` **Python** ```python from pareta import Pareta pa = Pareta.from_env() # now talks to Pareta through the proxy ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // now talks to Pareta through the proxy ``` The same `pareta_sk_…` key authenticates either way; the proxy must forward the `Authorization` header unchanged. ## `timeout` `timeout` caps how long a single request may take. The default is `httpx.Timeout(600.0, connect=10.0)`: up to 10 seconds to establish the connection and 600 seconds overall (the TypeScript client uses a single 600 000 ms budget). A bare float sets the overall timeout for read, write, and connect alike. **Python** ```python import httpx from pareta import Pareta # Simple: one number for everything. pa = Pareta(api_key="pareta_sk_…", timeout=120.0) # Granular: long read budget for big generations, short connect budget. pa = Pareta( api_key="pareta_sk_…", timeout=httpx.Timeout(120.0, connect=10.0), ) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; // One overall budget, in milliseconds (no separate connect budget in TS). const pa = new Pareta({ apiKey: "pareta_sk_…", timeout: 120_000 }); ``` When to raise it: - **Long completions.** Keep `timeout` above the serving deadline of the workload (45 s default, 120 s ICD-10 coding, 180 s long-document extraction); the default already is. Lower it only if your own caller has a tighter budget, or stream the response so tokens arrive incrementally (see [Inference](inference.md)). - **Long eval runs.** `evals.runs.create(..., wait=True)` does its own polling and has a separate `timeout` argument (default `900.0` seconds) that governs the wait loop, independent of the per-request HTTP timeout. See [Evals](evaluation.md). A request that exceeds the timeout raises `APITimeoutError` (a subclass of `APIConnectionError`) after retries are exhausted. ## `max_retries` The SDK automatically retries transient failures. The default is `2` (so up to 3 attempts total). Values below zero are clamped to `0`. Retries fire only on these status codes: ``` 408 Request Timeout 409 Conflict (transient lock/contention) 429 Too Many Requests 500 Internal Server Error 502 Bad Gateway 503 Service Unavailable 504 Gateway Timeout ``` Backoff is exponential with jitter, capped at 8 seconds: `min(0.5 * 2 ** attempt, 8.0)` plus a small random jitter. When the server sends a `Retry-After` header, the SDK honors it (capped at 30 seconds) instead of computing its own delay. **Python** ```python from pareta import Pareta # More patient: handy for batch jobs against a busy environment. pa = Pareta(api_key="pareta_sk_…", max_retries=5) # Disable retries entirely: every failure surfaces immediately. pa = Pareta(api_key="pareta_sk_…", max_retries=0) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; // More patient: handy for batch jobs against a busy environment. const patient = new Pareta({ apiKey: "pareta_sk_…", maxRetries: 5 }); // Disable retries entirely: every failure surfaces immediately. const failFast = new Pareta({ apiKey: "pareta_sk_…", maxRetries: 0 }); ``` What is *not* retried: - **4xx errors other than 408/409/429** — these are your request, not a transient blip. A `402 InsufficientCreditsError`, `401 AuthenticationError`, or `404 NotFoundError` raises on the first attempt. - **Connection errors on initial connect** (DNS, TCP, TLS refusal) — raised after the retry budget for the handshake is spent. - **Mid-stream drops.** Streaming calls (`chat.completions.create(stream=True)`) retry only the initial handshake. Once SSE bytes are flowing, a drop raises immediately, because a partial stream cannot be safely resumed. A `409` is worth a note: it is in the retry set because some backends use it for transient lock contention. A stable `409` from Pareta simply exhausts the retries and then raises `ConflictError`, so you see the right error either way. See [Errors](errors-and-retries.md). ## `http_client` (bring your own httpx) By default the client constructs its own httpx client, configured with your `timeout`, and closes it for you. Pass `http_client=` when you need control over the transport layer: an outbound proxy, a custom transport, mTLS, shared connection pools, or test doubles. **Python** ```python import httpx from pareta import Pareta # Route through a corporate proxy with a tuned connection pool. my_client = httpx.Client( proxy="http://proxy.internal:8080", limits=httpx.Limits(max_connections=50, max_keepalive_connections=10), timeout=httpx.Timeout(120.0, connect=10.0), ) pa = Pareta(api_key="pareta_sk_…", http_client=my_client) ``` The TS SDK has no owned HTTP client — it uses the global `fetch`. To control the transport (proxy, custom pool, mTLS, test doubles), inject your own `fetch` implementation via `fetch:`. In Node, a proxy/pool is configured on an undici `Agent` and threaded through a wrapper fetch: **TypeScript** ```typescript import { Pareta } from "pareta"; import { ProxyAgent } from "undici"; // Route through a corporate proxy with a tuned connection pool. const agent = new ProxyAgent({ uri: "http://proxy.internal:8080", connections: 50, // pool size }); const myFetch: typeof fetch = (input, init) => fetch(input, { ...init, dispatcher: agent } as RequestInit); const pa = new Pareta({ apiKey: "pareta_sk_…", fetch: myFetch }); ``` There is a single client, so there is no separate async variant to configure — the same injected `fetch` serves every awaited call. **Ownership matters.** When you inject a client, you own its lifecycle. `pa.close()` (or `await pa.aclose()`) will *not* close a client you passed in. Close it yourself: **Python** ```python my_client.close() # you opened it, you close it ``` **TypeScript** ```typescript await agent.close(); // you opened it, you close it ``` The TS SDK owns no connection pool of its own, so there is nothing on the client to close — only your injected transport (if any). The Python context-manager forms below rely on the SDK-owned client. One caveat: an injected client carries its own timeout configuration. The constructor's `timeout` argument is applied to the SDK-owned client only, so set the timeout on your own client when you bring one. ## Lifecycle and cleanup Each client owns an HTTP connection pool. Release it when you are done. ### Sync Use the context manager so cleanup happens automatically: **Python** ```python from pareta import Pareta with Pareta.from_env() as pa: completion = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": "Extract the parties."}], ) print(completion.choices[0].message.content) # HTTP client closed on exit ``` The TS client owns no connection pool, so there is no context manager and nothing to close — just construct it and `await` your calls: **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); const completion = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Extract the parties." }], }); console.log(completion.choices[0].message.content); ``` Or close it explicitly: **Python** ```python pa = Pareta.from_env() try: pa.models.list() finally: pa.close() ``` **TypeScript** ```typescript import { Pareta } from "pareta"; // No close() — the client holds no pool of its own. const pa = Pareta.fromEnv(); await pa.models.list(); ``` ### Async **Python** ```python from pareta import AsyncPareta async def main(): async with AsyncPareta.from_env() as pa: models = await pa.models.list() print(models) # HTTP client closed on exit ``` **TypeScript** ```typescript import { Pareta } from "pareta"; // One client; every call is already async. No async variant, no aclose(). const pa = Pareta.fromEnv(); const models = await pa.models.list(); console.log(models); ``` Or close it explicitly with `await pa.aclose()`. Remember the ownership rule: if you passed `http_client=`, neither `close()` nor exiting the context manager touches it. Close your own client. ## Platform truths worth knowing These hold no matter how you configure the client. They are why there is no GPU knob, no balance API, and no model catalog to wire up. - **GPUs are hidden.** You configure a key, a URL, timeouts, and retries — never hardware. The serving stack behind `model="auto"` (GPUs, tensor-parallelism, quantization) is Pareta's job, resolved per request. There is no hardware parameter anywhere in the SDK. - **There is one model id.** `models.list()` returns exactly one entry — `"auto"`. "Which model?" is the question Pareta answers for you, per request. Frontier vendor ids (`gpt-5.5`, …) appear only in eval and comparison contexts, as baselines. See [Core concepts](core-concepts.md). - **Inference and evals are metered against your org balance.** A successful `chat.completions.create()` debits your balance once per request — however many internal model calls auto's plan makes, orchestration overhead is Pareta's cost, not yours. `evals.runs.create()` debits for the run's compute (auto and frontier alike). `run.cost` reports the billed total as a `Decimal` in dollars (floored to whole cents), and `run.cost_micro_usd` the raw micro-USD. When the balance hits zero, both paths raise `InsufficientCreditsError` (402). Top-up is browser-only — the SDK exposes neither balance nor payment methods, by design. See [Evals](evaluation.md). - **Inference is OpenAI-compatible.** `base_url` plus your `pareta_sk_…` key is a drop-in OpenAI endpoint — point the `openai` SDK at the same `base_url` and call `model="auto"`. Pareta's SDK adds what `openai` cannot do: evals on your own data and auto's metrics. See [Inference](inference.md). ## Configuration cookbook A few complete, runnable setups. **Production, defaults, env-driven** — the recommended baseline: **Python** ```python from pareta import Pareta with Pareta.from_env() as pa: print(pa.models.list()) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); console.log(await pa.models.list()); ``` **Patient retries, explicit timeout** — for a batch job that should ride out contention: **Python** ```python import httpx from pareta import Pareta pa = Pareta( api_key="pareta_sk_…", timeout=httpx.Timeout(180.0, connect=10.0), max_retries=5, ) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = new Pareta({ apiKey: "pareta_sk_…", timeout: 180_000, // milliseconds maxRetries: 5, }); ``` **Fail fast** — no retries, surface every error on the first attempt (good for tests): **Python** ```python from pareta import Pareta pa = Pareta(api_key="pareta_sk_…", max_retries=0) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = new Pareta({ apiKey: "pareta_sk_…", maxRetries: 0 }); ``` **Async, custom transport** — own the httpx client, own the cleanup: **Python** ```python import asyncio import httpx from pareta import AsyncPareta async def main(): client = httpx.AsyncClient(proxy="http://proxy.internal:8080") pa = AsyncPareta.from_env(http_client=client) try: print(await pa.models.list()) finally: await client.aclose() # you opened it, you close it asyncio.run(main()) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; import { ProxyAgent } from "undici"; const agent = new ProxyAgent({ uri: "http://proxy.internal:8080" }); const fetchViaProxy: typeof fetch = (input, init) => fetch(input, { ...init, dispatcher: agent } as RequestInit); const pa = Pareta.fromEnv({ fetch: fetchViaProxy }); try { console.log(await pa.models.list()); } finally { await agent.close(); // you opened it, you close it } ``` ## See also - [Inference](inference.md) — OpenAI-compatible chat completions, streaming, and metering. - [Core concepts](core-concepts.md) — tasks, `model="auto"`, and how requests are planned and routed. - [Evals](evaluation.md) — benchmark `"auto"` against frontier baselines on your own data, including `run.cost`. - [Errors](errors-and-retries.md) — the full exception hierarchy and how retries interact with it. --- # Medical coding (ICD-10) Turn a clinical discharge summary into ICD-10-CM codes with one chat call. The summary goes to `model="auto"` as plain text; `response_format` with a `json_schema` pins the output to `{"codes": [...]}` — a JSON object holding an array of ICD-10-CM code strings; you parse the object and have structured codes. Medical coding is a text-in, structured-text-out job, so it rides the standard OpenAI-compatible chat surface — the one interface for every text workload. `"auto"` is the only model id; the completion is metered against your org balance, one debit per request regardless of internal routing. ## Setup **Python** ```python from pareta import Pareta pa = Pareta.from_env() # reads PARETA_API_KEY (and optional PARETA_BASE_URL) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // reads PARETA_API_KEY (and optional PARETA_BASE_URL) ``` See [installation](../guide/installation.md) for keys and environment. ## Code a discharge summary The output contract is `response_format`: a `json_schema` declaring `{"codes": [...]}` — an object with one array of code strings. Pareta constrains decoding to that schema on its own specialists and validates every answer against it before delivery, so the content always parses into exactly that shape. The prompt describes the task; schema instructions written only in the prompt are not enforced, so the schema is the contract your code relies on. With `response_format` set, `temperature` is not applied — structured serving runs at its canonical settings. `max_tokens` just needs headroom for the array; 512 covers a typical inpatient stay. **Python** ```python PROMPT = "Assign ICD-10-CM codes for the discharge summary below.\n\n" + DISCHARGE_SUMMARY resp = pa.chat.completions.create( model="auto", response_format={ "type": "json_schema", "json_schema": { "name": "icd_codes", "strict": True, "schema": {"type": "object", "properties": {"codes": {"type": "array", "items": {"type": "string"}}}, "required": ["codes"], "additionalProperties": False}, }, }, messages=[{"role": "user", "content": PROMPT}], max_tokens=512, ) raw = resp.choices[0].message.content or "" ``` **TypeScript** ```typescript const PROMPT = "Assign ICD-10-CM codes for the discharge summary below.\n\n" + DISCHARGE_SUMMARY; const resp = await pa.chat.completions.create({ model: "auto", response_format: { type: "json_schema", json_schema: { name: "icd_codes", strict: true, schema: { type: "object", properties: { codes: { type: "array", items: { type: "string" } } }, required: ["codes"], additionalProperties: false }, }, }, messages: [{ role: "user", content: PROMPT }], max_tokens: 512, }); const raw = resp.choices[0].message.content ?? ""; ``` Full runnable example: [python/icd-coding/icd_coding.py](https://github.com/Pareta-AI/examples/blob/main/python/icd-coding/icd_coding.py) · [typescript/icd-coding/icd-coding.ts](https://github.com/Pareta-AI/examples/blob/main/typescript/icd-coding/icd-coding.ts) ## Parse the codes The content is validated against the schema before delivery, so it is always a bare JSON object — no markdown fence, no prose — and `json.loads` is the whole parser. Keep one guard anyway: check that `codes` really is a list, so a wrong shape fails loudly at the boundary rather than flowing downstream. **Python** ```python import json def parse_codes(text: str) -> list[str]: codes = json.loads(text)["codes"] # schema-conformant JSON, by contract if not isinstance(codes, list): raise ValueError(f"expected a list of codes, got {type(codes).__name__}") return codes for code in parse_codes(raw): print(code) ``` **TypeScript** ```typescript function parseCodes(text: string): string[] { const codes = JSON.parse(text).codes; // schema-conformant JSON, by contract if (!Array.isArray(codes)) throw new Error(`expected a list of codes, got ${typeof codes}`); return codes; } for (const code of parseCodes(raw)) { console.log(code); } ``` Full runnable example: [python/icd-coding/icd_coding.py](https://github.com/Pareta-AI/examples/blob/main/python/icd-coding/icd_coding.py) · [typescript/icd-coding/icd-coding.ts](https://github.com/Pareta-AI/examples/blob/main/typescript/icd-coding/icd-coding.ts) ## Nothing to pick There is no coding model in this example because there is nothing to name: `"auto"` recognizes medical-coding traffic and routes it internally to the right serving path, per request, server-side. Your code stays a plain chat call with a `json_schema` contract — the routing is Pareta's job, not a parameter. Full runnable example: [python/icd-coding/icd_coding.py](https://github.com/Pareta-AI/examples/blob/main/python/icd-coding/icd_coding.py) · [typescript/icd-coding/icd-coding.ts](https://github.com/Pareta-AI/examples/blob/main/typescript/icd-coding/icd-coding.ts) ## See also - [Inference (OpenAI-compatible)](../guide/inference.md) — the full chat surface, streaming, extra params. - [Chat reference](../reference/chat.md) — `chat.completions.create` request and response shapes. - [Streaming chat](./streaming-chat.md) — token-by-token output for long generations. - [Evaluating on your data](./evaluate-on-your-data.md) — benchmark `"auto"` on your own summaries, metered like inference. --- # Retrieval: reranking and embeddings Build search over a small support knowledge base three ways: rerank a candidate list with `pa.rerank(...)`, semantic-search it with `pa.embeddings(...)`, and compose the two into the classic two-stage RAG stack — embeddings for recall, reranking for precision. These are the Retrieval interfaces: `query + documents → ranked list` goes to `rerank`, `text → vectors` goes to `embeddings`. They are dedicated routes because ranked lists and vectors don't fit the chat message contract — not because there is anything to navigate. You never name a serving model on either; Pareta resolves the lane server-side, the same way `model="auto"` does for chat. Rerank is metered per document scored, embeddings per input token, both against your org balance. ## Setup **Python** ```python from pareta import Pareta pa = Pareta.from_env() # reads PARETA_API_KEY (and optional PARETA_BASE_URL) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // reads PARETA_API_KEY (and optional PARETA_BASE_URL) ``` See [installation](../guide/installation.md) if the package isn't set up yet. ## Reranking `rerank(query, documents)` scores every document against the query and returns `(index, relevance_score)` rows, most relevant first. The scores are **calibrated** — each is an independent P(relevant) in (0, 1), not a softmax over the batch — so a fixed cutoff like `>= 0.5` is a real keep/drop filter that means the same thing across calls and corpora. `top_n` truncates the response to the best N, but all documents are still scored (and metered). **Python** ```python KB = [ "Refunds: annual plans are refundable in full within 30 days of purchase...", "Failed payments: a declined charge is retried after 24 hours...", "Seat changes: adding a seat mid-cycle bills the prorated difference...", # ...8 help-center passages in the full example ] ranked = pa.rerank("Can I get my money back if I cancel my annual plan?", KB) print(ranked.pairs) # documents scored — the metered unit for r in ranked.results: # most relevant first print(f"{r.relevance_score:.3f} {KB[r.index][:60]}") # calibrated scores: threshold to filter, not just sort keep = [KB[r.index] for r in ranked.results if r.relevance_score >= 0.5] # top_n truncates the response; top_documents maps indices back to your texts top3 = pa.rerank("Can I get my money back if I cancel my annual plan?", KB, top_n=3) print(top3.top_documents(KB)) # the winning texts, best first ``` **TypeScript** ```typescript const ranked = await pa.rerank("Can I get my money back if I cancel my annual plan?", KB); console.log(ranked.pairs); // documents scored — the metered unit for (const r of ranked.results) { // most relevant first console.log(`${r.relevanceScore.toFixed(3)} ${KB[r.index].slice(0, 60)}`); } // calibrated scores: threshold to filter, not just sort const keep = ranked.results.filter((r) => r.relevanceScore >= 0.5).map((r) => KB[r.index]); // topN truncates the response; topDocuments maps indices back to your texts const top3 = await pa.rerank("Can I get my money back if I cancel my annual plan?", KB, { topN: 3 }); console.log(top3.topDocuments(KB)); // the winning texts, best first ``` Full runnable example: [python/retrieval/rerank.py](https://github.com/Pareta-AI/examples/blob/main/python/retrieval/rerank.py) · [typescript/retrieval/rerank.ts](https://github.com/Pareta-AI/examples/blob/main/typescript/retrieval/rerank.ts) ## Embeddings (semantic search) Embedding is asymmetric: index your passages raw (the default), and embed the incoming question with `input_type="query"` so it gets the retrieval-query treatment. The vectors come back unit-normalized, so cosine similarity is a plain dot product — a one-line function, no vector library needed for a corpus this size. **Python** ```python def dot(a, b): # unit vectors: this IS cosine return sum(x * y for x, y in zip(a, b)) # index side: embed all passages in one order-preserving call, raw index = pa.embeddings(KB) doc_vecs = index.vectors print(index.prompt_tokens) # tokens embedded — the metered unit # search side: the query embeds asymmetrically from the passages q = pa.embeddings("can I get a refund on my yearly subscription?", input_type="query").vectors[0] top_k = sorted(range(len(KB)), key=lambda i: dot(q, doc_vecs[i]), reverse=True)[:3] for i in top_k: print(f"{dot(q, doc_vecs[i]):.3f} {KB[i][:60]}") ``` **TypeScript** ```typescript const dot = (a: number[], b: number[]) => a.reduce((s, v, i) => s + v * b[i], 0); // index side: embed all passages in one order-preserving call, raw const index = await pa.embeddings(KB); const docVecs = index.vectors; console.log(index.promptTokens); // tokens embedded — the metered unit // search side: the query embeds asymmetrically from the passages const q = (await pa.embeddings("can I get a refund on my yearly subscription?", { inputType: "query" })).vectors[0]; const topK = KB.map((_, i) => i) .sort((a, b) => dot(q, docVecs[b]) - dot(q, docVecs[a])) .slice(0, 3); for (const i of topK) { console.log(`${dot(q, docVecs[i]).toFixed(3)} ${KB[i].slice(0, 60)}`); } ``` Full runnable example: [python/retrieval/semantic_search.py](https://github.com/Pareta-AI/examples/blob/main/python/retrieval/semantic_search.py) · [typescript/retrieval/semantic-search.ts](https://github.com/Pareta-AI/examples/blob/main/typescript/retrieval/semantic-search.ts) ## The two-stage RAG stack The two lanes have complementary jobs. Embeddings are the **recall** stage: a cheap, per-token wide net that scans the whole corpus and won't miss a relevant passage phrased nothing like the question. The reranker is the **precision** stage: a per-document scorer that reads each (query, candidate) pair closely and is far better at deciding what actually answers the question — too expensive for the whole corpus, exactly right for the shortlist. So: embed-retrieve a wide top-K, rerank only those, keep the calibrated winners. **Python** ```python # stage 1 — recall: cosine top-5 over the whole corpus doc_vecs = pa.embeddings(KB).vectors q = pa.embeddings(QUERY, input_type="query").vectors[0] candidates = sorted(range(len(KB)), key=lambda i: dot(q, doc_vecs[i]), reverse=True)[:5] # stage 2 — precision: rerank only the 5 candidates (5 metered, not 8) pool = [KB[i] for i in candidates] ranked = pa.rerank(QUERY, pool, top_n=2) for r in ranked.results: # r.index points into pool; print(f"{r.relevance_score:.3f} {pool[r.index]}") # candidates[r.index] recovers the KB index ``` **TypeScript** ```typescript // stage 1 — recall: cosine top-5 over the whole corpus const docVecs = (await pa.embeddings(KB)).vectors; const q = (await pa.embeddings(QUERY, { inputType: "query" })).vectors[0]; const candidates = KB.map((_, i) => i) .sort((a, b) => dot(q, docVecs[b]) - dot(q, docVecs[a])) .slice(0, 5); // stage 2 — precision: rerank only the 5 candidates (5 metered, not 8) const pool = candidates.map((i) => KB[i]); const ranked = await pa.rerank(QUERY, pool, { topN: 2 }); for (const r of ranked.results) { // r.index points into pool; console.log(`${r.relevanceScore.toFixed(3)} ${pool[r.index]}`); // candidates[r.index] recovers the KB index } ``` Full runnable example: [python/retrieval/rag_search.py](https://github.com/Pareta-AI/examples/blob/main/python/retrieval/rag_search.py) · [typescript/retrieval/rag-search.ts](https://github.com/Pareta-AI/examples/blob/main/typescript/retrieval/rag-search.ts) ## See also - [rerank reference](../reference/rerank.md) — the full `Rerank` object, limits, and calibration notes. - [embeddings reference](../reference/embeddings.md) — the `Embeddings` object and input limits. - [Inference](../guide/inference.md) — `model="auto"` chat, the lane the retrieved context usually feeds. - Prove it on your own data: [evaluate on your data](./evaluate-on-your-data.md) benchmarks both retrieval stages against your own graded relevance. --- # Extraction: documents and contracts Pull structured fields out of documents — a scanned invoice, a PDF, a contract — and get JSON back. You'll extract vendor/total/line-items from a real invoice image, then key legal fields from a contract's text. Extraction is a chat job: image or text in, JSON out, so it all goes through `chat.completions.create(model="auto")`, OpenAI-compatible on the wire. One interface, whatever the document looks like; each request is one debit against the org balance regardless of internal routing. ## Setup Install the SDK ([installation guide](../guide/installation.md)) and set `PARETA_API_KEY`. **Python** ```python from pareta import Pareta pa = Pareta.from_env() # reads PARETA_API_KEY (and optional PARETA_BASE_URL) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // reads PARETA_API_KEY (and optional PARETA_BASE_URL) ``` ## Visual documents (images and PDFs) A visual document goes in as OpenAI content parts: one `text` part stating the fields you want, one `image_url` part carrying the pixels as a base64 data URI. Send the field schema as `response_format` on every call whose output your code parses: the prompt describes the task, but schema instructions in the prompt alone are not enforced — the `json_schema` is the contract Pareta constrains decoding to and validates before delivery, so the response parses without ceremony. This example downloads a real invoice from the public examples dataset and extracts five fields from it. **Python** ```python import base64, json, urllib.request INVOICE_FORMAT = { # the output contract "type": "json_schema", "json_schema": { "name": "invoice_fields", "schema": { "type": "object", "properties": { "vendor": {"type": "string"}, "invoice_no": {"type": "string"}, "date": {"type": "string"}, "total": {"type": "number"}, "line_items": { "type": "array", "items": { "type": "object", "properties": { "description": {"type": "string"}, "quantity": {"type": "number"}, "amount": {"type": "number"}, }, "required": ["description", "amount"], "additionalProperties": False, }, }, }, "required": ["vendor", "invoice_no", "date", "total", "line_items"], "additionalProperties": False, }, }, } url = ("https://raw.githubusercontent.com/Pareta-AI/example-datasets" "/main/invoice-extraction/documents/0.jpg") img_b64 = base64.b64encode(urllib.request.urlopen(url).read()).decode() resp = pa.chat.completions.create( model="auto", messages=[{ "role": "user", "content": [ {"type": "text", "text": "Extract the vendor, invoice number, date, total, " "and line items from this invoice."}, {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img_b64}"}}, ], }], response_format=INVOICE_FORMAT, max_tokens=1024, ) fields = json.loads(resp.choices[0].message.content) # validated against the schema before delivery ``` **TypeScript** ```typescript const INVOICE_FORMAT = { // the output contract type: "json_schema", json_schema: { name: "invoice_fields", schema: { type: "object", properties: { vendor: { type: "string" }, invoice_no: { type: "string" }, date: { type: "string" }, total: { type: "number" }, line_items: { type: "array", items: { type: "object", properties: { description: { type: "string" }, quantity: { type: "number" }, amount: { type: "number" }, }, required: ["description", "amount"], additionalProperties: false, }, }, }, required: ["vendor", "invoice_no", "date", "total", "line_items"], additionalProperties: false, }, }, }; const url = "https://raw.githubusercontent.com/Pareta-AI/example-datasets" + "/main/invoice-extraction/documents/0.jpg"; const imgB64 = Buffer.from(await (await fetch(url)).arrayBuffer()).toString("base64"); const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: [ { type: "text", text: "Extract the vendor, invoice number, date, total, " + "and line items from this invoice." }, { type: "image_url", image_url: { url: `data:image/jpeg;base64,${imgB64}` } }, ], }], response_format: INVOICE_FORMAT, max_tokens: 1024, }); const fields = JSON.parse(resp.choices[0].message.content ?? ""); // validated against the schema before delivery ``` Expected output for that document: ```json { "vendor": "Bradley-Andrade", "invoice_no": "97159829", "date": "2015-09-18", "total": 978.12, "line_items": [ ... ] } ``` ### PDFs You can hand a PDF into the same `image_url` slot. When a base64 data URI declares `application/pdf` — or its decoded bytes start with the `%PDF` magic, so a wrong or missing MIME type is still caught — the platform rasterizes it server-side before inference: the PDF block is replaced with one PNG image block per rendered page, up to the **first 8 pages** (sibling keys like `detail` are preserved on each page). For longer documents, split the PDF or send pre-rasterized page images. A PDF that cannot be rendered returns a 400 with a clear message rather than forwarding raw bytes a vision model would reject. Plain `http(s)` image URLs and URL-encoded (non-base64) data URIs pass through untouched. **Python** ```python pdf_b64 = base64.b64encode(open("contract.pdf", "rb").read()).decode() {"type": "image_url", "image_url": {"url": f"data:application/pdf;base64,{pdf_b64}"}} ``` **TypeScript** ```typescript const pdfB64 = (await readFile("contract.pdf")).toString("base64"); ({ type: "image_url", image_url: { url: `data:application/pdf;base64,${pdfB64}` } }); ``` Full runnable example: [python/extraction/visual_document.py](https://github.com/Pareta-AI/examples/blob/main/python/extraction/visual_document.py) · [typescript/extraction/visual-document.ts](https://github.com/Pareta-AI/examples/blob/main/typescript/extraction/visual-document.ts) ## Contract fields (text) When the document is already text, there is nothing special to do: the contract goes in as ordinary string content on the same chat surface. Declare the fields in the `response_format` schema — that is the enforced contract; the prompt only describes them — and give the model an explicit out (`null`) for anything the text does not state, in the schema (`["string", "null"]`) and in the prompt, otherwise it will guess. Sample contract text from CUAD (Hendrycks et al.), CC-BY-4.0. **Python** ```python import json from pathlib import Path contract_text = Path("data/sample-contract.txt").read_text() CONTRACT_FORMAT = { # the output contract "type": "json_schema", "json_schema": { "name": "contract_fields", "schema": { "type": "object", "properties": { "parties": {"type": "array", "items": {"type": "string"}}, "agreement_date": {"type": ["string", "null"]}, "effective_date": {"type": ["string", "null"]}, "governing_law": {"type": ["string", "null"]}, }, "required": ["parties", "agreement_date", "effective_date", "governing_law"], "additionalProperties": False, }, }, } prompt = ("Extract the parties, agreement date, effective date, and governing law. " "parties is a list of legal entity names; dates are YYYY-MM-DD; " "use null for anything the text does not state.") resp = pa.chat.completions.create( model="auto", messages=[{"role": "user", "content": f"{prompt}\n\n---\n\n{contract_text}"}], response_format=CONTRACT_FORMAT, max_tokens=512, ) fields = json.loads(resp.choices[0].message.content) # validated against the schema before delivery print(fields["parties"], fields["governing_law"]) ``` **TypeScript** ```typescript import { readFile } from "node:fs/promises"; const contractText = await readFile("data/sample-contract.txt", "utf8"); const CONTRACT_FORMAT = { // the output contract type: "json_schema", json_schema: { name: "contract_fields", schema: { type: "object", properties: { parties: { type: "array", items: { type: "string" } }, agreement_date: { type: ["string", "null"] }, effective_date: { type: ["string", "null"] }, governing_law: { type: ["string", "null"] }, }, required: ["parties", "agreement_date", "effective_date", "governing_law"], additionalProperties: false, }, }, }; const prompt = "Extract the parties, agreement date, effective date, and governing law. " + "parties is a list of legal entity names; dates are YYYY-MM-DD; " + "use null for anything the text does not state."; const resp = await pa.chat.completions.create({ model: "auto", messages: [{ role: "user", content: `${prompt}\n\n---\n\n${contractText}` }], response_format: CONTRACT_FORMAT, max_tokens: 512, }); const fields = JSON.parse(resp.choices[0].message.content ?? ""); // validated against the schema before delivery console.log(fields.parties, fields.governing_law); ``` Full runnable example: [python/extraction/contract_fields.py](https://github.com/Pareta-AI/examples/blob/main/python/extraction/contract_fields.py) · [typescript/extraction/contract-fields.ts](https://github.com/Pareta-AI/examples/blob/main/typescript/extraction/contract-fields.ts) ## See also - [Inference (OpenAI-compatible)](../guide/inference.md) — the full chat surface: streaming, extra params, error handling. - [Chat reference](../reference/chat.md) — `chat.completions.create` request and response shapes. - [Document extraction end-to-end](./document-extraction.md) — the full document workflow, from your own files to production. - Prove it on your own data: [evaluate on your data](./evaluate-on-your-data.md) — benchmark `"auto"` against frontier baselines on your own documents before you commit. --- # Text classification Turn `model="auto"` into a production text classifier: a closed label set declared as an `enum` in `response_format`, a few labeled examples, and a label your code can branch on. This page builds two of them — a banking-support intent classifier and a hate-speech moderation gate that routes violations to human review. Classification is a chat-shaped job, so it goes to the one chat interface: `pa.chat.completions.create(model="auto", ...)`, OpenAI-compatible on the wire. There is nothing to pick and nothing to deploy — auto routes every request server-side, and each call is one metered debit against your org balance regardless of internal routing. ## Setup **Python** ```python from pareta import Pareta pa = Pareta.from_env() # reads PARETA_API_KEY (and optional PARETA_BASE_URL) ``` **TypeScript** ```typescript import { Pareta } from "pareta"; const pa = Pareta.fromEnv(); // reads PARETA_API_KEY (and optional PARETA_BASE_URL) ``` See [installation](../guide/installation.md) for getting the SDK and key in place. ## Intent classification The `response_format` schema is the contract: its `enum` lists every allowed label, Pareta constrains decoding to it and validates the answer against it before delivery, so the label is a member of the set by construction. The system prompt describes the task, but schema instructions written only in the prompt are not enforced — the schema is. The few-shot pairs are the part worth your attention — on pattern tasks like intent routing, the examples in the prompt move accuracy far more than any sampling knob. When the classifier keeps confusing two intents, add a pair that shows the right answer; that is the tuning loop. **Python** ```python import json LABELS = ("card_arrival", "card_not_working", "lost_or_stolen_card", "transfer_failed", "balance_inquiry", "exchange_rate", "top_up_failed", "other") LABEL_FORMAT = { # the output contract "type": "json_schema", "json_schema": { "name": "intent_label", "schema": { "type": "object", "properties": {"label": {"type": "string", "enum": list(LABELS)}}, "required": ["label"], "additionalProperties": False, }, }, } SYSTEM = ( "You classify banking-support messages into exactly one intent label: " + ", ".join(LABELS) + ". If no label fits, use: other." ) FEW_SHOT = ( # the lever on pattern tasks — swap pairs to steer the classifier ("My new card was supposed to arrive two weeks ago and it still hasn't", "card_arrival"), ("The shop terminal declined my card even though my account has money", "card_not_working"), ("I made a transfer to my landlord yesterday and it bounced back", "transfer_failed"), ) def classify(text: str) -> str: messages = [{"role": "system", "content": SYSTEM}] for user, label in FEW_SHOT: messages.append({"role": "user", "content": user}) messages.append({"role": "assistant", "content": json.dumps({"label": label})}) messages.append({"role": "user", "content": text}) resp = pa.chat.completions.create( model="auto", messages=messages, response_format=LABEL_FORMAT, ) label = json.loads(resp.choices[0].message.content)["label"] return label if label in LABELS else "other" # closed set — belt and braces ``` **TypeScript** ```typescript const LABELS = ["card_arrival", "card_not_working", "lost_or_stolen_card", "transfer_failed", "balance_inquiry", "exchange_rate", "top_up_failed", "other"] as const; type Label = (typeof LABELS)[number]; const LABEL_FORMAT = { // the output contract type: "json_schema", json_schema: { name: "intent_label", schema: { type: "object", properties: { label: { type: "string", enum: [...LABELS] } }, required: ["label"], additionalProperties: false, }, }, }; const SYSTEM = "You classify banking-support messages into exactly one intent label: " + LABELS.join(", ") + ". If no label fits, use: other."; const FEW_SHOT: Array<[string, Label]> = [ // the lever on pattern tasks ["My new card was supposed to arrive two weeks ago and it still hasn't", "card_arrival"], ["The shop terminal declined my card even though my account has money", "card_not_working"], ["I made a transfer to my landlord yesterday and it bounced back", "transfer_failed"], ]; async function classify(text: string): Promise