Skip to main content
The Python and TypeScript SDKs give you a typed method for every route of the API, and they also retry failed calls safely, import documents in batches, read the events feed and verify webhooks. Each SDK is a thin client, so anything it sends you can send with curl to https://api.brussle.com/v1. Its types come from the OpenAPI document behind the API reference. It has no cache, never validates a response, and checks only the inputs this page names.

Create a client

The client takes these options beside the key:

Methods

Each method has the name of its route. TypeScript uses the same names in camelCase and takes the keyword arguments as one object, so ns.suggest_relations(kind="invoice") is ns.suggestRelations({ kind: "invoice" }) and Client(api_key=...) is new Client({ apiKey }). A name in brackets after a Python one is its TypeScript form.
The other routes, with their Python methods: In TypeScript, ns.image(digest) returns { bytes, type }, and the credential methods take the namespace as an option: db.credentials.get("openai", { namespace }). sign_up() (signUp()) creates an organization and a key scoped to default/quickstart for a coding agent with no key. Build a client on its api_key. It sends one request and never retries, since a second request makes a second organization. The SDKs send each / in a namespace name or document id as %2F. They refuse an id or name that is empty, . or .. with ValueError (TypeError) before sending anything, since a URL reads each of those as another path. For a template, make a handle on a prefix that ends in /*, such as db.namespace("acme/prod/*").

Calibrate a judgment

These methods read and steer the correction fitted on your outcomes. Brussle never bills reading fits or starting runs.
  • calibration(name): the calibration report, before and after the correction, per engine epoch.
  • fit_calibration(name) (fitCalibration): a run now instead of at the next scheduled one (fit now), whose result you read a minute or two later. Brussle accepts one request an hour per judgment, named runs included, and within that hour answers rate_limited with Retry-After.
    • With label and optional outcomes: a named run on the outcomes you choose by source and observed time, which answers read only once you pin one of its fits. outcomes without label is invalid_request.
    • With promote=True ({ promote: true }): the run makes its new fit current for every version and epoch that is not pinned (tenants included), even if it is not clearly better. If other judgments read a judgment with features, the response without confirm is the downstream estimate, and confirm=True queues the run (even within the hour) and re-judges them, billed. Python raises ValueError for promote with label or outcomes.
  • calibration_fits(name, version=..., engine_version=..., since=..., cause=..., cursor=...): every fit of every run, newest first, one row per version and engine epoch. current marks what answers read now, and fit is null where the fit did not beat the engine’s numbers. TypeScript keeps the query names, as in calibrationFits(name, { engine_version }).
  • calibration_fit(name, fit): one fit by its fit_… id, with the terms and raw-value range that reproduce any number it corrected.
  • compare_calibration_fits(name, fit, with_fit): two fits of one version and epoch scored on the same outcomes. difference is fit minus with_fit in log loss, with its standard error, so a positive difference favours with_fit. Brussle accepts one compare per judgment a minute.
  • update(name, calibration={"pins": [...]}): pin fits. The list replaces the pins whole, so {"pins": []} lifts them all.
  • alternatives(name) and the other alternatives methods: let your outcomes choose an engine, wording or recipe, and nothing switches until you create a version from one.

Bring your own model

With your own key for a provider, a judgment can run on one of that provider’s models instead of an included engine. Store the key with credentials.set, for one namespace or for your whole organization, and name the model as <provider>/<model id> at current. Brussle tests the key on the provider before it stores it, keeps it sealed and never returns it, so no response and no error carries it.
  • The provider must be active. db.engines.list() lists each provider under providers, and a judgment can name one of its models only while its status is active. No provider is active yet, so until one is, a create that names a model on your own key is refused.
  • The name is typed. In TypeScript, EngineName accepts an included engine or ${Provider}/${string}, so { name: "gpt-5.2" } is a type error. Python takes a str, and the API refuses a name it does not know.
  • Each answer names its model. model_id on an answer or evaluation is the provider’s own name for the model that answered, such as a dated snapshot, and null when the provider named none. path on the judgment and on each version says included or customer_key.
  • Text, JSON and embedding columns need your own key. Their answers carry value, and calibration.mode on the judgment is not_applicable, since they have no number to correct.
  • A judgment with no engine gets the namespace’s default_engine, else your key’s default model, else the included engine for its type.
See your own model for what happens when a key stops working, and each provider’s page (such as openai) for its limits and where your data goes.

Send the API’s JSON

Bodies keep the API’s field names in both languages (such as wait_for and top_k), so any JSON body from these docs or the dashboard’s query builder works unchanged. The one exception is ns.outcomes.append, which takes the array that goes under outcomes instead of the whole body. Options outside the body follow each language, so include_history=True is { includeHistory: true }, a get’s include=history,context,raw is one flag for each part (include_history, include_context and include_raw), and likewise idempotency_key, wait_timeout, the import options and the events feed’s namespace_prefix. The types are strict. Answers and definitions are unions discriminated on type (bool, choice, score, text, json and embedding), so in TypeScript answer.p type-checks only after answer.type === "bool". Filters are typed tuples ([field, op, value], ["And" | "Or", [...]] or ["Not", filter]), and an unknown operator is a type error. mypy cannot check a nested tuple literal, so in Python build them with And, Or and Not:
Python responses are plain dicts typed by brussle.types, and nothing is validated at runtime, so a field or enum value the API adds later does not break your client.

Errors and retries

An error response becomes an ApiError with status, code (such as budget_exceeded or too_large), message and details. A response that is not the API’s JSON (such as a proxy’s error page) gets the code unknown and a generic message, with details.request_id when there is one. Once the retries run out, the SDK raises a network error as it is, and in Python a timeout too (the client’s timeout, 60 seconds by default). Each call retries two times at most (max_retries, maxRetries, on the client), and every call is safe to retry:
  • A read: each GET, query and subscription query.
  • A write, which is idempotent by design.
  • Posting outcomes: the same outcome posted again (same document, judgment, value and observed_at) is stored once.
  • Marking or unmarking a non-production prefix, updating a subscription or a webhook endpoint, and recovering an endpoint’s deliveries, which change nothing when repeated.
  • Storing a provider key, since the same key again returns the stored credential and runs no second test, and revoking one, since a second revoke gives the first one’s answer.
  • Every other call, such as a create, a judgment PATCH, a delete, a backfill confirm or a draw, sends an idempotency key, yours or one the SDK makes.
The SDKs retry:
  • 429 or 503 with Retry-After, after that wait. A Retry-After over 60 seconds (MAX_RETRY_AFTER_SECONDS) returns the error at once. A used-up daily allowance has no Retry-After, and details.resets_at says when it renews.
  • Network errors, timeouts, 502, 503 and 504, after a wait of up to 0.5 seconds that doubles on each retry up to 8 seconds, with jitter, or after a Retry-After of at most 60 seconds. The response may have been lost, and if the call succeeded, a retry with its key gets that response back.
  • 500, the same way, only for a call safe without a key, since after its own error the API no longer holds the key and a retry would run the call again.
Every other error returns at once. The SDKs never retry too_large (413), since a write past a namespace’s size or attribute-name limit fails until you change the write or the namespace. Plan for three cases:
  • Rate limits. A 429 from a rate limit has details.rate_limit, which is per_key, or per_org for all your keys and processes together (so a retry can meet 429 again). When retries run out, send fewer requests overall, or ask for a higher limit.
  • New namespaces. Creating a namespace past your organization’s 1,000 a minute gets rate_limited with a Retry-After until the next minute, so raise max_retries or create fewer.
  • Long requests. A request past the request time gets unavailable (503) with Retry-After, and the SDK retries it. A judgment create, PATCH or backfill that got this error changed nothing, so the retry makes the change once.

Changes that become jobs

A judgment create, PATCH or backfill answers 202 with a job that finishes it when estimating its cost takes more than 20 seconds (when a change takes long). ns.judgments.create, update and backfill wait for the job by default, reading it after each Retry-After (or after 1 second, doubling up to 10). They return what a fast request would have, or raise the same ApiError. They raise JobWaitTimeoutError, which holds the job, after 10 minutes or wait_timeout= seconds ({ waitTimeoutMs } as the last argument). The request goes on, so wait again with db.jobs.wait(error.job["id"]) (db.jobs.wait(error.job)), which takes timeout= ({ timeoutMs }). With wait=False ({ wait: false }) the call returns at once, with accepted: false and the result of a request that finished in time, or accepted: true and the job.

Idempotency keys

An idempotency key (sent as the Idempotency-Key header) makes a call that changes something safe to retry. If you send none, the SDK makes one for each call not safe as it is, sends it on each retry, and makes a new one for the next call. Give your own key when you retry a call yourself (for example after a restart), as in ns.judgments.backfill("settles", confirm=True, idempotency_key="backfill-settles-v4"), or with { idempotencyKey } as the last argument in TypeScript. Use one key per logical request, and reuse it only for its retries.
  • A retry gets the first response. Brussle keeps a successful response for 24 hours, and a call with the same key and arguments gets it back unchanged, marked Idempotent-Replayed: true, without running. A retried create returns the version the first call made, a backfill confirm its job, a draw its leased documents, and a rotation its secret.
  • A failed call runs again. Brussle keeps only a successful response.
  • One key, one request. A key belongs to one route and set of arguments in your organization, so the same key with other arguments gets idempotency_key_reused (422) while the first call runs or its response is kept.
  • A retry while the first call runs gets rate_limited with Retry-After: 1 without running, so the SDKs wait and retry, and get the first call’s response once it is done.
  • Keys are 1 to 255 visible ASCII characters, and anything else gets invalid_request.
A write needs no key, since a retried append adds nothing while its values are still in the array and a retried upsert or patch sets the same content again. On a write, a key prevents the second write only when the first succeeded. See what you can rely on.

Importing documents

ns.import_documents(documents) (ns.importDocuments) upserts a large set of documents, reading documents as it goes from any iterable (or, in TypeScript, async iterable), so the import never has to fit in memory.
  • Batches of up to 1,000 documents or 64 MB, the most one write takes.
  • concurrency writes at once, 4 by default, which Python sends from a thread pool.
  • Retries follow the client’s rules, with one idempotency key per batch. Each import makes new keys, so calling import_documents again with the same documents writes them all again: each gets a new revision, and you pay its write bytes again, although an answer whose context did not change is kept with no engine call. To finish an import that stopped, send only the documents it had not written.
  • Repeated ids. A document whose id is still being written waits for that write, so the later of two documents with one id stays.
  • Failures. A batch that still fails after its retries is recorded and the import goes on, unless stop_on_failure=True (stopOnFailure: true), which starts no batch after the first failure.
  • Progress. on_progress (onProgress) gets the totals so far after each batch.
The summary has documents and batches written, revision, failures (each failed batch’s ids and error) and stopped. Its revision is the highest a batch returned, so a judgment whose judged_through reaches it has finished with the import (is a judgment caught up?). A write commits all its documents or none, so fix the cause and write a failed batch’s ids again. See import existing data.

Webhooks and events

A subscription (a saved query) sends subscription.entered when a document starts to match and, if you ask, subscription.exited when it stops. Platform events such as job.completed go to each endpoint whose events patterns match. Every event but a test send also goes to the events feed. See webhooks.
Creating an endpoint returns its secret, so keep it where your receiver can read it. rotate_secret (rotateSecret) returns a new one, and the old one keeps signing beside it for previous_valid_for (24 hours by default), so receivers can switch without missing an event.

The events feed

db.events.list(...) returns one page, oldest event first, with a next_cursor even when the page is empty. db.events.iterate(...) follows next_cursor and yields each event until a page is empty. Both take cursor, limit (1 to 1,000, 100 by default), types (patterns such as job.*) and namespace_prefix (namespacePrefix). An event’s id is also a cursor, so store the last one you handled and continue after it. Brussle keeps events for 30 days. An older cursor fails with invalid_request and details.reason cursor_expired, so read the current state again (a subscription’s query) and start without a cursor. See the events feed.

Verifying webhooks

verify_webhook(payload, headers, secret) (verifyWebhook) checks that a delivery came from Brussle and returns the parsed event. It checks the signature (Standard Webhooks, HMAC-SHA256) and that webhook-timestamp is within 5 minutes of your clock, or tolerance= seconds ({ toleranceSeconds }). secret can be a list. Python needs only the SDK, and TypeScript only WebCrypto, so it runs on edge runtimes. A request that fails a check raises WebhookVerificationError with a reason of headers, timestamp or signature, and you answer it with 400. An empty or malformed secret, or an empty list, raises ValueError (TypeError) before any check, so it never verifies a request. Flask and Next.js receivers are in webhooks, and FastAPI and Express receivers follow.
Pass the raw body, exactly the bytes you received. JSON parsed and serialized again can change spacing or key order, and then the signature does not match.
The event is a WebhookEvent, a union discriminated on type, so checking type narrows data. A test send has test set to true. Brussle can add event types, so ignore the ones you do not handle:
Brussle delivers each event at least once, and deliveries can arrive out of order. Remove duplicates by the event’s id (which the webhook-id header repeats). Ignore an event whose data.sequence is lower than one you already handled for the same subscription and document.