Using api.saina.run
How to go from a purchase to a working call, what you are charged for, and how to retry safely. The request and response format of /v1/ask is the same as a self-hosted server; this page covers what the hosted service adds.
In short: sign up, open the sign-in link, create a key in the console, and send Authorization: Bearer $SAINA_API_KEY. You pay for input tokens; output is free. Send a UUIDv7 Idempotency-Key if you retry, and a retry is never charged twice.
- From sign-up to first call
- Authentication
- How input tokens are counted
- Credits and pricing
- The playground
- Limits
- Retries and idempotency
- Response headers
- Error codes
- Balance and usage endpoints
- What the model supports
- Images and audio
- Answer types and examples
- Thresholds and fallback
- Specialists
- Keep calls in Studio
- Data retention
- Support
From sign-up to first call
- Sign up at saina.run/signup with your email. We send a sign-in link; there is no password. The free plan grants one credit (10,000 input tokens) on each UTC day you use it; each grant lasts 30 days.
- Open the sign-in email. Click Sign in on the page it opens. The link works once and expires after 15 minutes; if it expired, request a new one on the login page. Use the daily free credit to start; add credits in the console if needed.
- Create a key under Keys in the console. The full key is shown once. Copy it into your secret store or an environment variable.
- Call the API:
export SAINA_API_KEY='YOUR_API_KEY' # replace with a key from the console
curl https://api.saina.run/v1/ask \
-H "Authorization: Bearer $SAINA_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "saina-helm-2-0.8b",
"state": "I was charged twice for my subscription this month.",
"questions": {
"team": {"type": "single_choice", "question": "Which team should handle this?",
"options": {"billing": "Billing", "technical": "Technical support"}},
"urgent": {"type": "yes_no", "question": "Does this need a reply today?"}
}
}'
The response holds the answers and usage.input_tokens. The X-Saina-Credits-Charged and X-Saina-Balance headers show what this call cost and the balance after it. The same call from Python, JavaScript or n8n is one click away in the console playground's Code panel.
Already a customer? Buy more from the Billing tab of the console; credits go to the account you are signed in to.
One input, four answer types
Send this body to POST /v1/ask using the authentication in the quick start. Distribution mode is the default. These examples use the native SDK field names.
{
"model": "saina-helm-2-0.8b",
"state": "I was charged twice for my subscription. Please refund the duplicate today.",
"questions": {
"team": {
"type": "single_choice",
"question": "Which team should handle this?",
"options": {
"billing": null,
"technical": null,
"sales": null
}
},
"refund": {
"type": "yes_no",
"question": "Is a refund explicitly requested?"
},
"urgency": {
"type": "rating",
"question": "How urgent is the request?",
"levels": [
"Routine",
"Soon",
"Today"
]
},
"topics": {
"type": "multi_choice",
"question": "Which topics apply?",
"options": {
"billing": null,
"refund": null,
"technical": null
}
}
}
}
Illustrative answers fragment, checked against the SDK contract. These scores demonstrate the response structure; they are not measured predictions for this input. Your response also includes model and usage.
{
"answers": {
"team": {
"type": "single_choice",
"probabilities": {
"billing": 0.9,
"technical": 0.06,
"sales": 0.04
},
"selection": "billing",
"confidence": 0.85
},
"refund": {
"type": "yes_no",
"yes": 0.9,
"no": 0.1,
"confidence": 0.8
},
"urgency": {
"type": "rating",
"probabilities": {
"0": 0.1,
"1": 0.5,
"2": 0.4
},
"expected_level": 1.3,
"levels": [
"Routine",
"Soon",
"Today"
],
"confidence": 0.25
},
"topics": {
"type": "multi_choice",
"memberships": {
"billing": 0.9,
"refund": 0.9,
"technical": 0.1
}
}
}
}
single_choice: 2–255 mutually exclusive options. Their probabilities sum to one. Distribution mode names the highest-scoring option inselection.yes_no:yesandnosum to one. A decision-modeselected: falsemeans an accepted “no”;selected: nullmeans fallback.rating: 2–10 ordered levels, indexed from zero. Hereexpected_levelis 0 × 0.1 + 1 × 0.5 + 2 × 0.4 = 1.3. It is an average over the rubric, not the probability of level 1. Decision mode separately returns an accepted integerlevelor null.multi_choice: 2–255 independent memberships. They can overlap and need not sum to one. Decision mode returns every label whose membership meets the threshold.
The separate confidence field is derived from the distribution. It is not the threshold input or evidence of calibration. Test reliability on held-out examples from your domain.
Thresholds, margins and fallback
Add "mode": "decision" and "threshold": 0.8 to the request. The threshold defaults to 0.8 in decision mode; min_margin defaults to 0. Questions can override the request policy. Threshold and margin fields are not accepted in distribution mode.
For single choice and yes/no, the policy checks for a tie first, then compares the top option probability to the threshold, then compares the top-two probability gap to min_margin. Rating uses the top level probability and tie check, without a margin check. Equality with the threshold or minimum margin passes that check.
| Reason | Meaning |
|---|---|
accepted | The answer meets the decision policy. |
below_threshold | The top option is below the threshold; for multi-choice, no membership meets it. |
below_margin | The top option passes the threshold but its lead over the runner-up is smaller than the required margin. |
tie | The top two options tie (within the SDK's numerical tolerance). |
Illustrative single-choice fallback with threshold 0.80:
{
"answers": {
"team": {
"type": "single_choice",
"probabilities": {
"billing": 0.6,
"technical": 0.3,
"sales": 0.1
},
"selection": null,
"confidence": 0.4,
"reason": "below_threshold"
}
}
}
The API keeps the scores and returns a null selection, selected or level for an unaccepted exclusive answer. Multi-choice returns an empty selections list when nothing qualifies. Your application handles review or another action; fallback does not generate reasoning or invoke a second model.
A valid fallback is a completed, billed inference. An HTTP error such as an invalid request or unavailable service is a separate outcome; see error handling.
Authentication
- API keys look like
sk_saina_followed by 43 characters. Send one asAuthorization: Bearer …. A key can call/v1/ask,/v1/systemoneand/v1/decisionsand read balance, usage and request history. It cannot manage keys, buy credits or delete the account. - Shown once. We store only a hash. The console lists each key by name with the first and last four characters. If you lose a key, revoke it and create another.
- Rotation. Rotating a key issues a new one and keeps the old one working for an overlap you choose (24 hours by default, up to 7 days), so you can update every tool before it stops.
- Revocation takes effect on the next request. A revoked key gets
401 key_revoked. - The console signs you in with an emailed link instead of a password. Creating, rotating or revoking a key and deleting the account need a sign-in from the last 10 minutes; otherwise the console emails you a confirmation link first.
- Lost access? Enter your email on the login page. If an account exists, you get a sign-in link; the page answers the same way either way. From the console you can create a new key or rotate the old one.
How input tokens are counted
You pay for the input tokens in the request you send: the state once, plus each question and its options or levels, including their keys and descriptions. Text is counted as sent; objects and arrays are counted as compact JSON in the order sent, using the tokenizer published for the current price version. Prompt formatting the server adds is not charged.
The context counts once. Helm scores questions in groups of up to 8 that share one read of the state. Adding a question costs only that question and its options, however long the context is. A request with more than 8 questions runs as several groups; the context is still charged once. Each group (context, questions and options, as the model reads them) must fit in 8,192 tokens, or the request is rejected without a charge.
An illustrative example, not a measurement: a 400-token support ticket with three short questions of about 30 tokens each comes to about 400 + 3 × 30 = 490 input tokens, or about $0.00001. The console shows single requests in tokens and dollars.
Output tokens are not charged. The exact count for a request is in usage.input_tokens and in your request history. The console playground counts a request and shows the exact cost before you run it.
Credits and pricing
- Credits pay for input tokens. Usage is metered in tokens and debited from your credits, so a single request usually uses a fraction of a credit. Output tokens are free.
- Plans. Every account has one; the plan sets the credits included and the price of top-ups.
The free plan is limited to 10 requests a minute and 32 questions a request; paid plans get the API limits below. Top-ups come in $5, $10, $25, $50 and $100 packs, or any whole-dollar amount from $5 to $1,000, all at your plan's rate. Current plans and packs are also at
Plan Price Included Top-ups Free $0 1 credit each day you use it, kept 30 days $5 for 10,000 credits Starter $5/month 25,000 credits a month $5 for 25,000 credits Pro $10/month 55,000 credits a month $5 for 27,500 credits Max $100/month 625,000 credits a month $5 for 31,250 credits GET /v1/pricing. - Which credits go first. Credits that expire soonest: the free plan's daily credits (each lasts 30 days), then your plan's monthly credits (they expire when the month renews), then purchased top-ups, which never expire.
- Subscriptions renew monthly. Cancel any time in the console and keep the plan until the month ends. Upgrades start immediately and are prorated; downgrades start at renewal.
- Automatic top-up is optional and off by default: below a threshold you choose, the console buys a top-up with your saved card, up to a monthly limit you set.
- At zero balance, requests return
402 insufficient_creditsuntil credits are added. - What is charged: a completed, valid response, including a decision-mode answer that falls back (
below_threshold,below_margin,tie). A request with several questions is one operation: it finishes completely or it is not charged. - What is not charged: validation errors, rejected requests, rate limits, overload, inference failures, and replays of a result you already paid for.
- Reserved credits. Before a request runs, its counted cost is reserved, and the reservation becomes the charge when it settles. The console shows balance, reserved and available separately.
- Price versions. Each request records the price version it was charged at, so a future price change never alters past charges.
X-Saina-Price-Versionreports it. - Amounts are strings, in tokens. Balance and charge amounts in JSON (
balance,credits_chargedand the like) are decimal strings holding a 64-bit integer, for example"250000000". Parse them as integers (BigIntin JavaScript), not floats. - Invoices and receipts are in the Stripe customer portal, linked from the console's Billing tab.
The playground
The playground is in the console, after you create a free account. It sends the same /v1/ask request format to the hosted model, signed in with your console session instead of an API key.
- Runs are paid. A run is charged like an API call, at the same price, from the same credits. Runs use the same balance, including eligible free daily credits.
- The cost is shown first. When the request is complete, the console counts it and shows the input tokens and the exact cost in dollars. Counting is free and runs no inference. The quote is tied to that exact request and expires after a short time; change the request or wait too long and it is counted again before Run is enabled.
- Charged once. Each run gets its own idempotency key. A double click or a lost connection resends the same run, which the API recognizes and does not charge again. After a run the console shows the charge and the balance at settlement, then refreshes the live balance separately.
- Visible in usage. Playground runs appear in Usage under the
playgroundchannel, with no key and the signed-in user instead. - Drafts stay in your browser. The playground keeps your drafts in this browser's storage. Inputs are never saved on our side.
- The playground has tighter limits than the API (see below). The Code panel turns the current request into curl, Python, JavaScript or an n8n node that targets
https://api.saina.runwith a$SAINA_API_KEYplaceholder.
Limits
Defaults per account. Playground traffic also counts against the API limits.
| Limit | API | Playground |
|---|---|---|
| Request body | 2 MiB | 256 KiB |
| Request body with images or audio | 25 MiB | 25 MiB |
| Questions per request | 256 | 32 |
| Input tokens per request | 2,000,000 | 200,000 |
| Requests per minute | 600 | 60 (30 per session) |
| Input tokens per minute | 20,000,000 | 2,000,000 |
| Concurrent requests | 8 | 2 |
Request bodies may be compressed with Content-Encoding: gzip or zstd (one layer), as the TypeSafe SDKs do by default; the limits apply to the decompressed body.
Each question's prompt must also fit the model's context window; longer inputs are rejected, never truncated. Above a limit you get 429 rate_limited with Retry-After. Cloudflare also limits each IP address to 60 requests per 10 seconds. For more capacity, talk to us.
Retries and idempotency
Without an Idempotency-Key header, every request is a new operation, and a retry after a lost response can be charged twice. To retry safely, send a key:
KEY=$(python3 -c 'import uuid; print(uuid.uuid7())') # Python 3.14+, or any UUIDv7 library curl https://api.saina.run/v1/ask \ -H "Authorization: Bearer $SAINA_API_KEY" \ -H "Idempotency-Key: $KEY" \ -H 'Content-Type: application/json' \ -d @request.json # On a timeout or a dropped connection: send the same command again, with the same $KEY and the same body.
- The key must be a UUIDv7 (RFC 9562), with its timestamp no more than 5 minutes in the future and no more than 24 hours in the past. Anything else is
invalid_request. Generate one key per logical operation, just before you first send it. - Same key, same body, already finished: you get the stored response again, with
X-Saina-Replayed: trueand no new charge. - Same key, still running:
409 request_in_progresswithRetry-After. Wait and send it again. - Same key, different body:
409 idempotency_conflict. Keys are bound to the endpoint and the body (key order and whitespace do not matter). - Same key after a failure returns the recorded failure. To try again, use a new key.
- After 24 hours the stored response is deleted. The key then returns
410 idempotency_result_expiredwith the original request ID and whether it was charged. Nothing runs again. The same 410 can appear earlier if the stored result was lost in a service incident. - After a service recovery, a key we cannot verify returns
409 idempotency_unverifiable. Start a new operation with a new key. If you generate keys ahead of time, expect this after an incident.
When to retry automatically
Retry with the same key and body only for a lost connection or unclear response, accounting_unavailable, request_in_progress, rate_limited, and overloaded or inference_unavailable when the error says "admitted": false. Honor Retry-After, back off exponentially, and stop after a few attempts. Never create a new key for a retry. Everything else needs a decision from you or your code: a new key runs the request again and may be charged again.
Response headers
| Header | Meaning |
|---|---|
X-Request-Id | On every response. Include it when you contact support. |
X-Saina-Credits-Charged | Credits charged for this call, as an integer string. |
X-Saina-Balance | The balance right after this call settled. On a replay, the balance at the original settlement. |
X-Saina-Price-Version | The price version applied. |
X-Saina-Replayed | true when this is a stored result returned for a repeated idempotency key. |
X-Saina-Dialect | On /v1/decisions: openai or systemone, the request shape that was read. |
X-Saina-Task-Stored | When the request names a task: true when Studio stored the call, false when it ran without being stored. |
Error codes
Errors have one shape:
{"error": {"code": "insufficient_credits", "message": "...", "request_id": "req_...",
"admitted": false, "state": "not_admitted", "retry": "no"}}
state says what happened: not_admitted (nothing was recorded or reserved), in_progress, terminal (finished and will not run again under this key) or unknown (retry with the same key and body). retry is same_operation, new_operation or no.
| Code | HTTP | What to do |
|---|---|---|
invalid_api_key | 401 | Check the key. It may have a typo or belong to another environment. |
key_revoked | 401 | The key was revoked. Create a new one in the console. |
account_suspended | 403 | See suspension.next_step: buy_credits means the balance went below zero (often after a refund or dispute) and buying credits lifts it; contact_support means a security review, so email us. |
insufficient_credits | 402 | Buy credits. Nothing was charged. |
invalid_request | 400 / 422 | Fix the request; the message names the field, never its value. |
rate_limited | 429 | Wait for Retry-After, then retry the same operation. |
overloaded | 429 / 503 | With admitted: false (429), retry the same operation after Retry-After. With admitted: true (503), it was stopped and not charged; a new key is needed to run it again. |
inference_failed | 502 | The model failed. Not charged. Use a new key to try again. |
inference_unavailable | 503 | No model capacity right now. Not admitted, not charged. Retry the same operation after Retry-After. |
accounting_unavailable | 503 | Billing is briefly unavailable, so no paid work starts. Retry the same operation. |
idempotency_conflict | 409 | The key was used with a different body. Use a new key for the new request. |
request_in_progress | 409 | Still running. Retry the same operation after Retry-After. |
idempotency_result_expired | 410 | The stored result is gone. The response says whether the original was charged. It does not run again; use a new key if you need a new answer. |
idempotency_unverifiable | 409 | After a service recovery this key cannot be checked. Use a new key. |
quote_stale | 409 | Console playground only: the cost quote expired or no longer matches the request, model revision or price. Nothing was charged. Count again and run with the new quote. |
fresh_auth_required | 403 | Console only: confirm by email link, then repeat the action. |
permission_denied | 403 | The credential cannot do this; for example, an API key on a console-only route. |
not_found | 404 | Check the path or ID. |
Balance and usage endpoints
These accept an API key or a console session:
| Route | Returns |
|---|---|
GET /v1/account/balance | balance, reserved, available, overdraft_allowance, debt and any suspensions. |
GET /v1/account/usage?from=&to=&channel= | Daily totals, computed from the same records that are charged. |
GET /v1/account/requests?from=&to=&key_id=&channel=&status=&cursor=&limit= | Request history: request ID, key, channel, status, input tokens and credits for each request. |
GET /v1/pricing | Public. The current price version and packs. |
The console adds a CSV export of the request history with the same filters. channel is api, playground or openrouter, so playground spend can be told apart from API spend.
What the model supports
- Model:
saina-helm-2-0.8b(Saina Helm 2 0.8B, open weights), with a 262,144-token context, pinned to the revision thatGET /healthzreports. Requests that namesaina-helm,saina-helm-0.8borhelm-0.8bare also answered by Helm 2, and every response names the model that answered. - Model:
saina-helm-2-omni-0.8b(Saina Helm 2 Omni 0.8B, open weights) reads text, images and audio, with a 32,768-token context that includes the images and clips. Name it inmodelto use it;saina-helmstays on Helm 2. - Model:
saina-helm-2-routing-0.8b(text only) chooses an answering model from a request and candidate capabilities and prices. Evaluate quality and total cost on your workload. See the model card. - Question types:
yes_no,single_choice(2 to 255 options),multi_choice(multi-label, 2 to 255 options) andrating(2 to 10 levels). - Distribution mode returns a score for every option. Decision mode applies an option-probability
thresholdandmin_margin, per request or per question, and areasonon every answer:accepted,below_threshold,below_marginortie. POST /v1/systemoneaccepts the System One wire format and is metered and charged the same way. Multi-label questions need/v1/ask. Its limits are Saina's:noul,choicewith 2 to 255criteriaandscorewith 2 to 10 levels, every question withinstructions, up to 256 questions. Images and audio use theimagesandaudiosfields below; theassetsfield andboxquestions are not supported and are refused with422 invalid_requestbefore anything is charged. Unknown model labels are answered by the default model, and the response names it.POST /v1/decisionsaccepts the OpenAI Decisions request shape as well as System One bodies; see Decisions request shape.- The full request and response contract is in the SDK repository, and examples are on the hosted API page.
Decisions request shape
POST /v1/decisions (also at /api/v1/decisions) accepts two request shapes and tells them apart by the body:
- OpenAI Decisions shape:
inputplus aquestionsarray ofpredicate,choiceandscorequestions, as sent byclient.decisions.create()in the OpenAI SDKs. Point the client's base URL athttps://api.saina.run/v1, use a Saina key, and name a Saina model. - System One shape:
stateplus aquestionsobject, answered exactly as on/v1/systemone.
A body that matches both shapes or neither is a 400 invalid_request naming the field. You may send X-Saina-Dialect: openai or systemone to confirm the shape; it never overrides the body, and a header that disagrees is a 400. Responses carry X-Saina-Dialect. Saina is not affiliated with OpenAI or TypeSafe; this route accepts their request shapes, and answers come from Saina Helm.
from openai import OpenAI
client = OpenAI(base_url="https://api.saina.run/v1", api_key=SAINA_API_KEY)
decision = client.decisions.create(
model="saina-helm",
input="I was charged twice for my order. Please refund the extra payment.",
questions=[
{"type": "choice", "name": "department", "instructions": "Which department should handle this complaint?",
"choices": [{"value": "billing", "description": "Payments, invoices, and refunds."},
{"value": "technical", "description": "Problems using the product."},
{"value": "shipping", "description": "Delivery and tracking."},
{"value": "other", "description": "Requests outside these categories."}]},
{"type": "predicate", "name": "refund", "instructions": "Does the customer ask for a refund?"},
{"type": "score", "name": "urgency", "instructions": "How urgent is it?",
"levels": [{"label": "Can wait"}, {"label": "This week"}, {"label": "Today"}]},
],
)
for answer in decision.answers:
print(answer.name, answer.type)
How it maps. Each OpenAI request is translated to the native /v1/ask request and scored and billed exactly as that request: predicate is yes_no (probability is the probability of yes), choice is single_choice (2 to 255 choices; a choice's description is its option description), and score is rating (2 to 10 levels, lowest first; a level is read as label: description). Answers come back in question order with each question's name, or null for an unnamed question. choice and score answers carry probabilities for every option and Saina's confidence, which is derived from the whole distribution: it is not the top probability and not the value a threshold checks. score is the probability-weighted average of the level indices, so it can fall between levels.
Model names are exact. Name saina-helm or a release such as saina-helm-2-0.8b or saina-helm-2-omni-0.8b. Any other name, such as gpt-6-luna or jev-1.14, is a 404 not_found: an answer from a different model than the one named would be misattributed. (/v1/systemone keeps answering unknown System One labels with the default model.)
No refusals unless you ask for them. By default every question gets its full distribution and you apply your own threshold. Send Saina's decision policy as extra fields ("mode": "decision" with threshold and optionally min_margin; in the OpenAI SDKs pass them in extra_body) and an answer the policy does not accept comes back as {"type": "refusal", "name": ..., "reason": "below_threshold", "probabilities": [...]}. reason (below_threshold, below_margin or tie) and the distribution are Saina additions; a predicate refusal carries probability. A refusal is a completed inference and is charged, like a decision-mode fallback on /v1/ask.
Input. input is a string, sent to the model as the state unchanged, or an array of messages (user, developer, system, assistant) and function or custom tool calls and outputs, which becomes a JSON array state in the same order, with text and input_json parts kept as sent, and a tool item's status and an assistant message's phase kept. Tool outputs must follow their call (same call_id).
Images are read by models that read images, such as saina-helm-2-omni-0.8b: each input_image part with a base64 data URL (PNG, JPEG or WebP) becomes one of the request's images, in order, with the limits under Images and audio. As with images on /v1/ask, every question sees every image, and images are read before the text; each image's place in the input is kept as a marker {"image": n} (the n-th image, counted in the input tokens). Refused with a 400 naming the part, before anything is charged: images sent to a text-only model, image URLs (they are not fetched), images inside a question's instructions, and a detail other than auto. An image is never answered from its encoded text.
Not supported, each refused with 400 invalid_request: question types other than predicate, choice and score (including box; multi_choice needs /v1/ask), duplicate question names, a string and a boolean choice value with the same text, sampling parameters such as temperature, top_p and seed, and any other field not listed here. prompt_cache_key, prompt_cache_options, safety_identifier and metadata are accepted and ignored: there is no prompt cache, so usage.input_tokens_details.cached_tokens is always 0.
Pricing. Billed like /v1/ask: input tokens only, counted with Saina's tokenizer (so the count differs from other providers' for the same text), the input once plus each question with its choices or levels. usage.output_tokens is always 0, and total_tokens equals input_tokens. The example above is 65 input tokens (14 for the input, 33 for the choice question, 8 for the predicate, 10 for the score question; measured with the Helm 2 tokenizer). At the Starter rate of $5 for 250 million tokens ($0.02 per million) that is $0.0000013, or about 770,000 such requests per dollar; with a free-plan top-up ($0.05 per million) it is $0.00000325.
Limits, errors, idempotency and headers are those of /v1/ask: up to 256 questions per request (32 on the free plan), not the 400 another provider allows. Every question is checked before any runs, so an invalid question fails the whole request without a charge. An Idempotency-Key is bound to the route and the body, so the same request sent in two shapes, or to /v1/systemone and /v1/decisions, is two operations. Errors use the error shape below, which the OpenAI SDKs raise as BadRequestError, NotFoundError and so on. Request history records these requests as decisions_openai or decisions_systemone.
Images and audio
POST /v1/ask and POST /v1/systemone take two optional top-level fields for models that read more than text, such as saina-helm-2-omni-0.8b. Every question in the request sees every image and clip.
| Field | Each item | Types | Limits |
|---|---|---|---|
images | base64 data URL | image/png, image/jpeg, image/webp | 8 per request, 10 MiB each |
audios | base64 data URL | audio/wav, audio/x-wav, audio/flac, audio/mpeg, audio/ogg, audio/webm | 4 per request, 10 MiB and 10 seconds each |
{
"model": "saina-helm-2-omni-0.8b",
"state": "The customer says the blender arrived cracked and attached the receipt.",
"images": ["data:image/png;base64,iVBORw0KGgo..."],
"questions": { ... }
}
Sizes are of the decoded file; the whole request body may be up to 25 MiB. URLs and file paths are not accepted, and videos is not supported yet. Audio clips longer than 10 seconds are rejected, never cut. Each model lists what it reads in inputs on GET /v1/models (["text"] or, for example, ["text", "image", "audio"]). A model that reads text only rejects images and audio with invalid_request before anything is charged; nothing is dropped silently.
Images and audio are billed as input tokens, counted the way the model reads them: one token per 32 × 32 pixels of each image after it is resized to at most 1.6 megapixels, and the same for each clip's spectrogram (a 10-second clip is 124 tokens). usage.input_tokens includes them.
Specialists
A specialist is a version of a model trained further for one domain. Add "specialist" to a POST /v1/ask or POST /v1/systemone request to have it answer instead of the model itself. Leave the field out and the model answers as usual. The response names both, for example "model": "saina-helm-2-omni-0.8b", "specialist": "mechanical".
| Specialist | Model | Reads | What it is for |
|---|---|---|---|
mechanical | saina-helm-2-omni-0.8b | text, audio | Whether a machine sounds normal and which fault it most likely has, from a recording: bearings, electric motors (normal or faulty), air compressors and 3D printers (open weights) |
{
"model": "saina-helm-2-omni-0.8b",
"specialist": "mechanical",
"state": "The clip is a recording of a rolling-element bearing on a test rig at 1,750 rpm, recorded with a phone.",
"audios": ["data:audio/wav;base64,UklGRi..."],
"questions": {
"condition": { "type": "single_choice", "question": "Which condition does the machine in this clip have?",
"options": { "healthy": null, "inner": "Inner race bearing fault", "outer": "Outer race bearing fault", "ball": "Ball (rolling element) fault" } },
"normal": { "type": "yes_no", "question": "Is the machine operating normally (no fault or anomaly audible)?" }
}
}
A specialist costs the same per input token as its model, and its context, media limits and response headers are the same. GET /v1/specialists lists the specialists of every served model with what each one reads, and GET /v1/models lists each model's specialists in specialists. An unknown specialist is not_found and a specialist that does not read images rejects them with invalid_request; in both cases nothing is charged.
Keep calls in Studio
Add "task" to a POST /v1/ask, POST /v1/systemone or POST /v1/decisions request to keep the call in Saina Studio. Studio stores the state, questions and answers, and files the call under an automatic endpoint with the task's name. Leave the field out and nothing is stored, as before. OpenAI SDK callers send task in extra_body.
{
"model": "saina-helm-2-0.8b",
"task": "route-ticket",
"state": "I was charged twice for my order.",
"questions": {
"team": { "type": "single_choice", "question": "Which team should handle this?", "options": { "billing": null, "support": null } }
}
}
The response adds decision_id and collection_id. Use the decision ID to report business outcomes for the call. A task name is 3–64 lowercase letters, numbers or hyphens, starting and ending with a letter or number. trace_collection_id stores the call in another collection; the default is saina-decisions. The task costs nothing: the call is charged as if it had no task. A replay with the same idempotency key returns the same IDs, and the same key with another task is idempotency_conflict.
An automatic endpoint groups calls only. It has no version and does not answer requests. In Studio it shows the calls, the models they used and each set of questions sent. Save as endpoint turns it into an ordinary endpoint at v1. Calls with that task keep filing under it after saving. A call with a multi_choice question or more than 32 questions runs and is charged as usual, but is not stored (X-Saina-Task-Stored: false). Studio stores the call after the answer is sent, so storage never delays the answer. If storage fails, the call is still answered and charged but does not appear in Studio.
Collect decision traces
TraceClient in the Python saina SDK and TypeScript @run-saina/sdk collects decisions made by your own application. Declare the inputs and answer to retain. Your code executes the decision; capture sends evidence to a collection in background batches. Database handles, credentials and other function arguments are not inspected. No Saina endpoint is required.
SDK 1.0 release candidate adds immutable typed answers, local selection, and durable Traces.log(). Python and Node clients commit each record to a local SQLite spool before returning its ID, then deliver to POST /v1/traces with account-scoped deduplication. Node durable logging requires Node 22.13 or later. Keep the spool directory across process restarts; call flush() and close() during shutdown. Individually rejected records remain available for explicit recovery.
Python trace capture is included in SDK 0.10.0; TypeScript trace capture is included in SDK 0.5.0. The coordinated staging release provides the Python wheel and npm tarball built with this backend. Install the downloaded wheel with pip install ./saina-1.0.0rc1-py3-none-any.whl or tarball with npm install ./run-saina-sdk-1.0.0-rc.1.tgz.
Python context manager
import os
from saina import TraceClient
with TraceClient(
collection="support-routing",
source="support-agent",
api_key=os.environ["SAINA_API_KEY"],
base_url="https://api.saina.run",
) as traces:
with traces.decision(
task="route-ticket",
inputs={"message": ticket["message"]},
) as trace:
answer = your_agent.route(ticket, db, config)
trace.set_answer(answer)
For async code, use async with traces.decision(...), await traces.aflush() and await traces.aclose(). The client also supports async with TraceClient(...).
TypeScript callback scope
import {TraceClient} from "@run-saina/sdk";
const traces = new TraceClient({
collection: "support-routing",
source: "support-agent",
apiKey: process.env.SAINA_API_KEY,
baseUrl: "https://api.saina.run",
});
try {
const answer = await traces.decision(
{task: "route-ticket", inputs: {message: ticket.message}},
async trace => {
const answer = await yourAgent.route(ticket, db, config);
trace.setAnswer(answer);
return answer;
},
);
} finally {
await traces.close();
}
Only the explicit inputs, answer and optional JSON metadata are captured, with timestamps, duration and execution status. Missing set_answer/setAnswer makes a trace incomplete. Application exceptions propagate unchanged; capture records the error type without its message or stack. Supply finite JSON values, redact sensitive fields before capture and use asset references for media.
Call a Saina Decision Endpoint
The same client calls a published endpoint explicitly, with one server-side trace in the selected collection. Do not wrap it in another capture scope.
decision = traces.invoke_endpoint(
"support-triage", {"state": {"message": "Charged twice"}},
version="production",
)
traces.report_outcome(
decision["decision_id"], values={"resolved": True},
event_id="ticket-48213-resolved",
)
# TypeScript:
# const decision = await traces.invokeEndpoint("support-triage", {state: {message: "Charged twice"}});
# await traces.reportOutcome(decision.decision_id, {eventId: "ticket-48213-resolved", values: {resolved: true}});
Native proxy capture is asynchronous. The proxy returns its answer without waiting for trace storage. Background workers persist native evidence with stable IDs and retries; observability is eventually consistent. The response does not acknowledge durable trace storage. A process crash before persistence, a full queue or exhausted storage retries can lose a trace. Hosted delivery uses a separate database pool, at most 16 workers and a queue bounded to 256 waiting jobs and 32 MiB of pending response-size estimates. Metrics expose queued jobs, pending bytes, persisted traces and drops. Graceful shutdown drains within its deadline.
Endpoint invocation is never retried automatically. External capture retries delivery using stable collection/source/decision identities; identical replays deduplicate and conflicting evidence fails. Use a durable decision_id/decisionId when replaying from your own outbox. Business outcomes use a stable event ID and flush pending external SDK traces before submission. Native business-outcome reporting retries temporary not-found responses while evidence is being persisted; if exhausted, retry the business outcome with the same event ID. Client flush does not drain the server’s native queue.
Delivery and observability
The SDK sends up to 100 traces per batch, bounded to 8 MiB, or flushes every five seconds. Each trace is at most 1 MiB. A missing collection is created on first delivery. The queue holds up to 1,000 traces in memory and is not crash durable. Call flush/close before shutdown; serverless handlers must await delivery before returning. Failed batches remain queued. Overflow and oversized evidence emit errors and increment the dropped counter without replacing application results.
Monitor Python pending_count, dropped_count, last_error and on_error; TypeScript exposes pendingCount, droppedCount, lastError and onError. Explicit flush and close surface delivery failures. See the SDK tracing reference for configuration and lifecycle details.
Captured content is stored. Trace submission and Studio Decision Endpoint capture retain the explicit decision evidence in your collection. These collection writes are separate from ordinary inference requests described in the retention policy below. Observe the same evidence in Studio → Observability and Data → Collections. Approve or correct targets, then freeze a dataset version for fine-tuning; capture does not automatically approve labels or start a paid training job.
Hosted delivery uses an account API key on your application server at https://api.saina.run. Never embed the key in a browser bundle. For self-hosted Studio, use its service origin and omit the key.
Data retention
What is kept, for how long, and where requests are processed is set out in the data policy on the hosted API page.
Support
Email [email protected]. Include the X-Request-Id of the request in question, never your API key. If a key leaked, revoke it in the console first, then tell us.