Reference Python API

Python API

Classes and methods for training, sampling and deploying models. For OpenAI-compatible HTTP inference, see the Inference quickstart.

Draft reference. Method names and parameters follow the planned SDK and will be confirmed before launch.

Client

Client()

rsi.Client(api_key, endpoint=None, timeout=None, enable_retries=True)

Creates a client for the API. One client can open sessions, sample, and manage deployments.

Parameters
api_keystrRequired

Your API key.

endpointstrOptional

Host to connect to. Defaults to the fully managed API; set it to your Cell's host for VPC or on-prem.

timeoutfloatOptional

Request timeout in seconds.

enable_retriesboolOptional

Retry transient errors with backoff.

Returns Client

import os, rsi
client = rsi.Client(api_key=os.environ["RSI_API_KEY"])

session()

client.session(project=None)

Opens a training session with its own GPU allocation. Use it as a context manager: it keeps the session alive and releases it on exit.

Parameters
projectstrOptional

Groups runs and metrics in the Console.

Returns SessionContext

with client.session(project="support") as session:
    ...

chat_complete()

client.chat_complete(model, messages, max_tokens=None, temperature=None)

Returns a chat completion from a base model. For OpenAI-compatible HTTP calls, see the Inference quickstart.

Parameters
modelstrRequired

Model ID, for example Qwen3.8-27B.

messageslist[dict]Required

Conversation in chat format.

max_tokensintOptional

Maximum tokens to generate.

temperaturefloatOptional

Sampling temperature.

Returns ChatCompleteResult

result = client.chat_complete(
    model="Qwen3.8-27B",
    messages=[{"role": "user", "content": "Hello!"}],
)

create_deployment()

client.create_deployment(checkpoint=None, base_model=None, unified_replicas=1, wait=False)

Creates a dedicated deployment from a saved checkpoint or a base model, served behind an OpenAI-compatible endpoint.

Parameters
checkpointCheckpointOptional

Checkpoint saved with mode="inference". Provide this or base_model.

base_modelstrOptional

Serve a base model instead of a checkpoint.

unified_replicasintOptional

Number of replicas to start with.

waitboolOptional

Block until the deployment is ready.

Returns Deployment

deployment = client.create_deployment(
    checkpoint=checkpoint,
    unified_replicas=1,
    wait=True,
)
Response
{
  "id": "dep_7Hq2",
  "phase": "ready",
  "model": "dep_7Hq2",
  "base_url": "https://api.rsi-labs.ai/v1/deployments/dep_7Hq2",
  "replicas": 1
}

get_deployment()

client.get_deployment(deployment_id)

Fetches a deployment by ID.

Parameters
deployment_idstrRequired

The deployment's ID.

Returns Deployment

deployment = client.get_deployment("dep_7Hq2")

list_deployments()

client.list_deployments()

Lists your deployments with their phase and replica counts.

Parameters

No parameters.

Returns list[Deployment]

for d in client.list_deployments():
    print(d.id, d.phase, d.replicas)

scale_on_target()

client.scale_on_target(deployment_id, replicas)

Sets the desired number of replicas for a deployment. Autoscaling adjusts within the limits you set.

Parameters
deployment_idstrRequired

The deployment's ID.

replicasintRequired

Desired replica count.

Returns Deployment

client.scale_on_target("dep_7Hq2", replicas=3)

wait_for_deployment()

client.wait_for_deployment(deployment_id, phase="ready", timeout=None)

Blocks until the deployment reaches the given phase, or raises if it fails.

Parameters
deployment_idstrRequired

The deployment's ID.

phasestrOptional

Phase to wait for.

timeoutfloatOptional

Seconds to wait before giving up.

Returns Deployment

client.wait_for_deployment("dep_7Hq2")

delete_deployment()

client.delete_deployment(deployment_id)

Deletes a deployment. Calling it again on a deleted deployment also succeeds.

Parameters
deployment_idstrRequired

The deployment's ID.

Returns None

client.delete_deployment("dep_7Hq2")

get_deployment_usage()

client.get_deployment_usage(deployment_id)

Replica hours and GPU hours a deployment has used so far, across every checkpoint it has served.

Parameters
deployment_idstrRequired

The deployment's ID.

Returns DeploymentUsage

usage = client.get_deployment_usage("dep_7Hq2")
print(usage.replica_hours)

promote()

client.promote(deployment_id, checkpoint)

Serves another inference-mode checkpoint of the same base model behind the same endpoint. The new checkpoint starts beside the old one and takes over once it is ready, so base_url and model do not change and requests keep working.

Parameters
deployment_idstrRequired

The deployment's ID.

checkpointCheckpoint | strRequired

An inference-mode checkpoint, its ID or its path.

Returns Deployment

client.promote(deployment.id, checkpoint=candidate)

list_checkpoints()

client.list_checkpoints(run_id=None, mode=None, limit=100)

Lists checkpoints in your project, newest first.

Parameters
run_idstrOptional

Only this run's checkpoints.

modestrOptional

training or inference.

limitintOptional

At most this many.

Returns list[Checkpoint]

for ckpt in client.list_checkpoints(run_id=model.training_run_id):
    print(ckpt.name, ckpt.step)

get_checkpoint()

client.get_checkpoint(checkpoint)

Gets one checkpoint by ID or path.

Parameters
checkpointCheckpoint | strRequired

ID (ckpt_...) or path (rsi://...).

Returns Checkpoint

ckpt = client.get_checkpoint("ckpt_2pZ8")

delete_checkpoint()

client.delete_checkpoint(checkpoint)

Deletes a checkpoint. Immutable checkpoints cannot be deleted.

Parameters
checkpointCheckpoint | strRequired

The checkpoint, its ID or its path.

Returns None

client.delete_checkpoint(ckpt)

Evals

Private evals live under client.evals. See Private evals and promotion.

evals.create_suite()

client.evals.create_suite(name, prompts, graders)

Creates a suite: held-out examples plus graders. Up to 500 examples and 10 graders.

Parameters
namestrRequired

A name for the suite.

promptslistRequired

Each a prompt string, a list of chat messages, or a dict with prompt or messages and an optional reference.

graderslist[str | Judge]Required

Built-ins "exact_match", "contains", "json_valid", or rsi.Judge(name, rubric, model=None).

Returns EvalSuite

suite = client.evals.create_suite(
    name="support-private-v3",
    prompts=[{"prompt": "Where is my order?", "reference": "tracking"}],
    graders=["contains", rsi.Judge("resolution", "Resolves the issue.")],
)

evals.run()

client.evals.run(candidate, baseline, suite, temperature=None, max_tokens=None, wait=True)

Answers every example with the candidate and the baseline, scores both with every grader and tests each difference for significance. Answers and judge calls are billed as inference tokens.

Parameters
candidateCheckpoint | Deployment | Model | strRequired

What to evaluate: a checkpoint, deployment, live model, base model name, ID or rsi:// path.

baselineCheckpoint | Deployment | Model | strRequired

What to compare against, usually what serves production.

suiteEvalSuite | strRequired

The suite or its ID.

temperaturefloatOptional

Decoding temperature for both sides. Default 0.

max_tokensintOptional

Maximum answer length. Default 1024.

waitboolOptional

Wait for the result (default). With False, returns a pending operation; call result().

Returns EvalRun

run = client.evals.run(candidate=checkpoint, baseline=deployment, suite=suite)
if run.significant_win:
    client.promote(deployment.id, checkpoint=checkpoint)

evals.get_run()

client.evals.get_run(run_id, include_examples=False)

Returns a finished run. With include_examples, every answer and score side by side.

Parameters
run_idstrRequired

The run's ID.

include_examplesboolOptional

Include per-example answers and scores.

Returns EvalRun

run = client.evals.get_run("evr_3Kp9", include_examples=True)
for e in run.examples[:3]:
    print(e.candidate_answer, e.candidate_scores)

evals.list_suites() / list_runs()

client.evals.list_suites() client.evals.list_runs(suite=None)

Lists the project's suites, and its runs (all, or one suite's), newest first. Listed runs leave out examples.

Parameters
suiteEvalSuite | strOptional

Only runs of this suite.

Returns list[EvalSuite] / list[EvalRun]

for run in client.evals.list_runs(suite):
    print(run.id, run.significant_win)

Session

create_model()

session.create_model(base_model, lora=None, checkpoint=None)

Creates a trainable model in the session, with a LoRA adapter or full-weight training, optionally starting from a checkpoint.

Parameters
base_modelstrRequired

Open-weight model to start from.

loraLoraConfigOptional

Train a LoRA adapter. Omit for full-weight training.

checkpointCheckpointOptional

Resume from saved weights.

Returns Model

model = session.create_model(
    base_model="Qwen3.6-35B",
    lora=rsi.LoraConfig(rank=16),
)

sample()

session.sample(prompts, base_model=None, checkpoint=None, num_samples=1, max_tokens=None, stop=None)

Samples completions from a base model or checkpoint and waits for the results.

Parameters
promptslist[str]Required

Prompts to complete.

base_modelstrOptional

Model to sample from.

checkpointCheckpointOptional

Checkpoint to sample from.

num_samplesintOptional

Samples per prompt.

max_tokensintOptional

Maximum tokens per sample.

stoplist[str]Optional

Stop sequences.

Returns list[list[Sample]]

groups = session.sample(prompts=prompts, checkpoint=ckpt, num_samples=4)

Model

train_step()

model.train_step(batch, lr, loss_fn="cross_entropy")

Runs the forward pass, backward pass and an optimizer update in one call.

Parameters
batchlistRequired

Training examples, or RL data with advantages.

lrfloatRequired

Learning rate.

loss_fnstr | LossOptional

Built-in loss such as cross_entropy or importance_sampling, or a custom loss.

Returns OptimStepResult

model.train_step(batch, lr=1e-4, loss_fn="cross_entropy")

forward_backward()

model.forward_backward(data, loss_fn)

Computes the loss and gradients without updating weights. Pair with optim_step() for custom training loops.

Parameters
datalistRequired

Training data.

loss_fnstr | LossRequired

Loss to compute.

Returns ForwardResult

model.forward_backward(data=rl_batch, loss_fn="importance_sampling")

optim_step()

model.optim_step(lr, grad_clip_norm=None, weight_decay=None)

Applies an Adam optimizer update using the accumulated gradients.

Parameters
lrfloatRequired

Learning rate.

grad_clip_normfloatOptional

Clip gradients to this norm.

weight_decayfloatOptional

Weight decay.

Returns OptimStepResult

model.optim_step(lr=4e-5, grad_clip_norm=1.0)

sample()

model.sample(prompts=None, model_input=None, tools=None, num_samples=1, max_tokens=None)

Samples from the model's current in-memory weights, for example to generate RL rollouts.

Parameters
promptslist[str]Optional

Prompts to complete. Pass prompts or model_input.

model_inputlist[dict]Optional

Chat messages instead of prompts, rendered with the base model's chat template. A list of conversations samples several at once.

toolslist[dict]Optional

Functions the model may call, in OpenAI function format. Calls come back parsed in each Sample's tool_calls.

num_samplesintOptional

Samples per prompt.

max_tokensintOptional

Maximum tokens per sample.

Returns list[list[Sample]]

groups = model.sample(prompts=prompts, num_samples=4, max_tokens=4096)

save_weights()

model.save_weights(name, mode="training", immutable=False)

Saves the current weights as a checkpoint and returns it. A training-mode checkpoint keeps optimizer state, so a run can resume from it; an inference-mode checkpoint keeps the adapter weights only, for sampling and deployment. Names are unique within a run.

Parameters
namestrRequired

Checkpoint name: letters, digits, ., _ or -. It becomes the last part of the checkpoint's path.

modestrOptional

training (default) to resume later, or inference to sample or deploy.

immutableboolOptional

Protect the checkpoint from deletion.

Returns Checkpoint

checkpoint = model.save_weights("support-v1", mode="inference")
print(checkpoint.path)  # rsi://runs/run_.../checkpoints/support-v1

load_weights()

model.load_weights(checkpoint, load_optimizer=True)

Replaces the model's weights with a checkpoint's, rewinding its step. Loading optimizer state needs a training-mode checkpoint.

Parameters
checkpointCheckpoint | strRequired

A Checkpoint, or a checkpoint ID (ckpt_...) or path (rsi://...).

load_optimizerboolOptional

Also restore optimizer state (default True).

Returns None

model.load_weights(checkpoint)

log()

model.log(metrics)

Records one set of scalar metrics, shown as charts in the Console.

Parameters
metricsdict[str, float]Required

Metric names and values.

Returns None

model.log({"reward/mean": 0.62, "loss": 1.84})

RL library

from rsi.forge import rl. See Your first RL run for a walkthrough.

NameWhat it is
rl.EnvOne rollout's world: reset(row) returns the opening messages, on_turn(traj) answers the model (default: runs its tool calls), reward(traj, row) scores the result. Also on_error, on_truncated, close.
@rl.toolTurns a function into a tool; the schema comes from type hints and the docstring.
rl.TurnResult(messages, max_turn_tokens=None)What on_turn returns to continue with a token cap for the next turn.
rl.Recover(result)What on_error returns to continue instead of dropping the rollout.
rl.InfrastructureErrorRaise it when your side fails; the run stops instead of training on the outage.
rl.Budget(max_turns=8, max_generated_tokens=32768, max_context_tokens=131072, segment_tokens=4096, final_answer_reserve=0, tool_output_tokens=4096, max_turn_tokens=None)Per-rollout limits.
rl.Truncation(train="zero_reward", by_cause={})How truncated rollouts train: zero_reward, reward, drop or drop_and_exclude_from_baseline.
rl.RolloutEngine(model, *, env, budget, schedule, temperature=1.0, top_p=1.0, top_k=-1, seed=None, sample_timeout=1800, environment_timeout=None)Runs rollouts concurrently: submit(row, group_size=), next_group(), rollout(rows, group_size=), progress().
rl.Schedule(concurrency=256, max_sample_requests=None, admit_ahead=None, oversample_factor=1.0)How much sampling runs at once and how far ahead of training.
rl.AsyncTrainer(*, engine, optimizer, groups_per_step, group_size=16, advantage=GroupCentered(), loss="cispo", normalize=None, max_staleness=2, stale_policy="wait", truncation=Truncation(), train_zero_advantage_batches=False, sinks=(), checkpoint=None, evaluator=None, log_to_console=True)Trains while sampling continues; run(dataset, steps=) yields rl.Step(n, model_step, metrics, trajectories).
rl.run(trainer, dataset, *, steps, on_step=None)Runs the trainer and returns every step.
rl.Adam(lr, beta1=0.9, beta2=0.95, eps=1e-8, weight_decay=0.0, grad_clip_norm=None, schedule=None), rl.cosine(warmup=0, floor=0.0)Optimizer settings and learning-rate schedule.
rl.CISPO(eps_max=6.0), rl.PPO(clip_low=0.2, clip_high=0.2), rl.ImportanceSampling(), rl.DRO(beta=0.05)Losses; each takes normalize = "token" (default), "sequence" or "sum".
rl.GroupCentered(standardize=False), rl.Batchwise(standardize=False)Advantage estimators; any f(rewards, *, min_members) works too.
rl.Checkpointing(run_dir, *, weights_every=20, on_signal=("SIGTERM",))Recovery points: weights, optimizer state and run state every weights_every steps; rerunning the script resumes there.
rl.Evaluator(holdout, *, engine_factory=None, every=20, group_size=4, final_group_size=8, variants=("default",), sink=None)Evaluates held-out rows on saved weights in a separate session; results holds each rl.Evaluation(step, variant, checkpoint, metrics, trajectories).
rl.WandbSink(run, *, table_samples=8), rl.ConsoleSink(model)Metric sinks; the Console sink is on by default (log_to_console=True).
rl.Trajectorymessages, spans (one per model turn, with tokens, logprobs and policy version), reward, truncated, turns, final_text, reward_turn(value), to_data(advantage).

Data types

LoraConfig

rsi.LoraConfig(rank, train_attn=True, train_mlp=True, train_unembed=False)

Configures a LoRA adapter.

Parameters
rankintRequired

Adapter rank.

train_attnboolOptional

Train attention projections.

train_mlpboolOptional

Train MLP and MoE expert layers.

train_unembedboolOptional

Train the unembedding layer.

lora = rsi.LoraConfig(rank=16, train_unembed=True)

Checkpoint

Checkpoint

Saved weights. Returned by save_weights() and the checkpoint calls on Client. Anywhere a checkpoint is accepted, you can pass the Checkpoint, its id or its path.

Attributes
idstrRequired

The checkpoint's ID (ckpt_...).

pathstrRequired

rsi://runs/<run>/checkpoints/<name>.

namestrRequired

Checkpoint name, unique within the run.

modestrRequired

training or inference.

stepintRequired

The training step it was saved at.

base_modelstrRequired

The base model it adapts.

created_atdatetimeRequired

When it was saved.

expires_atdatetime | NoneRequired

When it expires, or None if it is kept until deleted.

ckpt = client.get_checkpoint("rsi://runs/run_7Hq2/checkpoints/support-v1")
print(ckpt.mode, ckpt.step)

Deployment

Deployment

A dedicated deployment serving a checkpoint or base model.

Attributes
idstrRequired

Deployment ID.

phasestrRequired

Lifecycle phase, for example ready.

modelstrRequired

Model name to pass in API calls.

base_urlstrRequired

OpenAI-compatible base URL.

replicasintRequired

Current replica count.

EvalRun

FieldType
idstrevr_...
suite_idstr
significant_winboolBetter with significance on at least one grader, worse on none
metricsdict[str, GraderResult]Per grader: candidate, baseline (mean scores, 0 to 1), delta, p_value, significant
alphafloatThe significance level, 0.05
example_countint
exampleslist[EvalExample]Only from get_run(..., include_examples=True)

Sample

Sample

One sampled completion.

Attributes
textstrRequired

Decoded completion.

tokenslist[int]Required

Completion token IDs.

logprobslist[float]Required

Log-probabilities of the completion tokens.

tool_callslist[ToolCall]Optional

Tool calls the model made when tools were offered: id, name and arguments (JSON text; parsed_arguments() returns a dict).