Python SDK
The SDK is the same turion package as the CLI (version 0.2.0, Python 3.11 or newer). Install it
into your project with uv add turion, or pip install turion without uv. The CLI’s own
uv tool install turion keeps the package in a separate environment your code cannot import
from. Everything is synchronous (from async code), and responses are typed
pydantic models, except chat completions, which are plain OpenAI-shaped dicts.
import turion
job = turion.train(base="gemma-4-e4b", data="support.jsonl", evals="evals.jsonl", name="support-v3")job.wait(on_progress=lambda j: print(j.status, j.phase))job.raise_for_status()print(job.eval) # metric='pass_rate' base=0.61 tuned=0.92 cases=50job.deploy() # scale to zero by default
client = turion.Client()reply = client.chat.completions.create( "acme/support-v3", [{"role": "user", "content": "Where is my order 1042?"}])print(reply["choices"][0]["message"]["content"])Client
Section titled “Client”turion.Client(api_token=None, base_url=None, *, timeout=60.0, max_retries=2)Each value resolves in this order: the argument, the environment (TURION_API_TOKEN, then
TURION_API_KEY; TURION_BASE_URL), then the config file turion login writes
(~/.config/turion/config.json, or the path in TURION_CONFIG_PATH; an older
~/.turion/config.json is read until it exists; see
Config file and precedence).
base_url defaults to
https://api.turion.ai; a trailing /v1 is dropped, so the OpenAI-style base URL works too.
Inside a deployed agent, where the runner sets TURION_BASE_URL=…/v1 and TURION_API_KEY,
turion.Client() needs no arguments. A client with no token raises AuthError("no_token", …) on
its first request, not at construction.
timeout is the default per-request timeout in seconds. Chat completions, decisions and
extractions use their own 600-second read timeout (a model may cold-start before its first token), and file uploads a
300-second one. Whatever the timeout, connecting gives up after 10 seconds, so an API that cannot
be reached says so quickly. max_retries is how many times a failed request is sent again; see
Retries. Requests carry User-Agent: turion-python/<version>. The client is a
context manager (with turion.Client() as c: …) and has close().
| Attribute | Covers |
|---|---|
client.chat | POST /v1/chat/completions |
client.decisions | POST /v1/systemone; client.decide(...) is the shortcut |
client.extractions | POST /v1/extract; client.extract(...) is the shortcut |
client.providers | your provider keys |
client.traces | gateway traces |
client.bases | base models |
client.datasets | datasets |
client.training | training jobs |
client.models | models, version knobs, deploy and undeploy |
client.agents | agents: deploy, run, route, secrets, evals, distil |
client.brain | Turion Brain: ask, search, records, emails, tools |
client.keys | API keys |
client.fleets | fleets and join tokens |
client.webhooks | webhook secret and deliveries |
client.predictions, client.imports, client.garden | image models |
Calls on the client itself:
client.account()→Account:id,name,handle,email,created_at,key(prefix,label) andquota(max_concurrent_predictions,monthly_gpu_seconds,monthly_gpu_seconds_used,max_replicas,period_start). ANonelimit means unlimited; the GPU-second figures are decimal strings.client.usage(*, from_=None, to=None, granularity="day")→UsageforGET /v1/usage:start,end,granularity,gpu,garden,provider_costandtotals.from_/toare ISO-8601 timestamps with a timezone (default: the last 30 days, at most 93);granularityisday,monthortotal.client.decide(model, state, questions, *, timeout=None)→Decision: see Decisions.client.extract(model, state, fields, reference_date=None, *, timeout=None, **extra)→Extraction: see Extract.client.webhook_secret()andclient.rotate_webhook_secret(): shortcuts forclient.webhooks.secret()androtate_secret().client.run(...),client.submit(...),client.run_prediction(...)andclient.run_sync_once(...)run Cog models (image models).
From async code
Section titled “From async code”The SDK has no async client. In async code, call your models with the OpenAI SDK’s
AsyncOpenAI, which works against Turion unchanged, and run the other SDK calls in a worker
thread with asyncio.to_thread, so they do not block the event loop:
import asyncioimport os
import turionfrom openai import AsyncOpenAI
oai = AsyncOpenAI(base_url="https://api.turion.ai/v1", api_key=os.environ["TURION_API_TOKEN"])client = turion.Client()
async def main() -> None: reply = await oai.chat.completions.create( model="acme/support-v3", messages=[{"role": "user", "content": "Where is my order 1042?"}], ) print(reply.choices[0].message.content)
job = await asyncio.to_thread(client.training.get, "ft_0123456789abcdef") print(job.status)
asyncio.run(main())Turion’s own headers (X-Turion-Agent, X-Turion-Run, …) go in extra_headers on the OpenAI
call.
client.chat.completions.create(...) calls Turion’s OpenAI-compatible gateway with the same
request and response shapes as OpenAI’s API: dicts in, dicts out.
client.chat.completions.create( model, # "acme/support-v3", "openai/gpt-6-luna", "agent:support-triage", … messages, # OpenAI messages stream=False, # True returns a ChatStream *, agent=None, # X-Turion-Agent: attribute the trace to an agent run=None, # X-Turion-Run: group the calls of one run step=None, # X-Turion-Step: the step's label or number trace=True, # False sends X-Turion-Trace: off extra_headers=None, # more request headers (they cannot replace Authorization) **params, # OpenAI parameters, sent as given: temperature, max_tokens, tools, …)model resolves as described under
POST /v1/chat/completions: your agent’s route
(agent:<name>), a deployed fine-tune (<owner>/<name>), a provider model with your stored key
(<provider>/<model>), or a model-garden id. A provider that refuses a sampling parameter for a
model (Anthropic’s Claude 5 models refuse temperature) gets the call again without it.
Without stream, the call returns the completion dict. from turion.chat import message_text
gives you choices[0].message.content (or "" for a reply that is only tool calls). The dict also
carries a _turion key that is not part of OpenAI’s shape: reply["_turion"]["trace_id"] is the
call’s trace id (from the X-Turion-Trace-Id header), or None when tracing was off.
reply = client.chat.completions.create( "acme/support-v3", [{"role": "system", "content": "You are terse."}, {"role": "user", "content": "Where is my order 1042?"}], temperature=0.2, run="r-17",)print(reply["choices"][0]["message"]["content"], reply["usage"])print("trace", reply["_turion"]["trace_id"]) # turion traces get <id>With stream=True it returns a ChatStream:
with client.chat.completions.create("acme/support-v3", messages, stream=True) as stream: print("trace", stream.trace_id) for piece in stream.text(): print(piece, end="", flush=True)ChatStream member | Description |
|---|---|
| iterate it | chat.completion.chunk dicts, in order, until data: [DONE] |
text() | only the non-empty choices[0].delta.content strings |
trace_id | the call’s trace id (X-Turion-Trace-Id), or None when tracing is off |
close() | release the connection; also done at the end of the stream and of a with block |
Errors:
- An HTTP error (unknown model,
409 model_not_deployed, a bad provider key) raises fromcreate(...)itself, before you iterate: the matching exception from the table under Exceptions, with the server’scode. - An error frame inside the stream raises
TurionErrorwith that frame’scodeandmessage. - A connection that drops mid-stream raises
TurionConnectionError("connection_error", …).
The official openai package works against the same endpoint, for code that already uses it:
import osfrom openai import OpenAI
client = OpenAI(base_url="https://api.turion.ai/v1", api_key=os.environ["TURION_API_TOKEN"])reply = client.chat.completions.create( model="acme/support-v3", messages=[{"role": "user", "content": "Where is my order 1042?"}], extra_headers={"X-Turion-Run": "r-17"},)Decisions
Section titled “Decisions”client.decide(...) asks a decision model typed questions about a
state and returns typed answers, with the request and response of TypeSafe’s POST /v1/systemone.
client.decide( model, # "turion-jev-31b", "typesafe/jev-1.13", "acme/ticket-router", ... state, # a string, a dict or a list questions, # {id: question}; at least one *, timeout=None, # seconds; default 600 (read), enough for a cold start)Build questions with the helpers, or pass TypeSafe’s question dicts as they are:
| Helper | Returns |
|---|---|
turion.choice(instructions, options) | {"type": "choice", …}. options is a list of names, or a dict of name to description (None when the name says it all) |
turion.score(instructions, levels) | {"type": "score", …}. levels is a list, lowest first, 2–10 entries |
instructions and the descriptions may also be dicts or lists; the model reads them as JSON.
| turion.noul(instructions, *, yes=None, no=None) | {"type": "noul", …}. yes/no describe the two answers (sent as criteria.true/criteria.false) |
import turion
client = turion.Client()d = client.decide("acme/ticket-router", "I was charged twice for October.", { "team": turion.choice("Which team should handle this?", ["billing", "tech", "sales", "other"]), "urgency": turion.score("How urgent is it?", ["can wait", "this week", "today"]), "refund": turion.noul("Does the customer ask for money back?"),})team = d.choices["team"]if team.confidence < 0.6: send_to_a_person()else: route(team.choice)Decision:
| Member | Description |
|---|---|
answers | dict[str, Answer], by question id; d["team"] is d.answers["team"] |
choices, scores, nouls | the same answers split by type (as in TypeSafe’s SDK), typed ChoiceAnswer, ScoreAnswer, NoulAnswer |
model | the model that answered, as the server names it (jev-1.13.0); a model on Turion GPUs answers under the name you called it by (turion-jev-31b, acme/ticket-router) |
usage | DecisionUsage: input_tokens, output_tokens |
trace_id | the call’s trace id (X-Turion-Trace-Id), or None |
raw | the response body exactly as received |
Every answer has type, probabilities (outcome to probability, summing to 1), confidence and
top(n=3), the n most likely outcomes as (outcome, probability) pairs, most likely first.
| Answer | Fields |
|---|---|
ChoiceAnswer | choice: the most likely option. probabilities is keyed by option |
ScoreAnswer | score: the expected level, levels counted from 0, so it can fall between two levels. legend: level ("0", "1", …) to description; probabilities uses the same keys. Properties level (the most likely level, an int) and label (its description; JSON for an object or array) |
NoulAnswer | noul: the probability of yes. probabilities is {"yes": p, "no": 1 - p}, confidence is max(p, 1 - p) (the wire answer has neither), and yes is p >= 0.5 |
An answer type this SDK does not know yet parses as a plain Answer with its fields kept, instead
of failing the call. On your own models confidence is the calibrated probability of the chosen
option (for a score, of the most likely level), which is not TypeSafe’s formula: compare
probabilities, not confidences, across the two (see
Limits and differences).
Errors raise the exception for the HTTP status (see Exceptions) with the server’s
code: NotFoundError("model_not_found"), TurionError("not_a_decision_model") (409, a chat
model), TurionError("model_not_deployed") (409), BadRequestError (422) with
invalid_question, too_many_options (more than 26 options), too_many_questions (more than
128) or context_length_exceeded, TurionError("model_loading") (503, retry), and the
provider’s own errors for typesafe/… and openrouter/…. A call with no questions raises BadRequestError("no_questions") before any
request.
Extract
Section titled “Extract”client.extract(...) pulls typed fields out of a document with an
extract model (POST /v1/extract): one typed value, or None,
per field.
client.extract( model, # "turion-extract-alpha" or your own, "acme/turion-extract-alpha" state, # the document text, a non-empty string fields, # {name: field}; at least one reference_date=None, # "YYYY-MM-DD" or a datetime.date, for relative dates *, timeout=None, # seconds; default 600 (read), enough for a cold start **extra, # any other key, sent in the body as is)A field is the dict the API takes, {"type": "number", "decimals": 2, "instructions": "…"}, or a
bare type name ("date", sent as {"type": "date"}). The types and their options are in
Extract models → Fields.
import turion
client = turion.Client()r = client.extract("turion-extract-alpha", open("invoice.txt").read(), { "invoice_number": "text", "total": {"type": "number", "decimals": 2, "instructions": "Amount due"}, "po_number": {"type": "text", "instructions": "Purchase order number"},})if r["po_number"].found: match_po(r["po_number"].value)Extraction:
| Member | Description |
|---|---|
answers | dict[str, ExtractAnswer], by field name; r["total"] is r.answers["total"] |
values | the same map reduced to each field’s value (None where the document does not say) |
id | the request id the server gave the call |
model | the model that answered, as the server names it |
usage | ExtractUsage: input_tokens, output_tokens (always 0), passes |
trace_id | the call’s trace id (X-Turion-Trace-Id), or None |
raw | the response body exactly as received |
ExtractAnswer has type, value (the typed value in its JSON form: a str for text, dates and
times, an int or float for numbers and durations, a list for a list, or None), p_null,
confidence, span ([start, end] of a text value in state), and the property found: the
value is neither None nor an empty list. Any other key the server sends, such as a list’s
spans, is kept as an attribute.
Errors raise the exception for the HTTP status (see Exceptions) with the server’s
code: NotFoundError("model_not_found"), TurionError("not_an_extract_model") (409, a chat or
decision model), TurionError("model_not_deployed") (409), BadRequestError (422) with
invalid_request or context_length_exceeded, and ServerError for garden_upstream (502),
not_configured (503, which the client retries), garden_timeout (504) and proxy_timeout
(524, not resent). A cold start usually takes longer than a call is held: the proxy in front of
api.turion.ai stops waiting after 100 to 120 seconds with 524, and the API’s own wait ends at
3 minutes with garden_timeout. So the first call to a scaled-to-zero model can raise
ServerError("proxy_timeout") (or garden_timeout) while its replica keeps starting: call again
once it is ready (turion model logs OWNER/NAME --follow shows when). An empty state, a state
that is not a string, no fields, or a field that is neither a dict nor a type name raises
BadRequestError before any request.
Provider keys
Section titled “Provider keys”Store your own key per provider so <provider>/<model> calls go straight to that provider, billed
by it. Keys are encrypted at rest and never returned.
| Method | Returns |
|---|---|
set(provider, key) | ProviderKey; stores or replaces the key |
list() | list[ProviderKey]: the providers you have a key for |
supported() | list[ProviderInfo]: every provider a key can be stored for |
remove(provider) | None; NotFoundError when no key is stored |
ProviderKey: provider, last4 (empty for a very short key), created_at, updated_at, and
account: the Hugging Face username, set only on what set("huggingface", key) returns.
ProviderInfo: name, display_name, base_url. Providers: openai, anthropic, google,
openrouter, groq, together, mistral, deepseek, typesafe for
decisions (client.decide("typesafe/jev-1.13", …)), and huggingface, a token for
Hugging Face imports and pushes, checked with Hugging Face before it is stored.
client.providers.set("openai", os.environ["OPENAI_API_KEY"])client.chat.completions.create("openai/gpt-6-luna", [{"role": "user", "content": "hi"}])Traces
Section titled “Traces”Every chat completion leaves a trace unless it was sent with trace=False.
| Method | Returns |
|---|---|
list(*, agent=None, model=None, run=None, status=None, limit=50, cursor=None) | TracePage (traces, next_cursor): one page, newest first |
iter(*, page_size=100, **filters) | an iterator over every matching Trace, fetching pages as needed |
get(trace_id) | Trace, including request, response and meta |
agent matches an agent’s name or id; status is ok, error or cancelled. Trace fields:
id, created_at, agent_id, agent_name, run_id, step, requested_model, route
(self_hosted, provider or garden), provider, served_model, stream, status,
http_status, error_code, error, latency_ms, input_tokens, output_tokens, truncated,
prediction_id, and, from get() only, request, response and meta. The property agent is
agent_name, else agent_id. A streamed response is stored assembled into one chat.completion.
for t in client.traces.iter(run="r-17"): print(t.created_at, t.requested_model, t.status, t.latency_ms)Base models
Section titled “Base models”| Method | Returns |
|---|---|
list() | list[Base]: every base in the catalog, teachers included |
get(base_id) | Base; NotFoundError("base_not_found") for an id that is not listed |
deploy(base_id, *, name=None, fleet=None, min_replicas=None, max_replicas=None, keep_alive_s=None) | Deployment: serve the base as it is, without training, as <handle>/<name> (name defaults to the base id). Only the arguments you pass are sent; see Deploy a base model without training |
Base fields: id, name, vendor, params, active_params, hf_repo, runtime,
licence, context, methods, default_method, min_vram_gb (per method), serve_vram_gb,
teacher, vision, recommended_for, notes, plus the property trainable (False for a
teacher and for an extract base). runtime is how a deploy of the base answers: chat on
/v1/chat/completions, extract on /v1/extract (Extract), or decision on
/v1/systemone (Decisions, turion-jev-31b, which also trains as a chat base); it
reads chat from an API that does not send it.
Training also accepts any public, ungated Hugging Face model as hf:<org>/<repo>, which is not in
this list.
deploy answers the same Deployment as client.models.deploy. A name you
already used for a deploy of the same base redeploys it; a name another model uses raises
ConflictError (409 name_taken), a teacher BadRequestError (422 base_not_deployable), and a
deployment that does not serve bases yet ServerError (503 not_configured, not retried).
d = client.bases.deploy("gemma-4-e4b", name="support")print(d.model) # acme/supportprint(d.endpoint) # https://api.turion.ai/v1/chat/completionsDatasets
Section titled “Datasets”The SDK validates, normalises and de-duplicates a dataset on your machine before it uploads it,
so a bad record fails locally with its file:line. Formats and rules:
Datasets.
| Method | Returns |
|---|---|
upload(path, name=None, eval_split=None) | Dataset, or (train, eval) with eval_split |
upload_local(local, eval_split=None, *, on_progress=None) | the same, for a LocalDataset you already loaded; on_progress(name, sent, total) reports the bytes of each file |
create_from_records(records, name) | Dataset from in-memory records (problems name record N) |
get(dataset_id) | Dataset |
list(limit=200) | list[Dataset], newest first, at most limit (1–500) |
delete(dataset_id) | None; TurionError("dataset_in_use") (409) while a queued or running job uses it |
import_hf(ref, name=None) | DatasetTransfer, queued: start copying hf:owner/name[@revision][:split] into a new dataset (ValueError for another shape) |
push_hf(dataset_id, repo, private=True) | DatasetTransfer, queued: start pushing a ready dataset to repo (owner/name or hf:owner/name) |
transfer(transfer_id) | DatasetTransfer, as it stands |
wait_transfer(transfer_id, *, poll_interval=2.0, timeout=None, on_status=None) | DatasetTransfer once done or failed; a failed one is returned, not raised. timeout raises TimeoutError (the transfer goes on) |
pathis a JSONL file, a CSV file with aprompt,completionheader, or a folder of such files (all one format).namedefaults to the file or folder stem.eval_split(0–0.5, e.g.0.1) holds out that share, picked deterministically, as a second dataset named<name>-eval; the eval half gets at least one record and the train half keeps at least one, so it needs at least two records. Decision data splits as the trainer does: whole states (a state’s questions stay on one side), at least 50 and at most 1,000 cases and never more than half. It needs at least 10 examples, and is refused withbad_eval_splitwhen no whole state can be held out.eval_split=0uploads one dataset.- A local problem raises
DatasetError(aBadRequestErrorwith codeinvalid_dataset, message startingfile:line:). If the server’s own check rejects the upload,uploadraisesTurionError("dataset_invalid", …)withdetails["dataset"]set to the id.
train, held_out = client.datasets.upload("support.jsonl", eval_split=0.1)print(train.id, train.examples, held_out.id, held_out.examples)Dataset fields: id, name, status (uploading, ready, invalid), format (chat,
prompt_completion, text, decision), examples, duplicates, tokens_est, bytes, sha256, error,
source (upload, traces or hf), agent_id, created_at, completed_at.
DatasetTransfer fields: id (tr_…), direction (import or push), repo, revision
(the commit read or written, once done), split, dataset_id, status (queued, running,
done, failed), error_code, error, created_at, finished_at, and the property
is_terminal. Imports and pushes use the Hugging Face token stored with
client.providers.set("huggingface", token); how they work is in
Datasets → Hugging Face.
started = client.datasets.import_hf("hf:acme/support-tickets")t = client.datasets.wait_transfer(started.id)if t.status == "done": print(t.dataset_id, t.revision)else: print(t.error_code, t.error)Two helpers work without a client:
turion.load_dataset(path, name=None)→LocalDataset: the same read-validate-dedup the upload does.LocalDatasethasname,format,records(normalised dicts),duplicates(dropped),files, the propertyexamplesandto_jsonl(). For decision data,recordsare in the one-question shape, a multi-question row already expanded to one record per question.turion.split_records(records, fraction, seed=0)→(train, eval)lists: the spliteval_splituses.
Training
Section titled “Training”turion.train(...)
Section titled “turion.train(...)”The one-call path: upload what needs uploading, then queue the job. It returns the queued
TrainingJob without waiting for it.
turion.train( base, # base id from client.bases.list(), or "hf:<org>/<repo>" data, # JSONL/CSV file or folder, "ds_…" id, Dataset or "hf:…" *, method=None, # "lora", "qlora", "full" or "decision"; default: the base's own evals=None, # eval set: local path, "ds_…" id, Dataset or "hf:…" eval_split=None, # hold out this share of data as the eval set name=None, # the fine-tune becomes <handle>/<name> fleet=None, # fleet slug to train on; default "turion" client=None, # default: turion.Client() **hyperparams, # epochs, lr, rank, max_seq_len, batch_size, … (see client.training.create))- A local
dataorevalspath is validated and uploaded first. A string startingds_is a dataset id unless a local file by that name exists. Anhf:owner/name[@revision][:split]ref is imported first and waited for (a failed import raisesTurionErrorwith itserror_code); an imported decision dataset picksmethod="decision"like a local one. eval_splitis0–0.5. On a local path it splits the file locally into two datasets. On a dataset id it is sent as theeval_splithyperparameter and the trainer holds out that share itself.- With neither
evalsnoreval_split, the trainer holds out 10% ofdatafor the eval (none for fewer than 10 examples), or 20% in whole states for decision data.eval_split=0means no hold-out, for a path or a dataset id: the job trains on all ofdata. - A local decision dataset trains with
method="decision", chosen for you whenmethodisNone. Another method on decision data, ormethod="decision"on another format, raisesBadRequestError("unsupported_method")before anything is uploaded. evalsandeval_splittogether raiseBadRequestError("bad_request"); a path that does not exist raisesTurionError("not_found", …).
client.training
Section titled “client.training”| Method | Returns |
|---|---|
create(base, dataset, *, eval_dataset=None, method=None, name=None, fleet=None, **hyperparams) | TrainingJob (queued) |
get(job_id) | TrainingJob |
list(limit=50, *, model=None) | list[TrainingJob], newest first; model="acme/support-v3" keeps the jobs that produced that model |
cancel(job_id) | TrainingJob; ConflictError("conflict") (409) once the job has finished |
logs(job_id) | str: the trainer’s log tail (last 64 KiB) |
create takes already-uploaded datasets (ds_… ids or Dataset objects). Hyperparameter
keywords are sent as given and the server fills the rest: epochs, learning_rate (alias lr),
lora_rank (alias rank), lora_alpha, max_seq_len, batch_size, grad_accum,
warmup_ratio, eval_split, skip_baseline_eval. A None value is dropped. Defaults and bounds
are in the REST reference; an unknown key or a
value out of bounds is a BadRequestError("validation_error") from the server. An unknown
method raises BadRequestError("unsupported_method") before any call.
TrainingJob
Section titled “TrainingJob”Bound to the client that fetched it, so its methods call the API.
| Field | Description |
|---|---|
id | ft_… |
name, base, base_hf_repo, method | what is being trained |
hyperparams | the full resolved set the trainer runs with |
dataset_id, eval_dataset_id | the datasets |
base_revision | the Hugging Face commit of the base the job trains on; "" when it could not be pinned (it trains on main, and notes says so) |
status | queued, running, succeeded, failed, cancelled |
phase | queued, starting, downloading, baseline_eval, training, tuned_eval, uploading, done |
progress | TrainingProgress: step, total_steps, epoch, epochs, loss, learning_rate, eta_s; each may be None |
metrics | {"loss": [[step, loss], …], "epochs": [{"epoch", "loss", "eval_loss"}, …], "final": …}. final is the trainer’s own metrics.json once the job succeeded (None in list(); get() has it) |
notes | what the platform noted about the run, e.g. that the base’s revision could not be pinned |
decision_metrics | a decision job’s held-out reports, {"tuned": DecisionMetrics, "base": DecisionMetrics} (no base when the baseline was skipped); {} otherwise |
split | a decision job’s split: groups_train, groups_eval (states on each side), warnings, eval_overlap_removed, eval_state_keys; {} otherwise |
eval | TrainingEval: metric (pass_rate), base, tuned, cases. base is None when the baseline was skipped, tuned until the tuned eval ran |
model, model_version | the fine-tune’s slug and version once the job succeeded |
prediction_id, fleet | the run behind the job and the fleet it runs on |
gpu_seconds | billed GPU-seconds, a decimal string, set when the job ends |
error | why it failed or was cancelled |
created_at, started_at, completed_at | timestamps |
| Member | Description |
|---|---|
is_terminal | True once status is succeeded, failed or cancelled |
wait(on_progress=None, poll_interval=5.0, timeout=None) | poll until terminal and return the job. on_progress(job) is called once right away and after every poll. A failed or cancelled job is returned, not raised. A 429, a 5xx or a dropped connection is retried with backoff (1 s, 2 s, 4 s … up to 30 s, never sooner than poll_interval); the eighth failure in a row is raised. timeout raises TimeoutError; the job keeps running |
refresh() | re-read the job in place; returns it |
raise_for_status() | raise TurionError("training_failed") or ("training_cancelled"); return the job otherwise |
deploy(scale_to_zero=True, max_replicas=1, keep_alive_s=300) | deploy the fine-tune (client.models.deploy); scale_to_zero=False keeps one replica warm. Raises TurionError("no_model") before the job has produced a model |
cancel() | cancel the job and update it in place |
logs() | the trainer’s log tail |
A job built by hand (not fetched through a client) raises TurionError("unbound") from these
methods.
import turion
client = turion.Client()job = turion.train( base="gemma-4-e4b", data="support.jsonl", evals="evals.jsonl", name="support-v3", epochs=2, lr=1e-4, client=client,)print(job.id, job.status)
def show(j): p = j.progress if j.phase == "training" and p is not None and p.loss is not None: print(f"step {p.step}/{p.total_steps} loss {p.loss:.3f}") else: print(j.phase)
try: job.wait(on_progress=show, timeout=6 * 3600)except TimeoutError: print("still running:", job.id)else: job.raise_for_status() print(f"base {job.eval.base} -> tuned {job.eval.tuned} on {job.eval.cases} cases") d = job.deploy() print(d.model, d.openai_base_url)client.evals
Section titled “client.evals”Server-side eval runs of a decision model: what turion eval starts on one. A run scores versions, and with include_base the zero-shot base, on one
decision dataset, on your trainer; it is metered in GPU-seconds like a training job.
| Method | Returns |
|---|---|
create(model, versions, dataset, include_base=False) | EvalRun, queued. model is owner/name, and the run belongs to it. Each version is "v2" (of model) or "owner/name@v1" (another decision model of your workspace); the first is the reference every comparison is against. dataset is a ready decision dataset (ds_… or a Dataset) |
get(model, eval_id) | EvalRun |
wait(model, eval_id, timeout=1800, *, poll_interval=5.0, on_status=None) | EvalRun once succeeded, failed or canceled; a failed run is returned, not raised. timeout raises TimeoutError (the run goes on) |
list(model, *, limit=20, cursor=None) | EvalRunPage: evals (each report cut to its overall.macro_f1; get() has the rest) and next_cursor |
cancel(model, eval_id) | EvalRun, canceled; ConflictError("conflict") (409) once the run has finished. A canceled run is not billed |
EvalRun has id, status (queued, running, succeeded, failed, canceled), kind,
versions (labels: v2, or owner/name@v1 for another model’s), include_base, dataset,
dataset_name, dataset_sha256, metrics ({label | "base": DecisionMetrics}), comparisons
(EvalComparison: a, b, metric, value_a, value_b, diff, lo, hi, cases),
notes, error, is_terminal, raw and raise_for_status() (raises eval_failed or
eval_canceled). In an eval run each report’s overall.ece_shipped is the calibration error at
the temperature the version ships with: read it rather than the cross-fitted ece.
run = client.evals.create("acme/triage-2", ["acme/triage@v1", "v1"], "ds_fedcba9876543210")run = client.evals.wait("acme/triage-2", run.id).raise_for_status()for c in run.comparisons: print(c.a, "vs", c.b, c.metric, c.diff, (c.lo, c.hi))Models & deployment
Section titled “Models & deployment”client.models
Section titled “client.models”| Method | Returns |
|---|---|
list() | list[Model]: yours plus the curated catalog |
get(slug) | Model with its versions |
get_version(slug, version) | ModelVersion |
update_version(slug, version, *, keep_alive_s, min_replicas, max_replicas, concurrency_limit, priority, cold_start_target_s) | ModelVersion: retune one version’s knobs |
deploy(slug, *, min_replicas=None, max_replicas=None, keep_alive_s=None) | Deployment: make an LLM answer on /v1/chat/completions. Only the arguments you pass change; a first deploy starts at 0, 1 and 300 |
undeploy(slug) | Deployment: take it out; calls then answer 409 model_not_deployed |
logs(slug, *, version=None, boot=None, after=0, limit=None) | ReplicaLogs: the model’s recent cold starts and one start’s lines (below) |
Model fields: id, slug, display_name, description, visibility, created_at, fleet,
versions_count, latest_version (version, created_at, source), last_prediction_at,
kind (model for a Cog image or an import, llm for a fine-tune or a base served as it is),
deployed, origin (training, base, or None for an image model), base (the catalog base
id when origin == "base"), versions (filled by get) and hosted (filled by an import only).
latest() returns the newest version.
ModelVersion fields: id, version, image_uri, cog_schema, vram_gb,
vram_footprint_mb (the GPU memory one replica reserves; None = unknown), predict_timeout_s,
concurrency_limit, priority, source (kind, url, ref, image), keep_alive_s,
min_replicas, max_replicas, cold_start_target_s, cold_start_observed_s (a decimal
string), setup_timeout_s, created_at, archived_at.
update_version sends only the keyword arguments you pass, so raising keep_alive_s cannot reset
a replica count someone else set. concurrency_limit=None and cold_start_target_s=None are sent
as explicit nulls and clear those knobs. It is the SDK side of
turion model set and
PATCH /v1/models/{slug}/versions/{version}
(vram_footprint_mb is only settable through the REST call).
deploy scales to zero by default (min_replicas=0). The server stores max_replicas as given;
your account’s replica quota caps it while the model runs, so a raised quota applies without
deploying again. Only fine-tunes (kind == "llm") deploy; anything else raises
BadRequestError (422 not_deployable).
Deployment fields: model, deployed, version, min_replicas, max_replicas,
effective_max_replicas (max_replicas after your quota), keep_alive_s, deployed_at,
endpoint (the full …/v1/chat/completions URL; …/v1/systemone for a decision model,
…/v1/extract for an extract model), kind (llm, decision or extract), plus the property
openai_base_url: the endpoint without /chat/completions, ready for OpenAI(base_url=…).
d = client.models.deploy("acme/support-v3", keep_alive_s=600)print(d.endpoint) # https://api.turion.ai/v1/chat/completionsclient.models.undeploy("acme/support-v3")logs reads GET /v1/models/{owner}/{name}/logs.
ReplicaLogs fields: model, boots (newest first, up to 10), boot (the id of the start
lines belong to, None when nothing has started), lines (seq, ts, line) and
next_after; current() returns that start. ReplicaBoot fields: id, version, node,
phase (pulling, starting, loading, ready or failed), started_at, pulled_at,
container_started_at, ready_at, failed_at, updated_at, last_seq, lines_dropped, and the
property finished (ready or failed). Pass next_after back as after to get only newer lines:
import time
logs = client.models.logs("acme/invoices")while logs.current() and not logs.current().finished: for entry in logs.lines: print(entry.ts, entry.line) time.sleep(2) logs = client.models.logs("acme/invoices", boot=logs.boot, after=logs.next_after)Agents
Section titled “Agents”client.agents deploys and runs your own agent code. The workflow is in
Build & deploy agents; the endpoints are under
REST API → Agents.
import turion
client = turion.Client()agent = client.agents.deploy("./support-triage") # tar + upload + create (or new revision)client.agents.set_secrets("support-triage", {"ZENDESK_API_TOKEN": "…"})run = client.agents.run("support-triage", "Where is my order A-1001?")print(run.status, run.output["output"])
job = client.agents.distil("support-triage").job.wait() # traces → datasets → training jobjob.raise_for_status()job.deploy()client.agents.set_route("support-triage", job.model, share=20)| Method | Returns |
|---|---|
deploy(path=".", *, name=None, on_skip=None, on_progress=None) | Agent: pack the directory, upload it and create the agent or a new revision. Left out: .git, __pycache__, .venv/venv/env, node_modules, .direnv, caches, dist, build, *.pyc, .env*, .envrc and symlinks; at most 50 MiB (BadRequestError("code_too_large")) |
upload_code(data, *, on_progress=None) / create(name, *, config, code_ref, code_sha256, blueprint=None, description=None) | the two steps deploy runs: upload a tarball (returns its turion://uploads/… ref), then create the agent from it. blueprint is kept for older agents and clients; new code leaves it out |
list() | list[Agent] |
get(name) | AgentDetail: the agent plus revisions, traces, distil progress and schedules |
code(name, revision) | AgentCode: revision, code_sha256, url (a presigned GET for the revision’s code tarball) and expires_at (10 minutes on). turion.agents.download_code(code) fetches it and raises TurionError("code_mismatch") when the bytes do not match code_sha256; turion.agents.extract_code_tarball(data, dest) unpacks it, refusing links and paths outside dest (BadRequestError("unsafe_archive")) |
delete(name) | None |
run(name, input, *, wait=60.0, owner=None, poll_interval=2.0, timeout=None, trace=True, on_status=None) | AgentRun: waits for the result (polling past wait); wait=0 returns the queued run |
runs(name, *, limit=20, cursor=None, owner=None) | AgentRunPage: runs, next_cursor |
get_run(name, run_id, *, owner=None) | AgentRunDetail: the run plus its traces |
logs(name, run_id) | str: what the run printed |
set_route(name, primary, *, fallback=None, share=100) / clear_route(name) | Agent |
set_secrets(name, mapping) | list[str]: names now set; a None value deletes that secret |
secrets(name) | list[str]: names only |
save_eval(name, *, model, cases, passed, score, results, revision=None) / evals(name, limit=20) | AgentEval / list[AgentEval] |
distil(name, *, base=None, min_traces=1000, method=None, epochs=None, job_name=None) | Distillation: dataset, eval_dataset, job (a bound TrainingJob), examples |
- Every method takes the agent’s bare name or your own
owner/name.run(),runs()andget_run()also take another account’sowner/name(orowner=), the form in an agent’sruns_url. The other methods raiseturion.agents.AgentRefErrorfor one: aBadRequestErrorand aValueError(codeinvalid_ref) whose message names the method, since only an agent’s owner can read or change it. run()returns a failed run rather than raising; checkstatusanderror.timeoutbounds the whole call, server hold included, withTimeoutError(the run keeps going;Nonewaits as long as it takes). A poll answered with a 429, a 5xx or a dropped connection is retried with backoff (1 s, 2 s, 4 s … up to 30 s, six failures in a row at most); thePOSTthat starts the run is never retried.on_status(run, elapsed_s)is called on the first answer and on every poll.trace=Falsekeeps the run’s model calls out of traces and distillation data.deploy()skips symlinks rather than following them;on_skip(rel_path, why)hears about each.on_progress(sent, total)reports the upload. It raisesBadRequestError("invalid_config")before uploading whenturion.tomlhas a top-level[[schedule]]: schedules go under[agent]as[[agent.schedule]](Schedules).set_route()raisesBadRequestError("validation_error")for ashareoutside 0–100.distil()raisesTurionError("not_enough_traces")(409,details["current"]anddetails["required"]) belowmin_tracesusable examples, andBadRequestError("no_distil_base")(422) for an agent with nodistil_basewhen nobaseis given.
Agent fields: id, name, owner, blueprint, description, revision, model,
fallback, distil_base, route (AgentRoute: primary, fallback, share), secrets,
runs_url, created_at, updated_at, and the property serving (the route’s primary, else
model). blueprint is kept for agents made by older CLIs from their bundled agents; it is
None for agents made from the template. AgentDetail adds revisions (number, code_sha256, config, created_at),
traces (a count), distil (traces, runs, usable, threshold, ready) and schedules
(AgentSchedule: name, cron (UTC), input, next_run_at, last_run_id, last_run_at,
last_skipped_at, last_error; [] without any). AgentRun fields: id, agent,
revision, status, input, output, error, logs_url, created_at, started_at,
completed_at, trigger (what started it: api, schedule:<name> or approval:<id> for the
run of an approved proposal; None from an older
server), and is_terminal. AgentEval fields: id, revision, model,
cases, passed, score, results, created_at.
Turion Brain
Section titled “Turion Brain”client.brain reads and manages the workspace’s
Turion Brain: a copy of the records in
the tools it connects. The CLI’s turion brain … commands
are these calls.
answer = client.brain.ask("When did syncing become hourly?")print(answer.answer)for cite in answer.citations: print(cite.n, cite.title, cite.url or cite.id)
for hit in client.brain.search("renewal quote", source="turioninbox"): print(hit.id, hit.title)
for email in client.brain.iter_inbox_messages(): print(email.received_at, email.status, email.subject)| Method | Returns |
|---|---|
state() | BrainState: status (draft, setup_in_progress, active), sources, restricted_tools, self_serve_tools, mcp_url |
technical() | BrainTechnical: database (None before the first tool is connected), sync, sources (each tool’s status, records, last_sync_at, error), runs |
overview() | BrainOverview: records, entities and links in counts, and ask_model |
ask(question, *, detail=False, trace=True, timeout=300) | BrainAnswer: answer, citations, steps, model, usage, trace_ids, seconds. Two to four sentences unless detail; trace=False sends X-Turion-Trace: off |
search(query, *, source=None, type=None, limit=10) | list[BrainSearchHit], best match first; limit is 50 at most |
document(record_id) | BrainDocument: the record with its body, fields, link_counts and newest links |
entity(entity_id) | BrainEntity: a person, repository or thread with its aliases, external_ids and links |
schema() | BrainSchema: entities, links (each with its origin), unresolved, matching |
agents() | list[BrainAgent]: the agents whose own key reads the brain |
connections() | BrainConnections: tools (each a BrainConnection), available, token_storage |
connect(key, *, config=None, token=None) | BrainConnected: tool and the queued run. Settings and a token left out stay as saved |
disconnect(key) | BrainConnection: the tool’s records leave the brain and it stops syncing |
sync(key) | BrainSyncRun: the tool is read again now |
inbox_messages(*, before=None, limit=50) | BrainInboxPage: messages newest first and next_before; limit is 100 at most |
iter_inbox_messages(*, page_size=100) | iterator of BrainInboxMessage, fetching pages as needed |
inbox_message(message_id) | BrainInboxMessageDetail: the email with to, cc, sent_at, body, attachments_read |
matches() | BrainMatches: suggested, linked, rejected pairs of identities |
decide_match(a, b, *, same) | BrainMatch: the pair linked (same=True) or kept apart |
telegram() | BrainTelegram: enabled, bot, chats |
telegram_link() | BrainTelegramLink: code, command, private_url, group_url, expires_at |
telegram_unlink(chat_id) | None |
A BrainInboxMessage has id, received_at, sender (the address that sent it to the inbox),
size_bytes and status. Once status is read it also has what the brain read: subject,
sender_from ({"email", "name"}, the API’s from: the original sender of a forwarded email),
forwarded, attachments and record_id. Until then it is waiting.
The reads raise ConflictError (409 brain_not_synced) until the brain’s first tool is
connected. An API key does not read a tool limited to owners and admins: its records are left
out, and the inbox calls raise ForbiddenError (403 brain_inbox_limited) when the inbox is the
limited tool. connections, connect, disconnect, sync, decide_match, telegram_link and
telegram_unlink need platform.credentials.manage.
Picking and paying for tools, signing in to Gmail, Google Drive and Slack, setting who can ask about a tool and replacing Turion Inbox’s address are done on the Brain page of the members area.
API keys, fleets and webhooks
Section titled “API keys, fleets and webhooks”| Method | Returns |
|---|---|
client.keys.create(label="default") | ApiKeyCreated: id, prefix, label and token, the only copy of the secret |
client.keys.list() | list[ApiKey] (id, prefix, label, revoked, created_at, last_used_at), newest first |
client.keys.revoke(key_id) | None; idempotent, and allowed for the key the client is using |
client.fleets.create(name) | Fleet (id, slug, kind) |
client.fleets.list() | list[Fleet]: yours plus the shared turion fleet |
client.fleets.get(name_or_id) | Fleet with nodes (FleetNode: id, name, status, last_seen_at, verified_at, capabilities) and, for your own fleet, join_tokens |
client.fleets.mint_join_token(fleet, *, ttl_hours=None, label=None) | JoinToken: id, token (shown once), expires_at; the server’s default lifetime is 168 hours |
client.fleets.revoke_join_token(fleet, token) | str: the id that was revoked. token is an id, an unambiguous start of one, or the fjt_… prefix |
client.fleets.delete(fleet) | None. Revokes the fleet’s join tokens and nodes and frees its name; ConflictError("fleet_in_use") while it is in use (details: busy_nodes, provisions, models, jobs), ForbiddenError("fleet_not_deletable") for turion |
client.webhooks.secret() / rotate_secret() | the whsec_… secret, or None before one exists / the new secret |
client.webhooks.deliveries(*, prediction=None, limit=50, cursor=None) | (list[WebhookDelivery], next_cursor) |
client.webhooks.retry(delivery_id) | WebhookDelivery; TurionError("already_delivered") (409) for one that was delivered |
Fleet methods take a bare name (gpus), a slug (acme/gpus) or an id; a name that matches no
fleet raises TurionError("fleet_not_found"), and a join token that matches none or several
raises join_token_not_found or join_token_ambiguous.
turion.verify_webhook(secret, headers, body, *, tolerance_s=300) checks an incoming delivery’s
X-Turion-Signature (HMAC-SHA256 over "{timestamp}." + body) and its age, and returns True or
False; it never raises. See Webhooks.
import turion
if not turion.verify_webhook(secret, request.headers, request.body): abort(400)Exceptions
Section titled “Exceptions”All exceptions subclass turion.TurionError, which carries .code, .message, .status
(the HTTP status, when there was a response), .details, .path (the API path that failed),
.trace_id (the call’s X-Turion-Trace-Id, on chat and decision calls) and .request_id (the
response’s X-Request-Id, on every API error). The class follows the HTTP status; the server’s
code (model_not_deployed, dataset_not_ready, quota_exceeded, …) is on .code. When you
email hello@turion.ai about a failed call, include .request_id or
.trace_id.
| Exception | Raised on |
|---|---|
BadRequestError | 400 and 422: validation errors, not_deployable, unsupported_method, base_not_trainable, base_not_public |
AuthError | 401: missing or invalid key; also no_token before any request when no key is configured |
ForbiddenError | 403: for example changing a curated model (not_owner), registering your own image on the shared fleet (image_needs_own_fleet), or an agent’s key calling something outside its scope (agent_key_scope) |
NotFoundError | 404, including model_not_found from chat completions and another account’s model or fleet |
ConflictError | 409: model_not_deployed, name_taken, dataset_not_ready, a finished job, … |
RateLimitError | 429: quota_exceeded; .details["quota"] says which allowance is used up |
ServerError | 5xx: garden_timeout, garden_upstream, not_configured, and proxy_timeout for a 524 from the proxy in front of the API, … |
TurionConnectionError | network failure (connection_error): the API could not be reached, or a stream broke |
TurionError | every other status (413, …), and the client-side codes below |
Retries. A request is sent again, up to max_retries times (default 2), when it never got
through to the API or when the API answers 429 or 503, whatever the method. A GET is also
retried after any other 5xx or a connection that dropped mid-answer; other methods are not, so a
call that may have done its work (a training job, a model call) is never sent twice. The wait is
the response’s Retry-After when it has one (up to 30 seconds; a longer one is raised at once),
otherwise half a second, doubling. A 429 for the month’s GPU-second allowance and a
503 not_configured are never retried, since asking again cannot help. max_retries=0 turns
retries off. The exception comes from the last attempt.
Codes the SDK raises itself, before or without an HTTP error:
| Code | Raised when |
|---|---|
no_token | (AuthError) no API key from the argument, the environment or the config file: No API key. Run `turion login`, or set TURION_API_TOKEN. |
bad_token | (AuthError) the key has a line break, a space or another character an HTTP header cannot carry; the message never includes the key |
invalid_ref | (AgentRefError, a BadRequestError and a ValueError) an agent method given another account’s owner/name, or a malformed ref |
invalid_dataset | (DatasetError, a BadRequestError) a local dataset problem; the message starts with file:line |
bad_eval_split | (BadRequestError) eval_split outside 0–0.5, fewer than two records to split, or for decision data fewer than 10 examples or no whole state that can be held out |
dataset_invalid | the server’s validation rejected an upload; details["dataset"] is its id |
unsupported_method | (BadRequestError) method is not lora, qlora, full or decision, or does not fit the data’s format (turion.train()) |
no_questions | (BadRequestError) client.decide() with no questions |
bad_question | (BadRequestError) turion.choice() / turion.score() given a string instead of a list or dict |
base_not_found | (NotFoundError) client.bases.get() with an id that is not listed |
not_found | turion.train() with a data/evals path that does not exist; agents.deploy() with a missing directory |
bad_request | (BadRequestError) turion.train() with both evals and eval_split; client.run() with both sync and stream; client.decide() with state=None |
code_too_large | (BadRequestError) agents.deploy(): the packed agent is over 50 MiB |
training_failed / training_cancelled | TrainingJob.raise_for_status() on a failed or cancelled job |
no_model | TrainingJob.deploy() before the job produced a model |
unbound | a TrainingJob method on a job that was not fetched through a client |
fleet_not_found, join_token_not_found, join_token_ambiguous | a fleet or join token reference that matches nothing, or more than one token |
prediction_failed / prediction_canceled | client.run(): the prediction reached that terminal status |
prediction_incomplete | Prediction.result() on a prediction that is still running |
bad_ref | client.run() with sync=True and a ref that is not owner-scoped (acme/whisper) |
stream_incomplete | client.run(stream=True) and the output stream ended without a terminal event; poll GET /v1/predictions/{id} |
import turion
try: reply = client.chat.completions.create("acme/support-v3", messages)except turion.NotFoundError: print("no such model")except turion.ConflictError as e: if e.code == "model_not_deployed": client.models.deploy("acme/support-v3")except turion.TurionError as e: print(f"{e.code}: {e.message} (trace {e.trace_id})")TrainingJob.wait(), client.agents.run(), client.run() and Prediction.wait() raise the
built-in TimeoutError, not a TurionError, when their timeout elapses.
Image models (Cog)
Section titled “Image models (Cog)”These run Cog images and imported checkpoints, such as image models, as predictions. See
Training and Chat for training and serving your own language model.
client.garden (models(), and chat(model, messages, *, stream=False, **params), which streams
content strings) is the older model-garden client; client.chat.completions.create reaches the
same garden ids.
client.run(ref, input, ...)
Section titled “client.run(ref, input, ...)”Upload file inputs, create the prediction, poll to completion, and return the output.
client.run( ref, # "owner/name" or "owner/name:version", e.g. "acme/whisper:v2" input, # dict of inputs *, version=None, # alternative to the ":version" suffix webhook=None, # https URL to POST the signed result to sync=False, # one round-trip via POST /v1/run/{owner}/{model} stream=False, # return an iterator of output chunks wait_timeout=None, # sync only: seconds the server holds the connection (sent as 60 when None) poll_interval=2.0, # seconds between polls timeout=None, # max seconds to wait (None = indefinitely); raises TimeoutError on_status=None, # callback(prediction) while polling: once, then on each status change)- File inputs are uploaded for you: any
pathlib.Path, open file object, or string naming an existing local file, nested anywhere ininput, is uploaded and replaced with itsinput_ref. See Files & outputs. - Returns the prediction’s
outputonsucceeded. - Raises
TurionError("prediction_failed", …)onfailedandTurionError("prediction_canceled", …)oncanceled.
def show(p): print(p.id, p.status)
out = client.run("acme/whisper", input={"audio": "sample.wav"}, timeout=300, on_status=show)Three related calls give you more control:
client.submit(ref, input, *, version=None, webhook=None)uploads the files and creates the prediction, and returns it without waiting.client.run_prediction(...)takes the same arguments asrun()(withoutstream) and returns the terminalPredictioninstead of its output, so you can readstatus,erroror download the outputs.client.run_sync_once(ref, input, *, version=None, webhook=None, wait_timeout=None)makes onePOST /v1/run/{owner}/{model}and returns the prediction as the server answered: terminal, or still running when the wait ran out.
stream=True
Section titled “stream=True”Returns an iterator of output chunks instead of the final output; see Stream a model’s output.
for chunk in client.run("acme/storyteller", {"prompt": "…"}, stream=True): print(chunk, end="", flush=True)- The prediction is submitted when you call
run()(uploads and create), then iterated lazily. - A model that does not stream yields one item, its final output (nothing if that output is
null). - It never polls, so
on_status,timeoutandpoll_intervalare ignored. - When the chunks are a strict prefix of the final text output, the missing tail is yielded at the
end; otherwise the chunks stand. A stream that ends without a terminal event raises
TurionError("stream_incomplete", …).
sync=True
Section titled “sync=True”One round-trip via POST /v1/run/{owner}/{model}; see Sync mode.
out = client.run("acme/whisper", {"audio": "clip.wav"}, sync=True, wait_timeout=120)refmust be owner-scoped (acme/whisper); a bare curated slug raisesTurionError("bad_ref", …)before any HTTP call.- When the server answers
202(its wait ran out), the client falls back to polling (poll_interval,timeoutandon_statusapply to that), so the call blocks either way. wait_timeoutis 60 seconds when not given and capped at 300 by the server. The client sends the value it uses and sets its own request timeout to that plus 15 seconds.
client.imports
Section titled “client.imports”| Method | Returns |
|---|---|
civitai(url, *, fleet=None, name=None, timeout=120.0) | Model with a hosted block (slug, version, model_version_id, members_url, created) |
m = client.imports.civitai("https://civitai.com/models/827184?modelVersionId=1490781")print(m.hosted.slug, m.hosted.version) # acme/some-checkpoint v1One server-side call: nothing is built locally, so it needs no Docker and no registry login. The
default timeout is 120 seconds because the server queries the Civitai API inside the request.
Re-importing the same Civitai version returns the existing model with hosted.created == False.
See Host a Civitai model and
POST /v1/imports/civitai.
client.predictions
Section titled “client.predictions”| Method | Returns |
|---|---|
create(model, input, *, version=None, webhook=None) | Prediction (status starting). Inputs are not uploaded here; use client.run() or client.submit(), or upload first |
get(id) | Prediction |
list(*, cursor=None, limit=None) | (list[Prediction], next_cursor) |
cancel(id) | None; TurionError (409) if already terminal |
logs(id) | str: container logs |
wait(id, *, on_status=None, on_log=None, poll_s=2.0, timeout=None) | the terminal Prediction. on_status(prediction, elapsed_s) fires on every poll, on_log(line) once per new log line while it runs; a dropped connection or a 5xx is retried on the next poll |
stream(id) | iterator of status events ({"status": …}), ending at the terminal event |
stream_output(id) | iterator of output events: {"seq", "output"} per chunk, then the terminal {"status", "output", "error"} |
stream_output is the raw relay; run(stream=True) is the convenience wrapper over it. See
Stream a model’s output.
Prediction
Section titled “Prediction”Fields mirror the REST prediction object: id, model,
version, status, input, output, error, created_at, started_at, completed_at,
urls, and queue_position (0 = next up, only while starting). Plus:
| Member | Description |
|---|---|
is_terminal | True once status is succeeded, failed or canceled |
reload() | refresh in place from the API; returns self |
wait(poll_interval=2.0, timeout=None, on_status=None) | poll until terminal; on_status(prediction) fires once immediately, then on each change; raises TimeoutError on timeout |
result() | the output of a succeeded prediction; raises prediction_failed, prediction_canceled or prediction_incomplete otherwise |
download_outputs(dir) | save every URL and data URI in output under dir/{prediction_id}/ and return the paths. Output URLs expire 24 hours after the run |
pred = client.predictions.create("acme/whisper", {"audio": "turion://uploads/…"})pred.wait(timeout=300)if pred.status == "succeeded": print(pred.output)else: print(pred.error, client.predictions.logs(pred.id))