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.
api_keystrRequiredYour API key.
endpointstrOptionalHost to connect to. Defaults to the fully managed API; set it to your Cell's host for VPC or on-prem.
timeoutfloatOptionalRequest timeout in seconds.
enable_retriesboolOptionalRetry 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.
projectstrOptionalGroups 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.
modelstrRequiredModel ID, for example Qwen3.8-27B.
messageslist[dict]RequiredConversation in chat format.
max_tokensintOptionalMaximum tokens to generate.
temperaturefloatOptionalSampling 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.
checkpointCheckpointOptionalCheckpoint saved with mode="inference". Provide this or base_model.
base_modelstrOptionalServe a base model instead of a checkpoint.
unified_replicasintOptionalNumber of replicas to start with.
waitboolOptionalBlock until the deployment is ready.
Returns Deployment
deployment = client.create_deployment(
checkpoint=checkpoint,
unified_replicas=1,
wait=True,
){
"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.
deployment_idstrRequiredThe 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.
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.
deployment_idstrRequiredThe deployment's ID.
replicasintRequiredDesired 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.
deployment_idstrRequiredThe deployment's ID.
phasestrOptionalPhase to wait for.
timeoutfloatOptionalSeconds 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.
deployment_idstrRequiredThe 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.
deployment_idstrRequiredThe 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.
deployment_idstrRequiredThe deployment's ID.
checkpointCheckpoint | strRequiredAn 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.
run_idstrOptionalOnly this run's checkpoints.
modestrOptionaltraining or inference.
limitintOptionalAt 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.
checkpointCheckpoint | strRequiredID (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.
checkpointCheckpoint | strRequiredThe 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.
namestrRequiredA name for the suite.
promptslistRequiredEach a prompt string, a list of chat messages, or a dict with prompt or messages and an optional reference.
graderslist[str | Judge]RequiredBuilt-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.
candidateCheckpoint | Deployment | Model | strRequiredWhat to evaluate: a checkpoint, deployment, live model, base model name, ID or rsi:// path.
baselineCheckpoint | Deployment | Model | strRequiredWhat to compare against, usually what serves production.
suiteEvalSuite | strRequiredThe suite or its ID.
temperaturefloatOptionalDecoding temperature for both sides. Default 0.
max_tokensintOptionalMaximum answer length. Default 1024.
waitboolOptionalWait 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.
run_idstrRequiredThe run's ID.
include_examplesboolOptionalInclude 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.
suiteEvalSuite | strOptionalOnly 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.
base_modelstrRequiredOpen-weight model to start from.
loraLoraConfigOptionalTrain a LoRA adapter. Omit for full-weight training.
checkpointCheckpointOptionalResume 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.
promptslist[str]RequiredPrompts to complete.
base_modelstrOptionalModel to sample from.
checkpointCheckpointOptionalCheckpoint to sample from.
num_samplesintOptionalSamples per prompt.
max_tokensintOptionalMaximum tokens per sample.
stoplist[str]OptionalStop 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.
batchlistRequiredTraining examples, or RL data with advantages.
lrfloatRequiredLearning rate.
loss_fnstr | LossOptionalBuilt-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.
datalistRequiredTraining data.
loss_fnstr | LossRequiredLoss 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.
lrfloatRequiredLearning rate.
grad_clip_normfloatOptionalClip gradients to this norm.
weight_decayfloatOptionalWeight 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.
promptslist[str]OptionalPrompts to complete. Pass prompts or model_input.
model_inputlist[dict]OptionalChat messages instead of prompts, rendered with the base model's chat template. A list of conversations samples several at once.
toolslist[dict]OptionalFunctions the model may call, in OpenAI function format. Calls come back parsed in each Sample's tool_calls.
num_samplesintOptionalSamples per prompt.
max_tokensintOptionalMaximum 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.
namestrRequiredCheckpoint name: letters, digits, ., _ or -. It becomes the last part of the checkpoint's
path.
modestrOptionaltraining (default) to resume later, or inference to sample or deploy.
immutableboolOptionalProtect the checkpoint from deletion.
Returns Checkpoint
checkpoint = model.save_weights("support-v1", mode="inference")
print(checkpoint.path) # rsi://runs/run_.../checkpoints/support-v1load_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.
checkpointCheckpoint | strRequiredA Checkpoint, or a checkpoint ID (ckpt_...) or path (rsi://...).
load_optimizerboolOptionalAlso 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.
metricsdict[str, float]RequiredMetric 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.
| Name | What it is |
|---|---|
rl.Env | One 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.tool | Turns 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.InfrastructureError | Raise 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.Trajectory | messages, 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.
rankintRequiredAdapter rank.
train_attnboolOptionalTrain attention projections.
train_mlpboolOptionalTrain MLP and MoE expert layers.
train_unembedboolOptionalTrain the unembedding layer.
lora = rsi.LoraConfig(rank=16, train_unembed=True)Checkpoint
CheckpointSaved 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.
idstrRequiredThe checkpoint's ID (ckpt_...).
pathstrRequiredrsi://runs/<run>/checkpoints/<name>.
namestrRequiredCheckpoint name, unique within the run.
modestrRequiredtraining or inference.
stepintRequiredThe training step it was saved at.
base_modelstrRequiredThe base model it adapts.
created_atdatetimeRequiredWhen it was saved.
expires_atdatetime | NoneRequiredWhen 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
DeploymentA dedicated deployment serving a checkpoint or base model.
idstrRequiredDeployment ID.
phasestrRequiredLifecycle phase, for example ready.
modelstrRequiredModel name to pass in API calls.
base_urlstrRequiredOpenAI-compatible base URL.
replicasintRequiredCurrent replica count.
EvalRun
| Field | Type | |
|---|---|---|
id | str | evr_... |
suite_id | str | |
significant_win | bool | Better with significance on at least one grader, worse on none |
metrics | dict[str, GraderResult] | Per grader: candidate, baseline (mean scores, 0 to 1), delta, p_value, significant |
alpha | float | The significance level, 0.05 |
example_count | int | |
examples | list[EvalExample] | Only from get_run(..., include_examples=True) |
Sample
SampleOne sampled completion.
textstrRequiredDecoded completion.
tokenslist[int]RequiredCompletion token IDs.
logprobslist[float]RequiredLog-probabilities of the completion tokens.
tool_callslist[ToolCall]OptionalTool calls the model made when tools were offered: id, name and arguments (JSON text; parsed_arguments() returns a dict).