Docs/Python
SDKs

Python

v0.4.0

The Python SDK wraps the API on these pages:

  • Sessions: give Sai a task on a computer, and get the answer back. Sai decides every click.
  • Direct control: your code drives a computer directly with Simulang. No agent decides the steps; only the model calls your code makes are billed.

Note

Current version is 0.4.0. The API may still change before 1.0.0.

Install

InstallShell
pip install sai-sdk
export SAI_API_KEY="sapi_..."

The import name is sai. Python 3.10 or later; one dependency, httpx. Create the key in the portal (see Quickstart).

Give Sai a task

Give Sai a taskPython
from sai import Sai

sai = Sai()
pc = sai.machines.list()[0]

session = sai.sessions.create(machine=pc)
result = session.run("Open Notepad, type hello, save it to the desktop as hello.txt")

print(result.status)  # idle, needs_approval or error
print(result.text)    # Sai's answer
print(result.usage)   # tokens and cost of this task
  • machine can be left out when the account has one computer.
  • More session.run(...) calls continue the same conversation. sai.sessions.create() starts a new one with no memory of the old. See Sessions.
  • run() sends the task and waits. On a free account the first task of the day waits about two minutes while the computer starts.

Watch it work

send() returns at once with a turn. Iterate its events, then read the result:

Watch the eventsPython
turn = session.send("Find last month's invoices in Downloads and total them")
for ev in turn.events():
    if ev.kind == "step":
        print("  ", ev.text)
    elif ev.kind == "approval":
        turn.respond(ev.approval, "yes")
result = turn.wait()
ev.kindWhat it is
stepA progress line: what Sai is doing
messageSai's text
approvalSai is waiting for permission. ev.approval holds it
tool_errorA step failed. Sai usually recovers
errorThe turn failed. ev.code is set when the account ran out (below)
finishedThe turn is complete

turn.events(raw=True) also yields reasoning, tool-call and framing frames as other, with the wire event in ev.raw. See Events.

Approvals

Sai asks before risky actions (see Approvals). Without a handler, run() and wait() return with status == "needs_approval" and the request in result.approval. To answer as it comes, pass on_approval:

Approval handlerPython
def decide(approval):
    if approval.is_link_only:
        print("Approve in a browser:", approval.url)
        return None  # a person answers it; keep waiting
    if approval.type == "choice":
        return ("yes", [[q["options"][0]["value"]] for q in approval.questions])
    return "yes"

result = session.run("Clean up the temp folder", on_approval=decide)

The handler returns "yes", "no", "task" (allow the rest of this task), a (response, selections) pair for a choice, or None to leave the approval to someone else. A link-only approval cannot be answered over the API: respond() raises LinkOnlyApprovalError with approval_url.

For an unattended run with nobody to answer, pass autonomous=True (from sai-sdk 0.1.0a4). The turn runs as if "task" had been answered up front, and the grant ends with the turn. Link-only approvals still stop it. See Unattended runs.

Unattended runPython
session.run("Export last month's invoices to CSV", autonomous=True)

Files, models, stopping

Files, models, stoppingPython
report = sai.files.upload("report.pdf")
session.run("Summarise the attached report", attachments=[report])

allowed = [m.id for m in sai.models.list() if m.allowed]
session.run("...", model="anthropic/claude-opus-5-5")  # sticks to the session

turn = session.send("...")
turn.abort()

A message sent while a turn is running steers that turn; turn.queued is then True.

Typed output (advanced)

Pass output_schema and the turn's record comes back in result.record, with output matching the schema. See Structured output for every option.

Typed outputPython
result = session.run(
    "Open https://news.ycombinator.com and read the title of the top story.",
    output_schema={"type": "object", "properties": {"title": {"type": "string"}}, "required": ["title"]},
)
if result.ok:
    print(result.record.output["title"])
else:
    print(result.record.reason_code)   # e.g. output_invalid

send() and run() also take inputs, success_criteria (a string, or a list of Check), idempotency_key and record_trajectory, and thinking_level ("off", "low", "medium", "high" or "xhigh"). Every turn has an id, turn.id; read it later with sai.turns:

Read a turn laterPython
turn = session.send("...", record_trajectory=True)
record = sai.turns.wait(turn)               # until succeeded, failed or needs_input
for step in sai.turns.trajectory(turn):
    print(step.index, step.title)

Learn code from turns (research preview)

sai.learn turns recorded turns into Simulang code you run with a control lease, and repairs it. sai.judge checks recorded turns against criteria you choose afterwards. See Learned code.

Learn and repair codePython
from sai import Check, Evaluation

turn = session.send(
    "Open {{newsSite}}, find all {{topic}} news published today, write their headlines into Notepad, one per line, and save the file as {{fileName}}",
    inputs={"newsSite": "TechCrunch", "topic": "AI", "fileName": "techcrunch_headlines.txt"},
    record_trajectory=True,
)
sai.turns.wait(turn)

learned = sai.learn.create([turn])            # waits for the code; longer for a longer task
with sai.control.open(machine=pc) as lease:
    r = lease.run(learned, {"newsSite": "TechCrunch", "topic": "Fintech", "fileName": "techcrunch_fintech.txt"})   # inputs over the defaults
    print(r.result)

fixed = sai.learn.create(
    initial_code=learned.code,
    evaluations=[Evaluation(inputs={"newsSite": "TechCrunch", "topic": "Fintech", "fileName": "techcrunch_fintech.txt"}, result=r, passed=False)],
)
judgement = sai.judge.create([turn], [Check("file", "The agent saved the headlines to the file")])

learned.status is failed when the code still has learned.validation["errors"].

With max_iterations, learn also runs the code on a computer, judges each run and repairs the code until it passes, starting from your turns or, without them, from an agent run of task_template. The call answers at once with a learn job; wait reads it until it ends.

Run, judge and repair on a computerPython
job = sai.learn.create(
    task_template="Open {{newsSite}}, find all {{topic}} news published today, write their headlines into Notepad, one per line, and save the file as {{fileName}}",
    inputs={"newsSite": "TechCrunch", "topic": "AI", "fileName": "techcrunch_headlines.txt"},
    machine=pc,
    criteria="techcrunch_headlines.txt is saved and holds only the headlines of the AI articles TechCrunch published today, one per line, with no text left from earlier runs",
    max_iterations=3,          # up to 3 code versions; 0 (the default) only writes the code
    rollouts=3,                # each version must pass 3 runs in a row
    continue_with_agent=True,  # after a failed run, the agent finishes the task and the repair learns from it
)
done = sai.learn.wait(job)     # can take an hour; timeout= to stop waiting
print(done.status, done.stop_reason, done.test_result)
print(done.code)               # the latest version
for it in done.iterations:
    print(it.index, it.changes, [r.verdict for r in it.rollouts])

run = sai.learn.rollout(job, 1, 1)   # what one run returned and logged, and its judgement
sai.learn.cancel(job)                # stops at once and keeps the last complete results

template and feedback are still accepted as the old names of task_template and guidance.

Drive a computer yourself

A control lease holds one computer and runs Simulang blocks on it. Use it as a context manager: while it is open, Sai's own tasks on that computer wait.

Drive a computerPython
with sai.control.open(machine=pc) as lease:
    print(lease.shell("hostname")["stdout"])

    lease.write_file(r"C:\data\note.txt", "hello")
    print(lease.read_file(r"C:\data\note.txt"))

    r = lease.exec("""
        var page = await machine.browser.newtab('https://example.com')
        var snap = await page.snapshot()
        snap.title
    """)
    print(r.result)  # Example Domain
    ext = r.screenshot_mime_type.split("/")[1]  # jpeg or png
    open(f"page.{ext}", "wb").write(r.screenshot)
  • exec() returns an ExecResult with result, logs, error, screenshot, screenshot_mime_type and duration_ms. A block that throws still returns: check r.error.kind (exception, timeout, interrupted).
  • Use var, not let or const, for values the next block needs.
  • lease.screenshot() grabs the whole screen. It needs the computer's screen-capture service; where that is off it raises BlockError, and a page or app snapshot is the way to get an image.
  • lease.interrupt() stops a running block from another thread.

Direct control is a research preview, open to every account; the model calls the code makes are billed as usual. See Control for limits and errors.

Other calls

Other callsPython
sai.account.get()      # plan and spendable credit
sai.models.list()      # models, with `allowed` for this plan
sai.machines.live(pc)  # a link to the screen for a person, and a stream for your viewer; see Live view
sai.machines.revoke_live(pc)  # every live_url stops working and its screen sessions end; returns how many
Who the key is, and its sessionsPython
sai.auth.check()            # the user, and the Tenant and Organisation for a Tenant token
sai.sessions.list(machine=pc)  # your sessions on the computer, any channel, most recent first

Hand the screen to a person

When Sai needs a person at the screen (a sign-in, a captcha), machines.live returns a LiveView with live_url: a page anyone with the link can open without a Simular account. They can use the mouse and keyboard. The page pauses its own input while a Sai turn runs; the pause is not enforced. Send a message once they are done, and revoke the link.

Hand the screen to a personPython
view = sai.machines.live(pc)
print("Sign in here, then tell me:", view.live_url)  # valid until view.expires_at (ms)
# ... once they are done
session.run("I signed in. Carry on.")
sai.machines.revoke_live(pc)  # returns the number of links revoked
  • live_url and expires_at (Unix time in milliseconds) are None where the server does not offer the page. live_url is left out of repr(), like websocket_url, because it carries a token.
  • websocket_url is the same screen as a Guacamole tunnel for a viewer of your own. It takes input too.
  • machines.revoke_live(machine) -> int revokes every live_url handed out for the computer and ends the screen sessions they opened. See When Sai needs a person.

Run Sai for your customers

With an Organisation, each customer is a Tenant. Your backend manages Tenants with an Organisation Key, and acts as one Tenant through a Tenant token.

TenantsPython
import os
from sai import Sai

org = Sai(api_key=os.environ["SAI_ORG_KEY"], org_id="org_3f9a1c0b7e2d4a6f8c10")

tenant = org.tenants.create("Riverside Clinic", external_id="clinic-4821")
enrollment = org.tenants.create_enrollment(tenant)  # hand enrollment.token to your installer
print(org.tenant_machines.list(tenant))

clinic = org.tenants.client(tenant)  # acts as the Tenant
clinic.sessions.create().run("Open the calendar and read today's appointments")
  • org.tenants.client(tenant) exchanges the Organisation Key for a one-hour Tenant token, and exchanges again when it has less than five minutes left. org.tenants.token(tenant) is the exchange alone: pass token.token as Sai(api_key=...).
  • org_id is needed only for the exchange. It defaults to SAI_ORG_ID; token() and client() also take org_id=.
  • org.tenants.list(status=, external_id=, limit=, cursor=) returns one page: page.tenants and page.next_cursor. external_id= finds your customer's Tenant without storing its id.
  • org.tenants.update(tenant, name=, metadata=, status=). status="disabled" stops the Tenant, "active" brings it back. org.tenants.delete(tenant) disables it and revokes every machine.
  • org.tenant_machines.get(tenant, machine_id) and org.tenant_machines.revoke(tenant, machine).

A Tenant can also have cloud machines that Sai hosts:

Cloud machinesPython
import os
import uuid
from sai import Sai

org = Sai(api_key=os.environ["SAI_ORG_KEY"], org_id="org_3f9a1c0b7e2d4a6f8c10")

machine = org.tenant_machines.create(
    "Xk2p9QzR4tLm8vNa3bCd",
    os="windows",
    name="Riverside intake",
    request_id=str(uuid.uuid4()),
    wait=True,
)
clinic = org.tenants.client("Xk2p9QzR4tLm8vNa3bCd")
clinic.sessions.create(machine=machine.id).run("Open Notepad and type hello")
org.tenant_machines.delete("Xk2p9QzR4tLm8vNa3bCd", machine)
  • org.tenant_machines.create(tenant, os=, name=, request_id=, wait=False, timeout=600). os is "windows" or "linux". Pass the same request_id when you retry a create. With wait=True it gets the machine every 5 seconds until its state is ready. A failed or deleting machine raises SaiError with the machine in e.body. No ready within timeout seconds raises TimeoutError.
  • org.tenant_machines.list(tenant) and .get(tenant, machine_id) return both kinds. Each machine has kind, state, machine_class (cloud only) and created_at.
  • org.tenant_machines.delete(tenant, machine) returns "deleting" for a cloud machine and "revoked" for an enrolled one.
  • org.tenants.update(tenant, cloud_machine_limit=, residential_proxy=). cloud_machine_limit=None removes the limit. residential_proxy has no effect yet.
  • A refused create raises the usual SaiError subclass. Its details are in e.body: limit and used, scope and resetsAt, or errorId.

See Tenants for every field and error.

What your Tenants spent

UsagePython
import os
from sai import Sai

org = Sai(api_key=os.environ["SAI_ORG_KEY"], org_id="org_3f9a1c0b7e2d4a6f8c10")
usage = org.usage.get(granularity="month", from_="2026-10", to="2026-10")
for t in usage.totals.by_tenant.values():
    print(t.name, t.cost_cents)

page = org.usage.sessions("Xk2p9QzR4tLm8vNa3bCd", from_="2026-10-01", to="2026-10-31")
for s in page.sessions:
    print(s.session_id, s.cost_usd)
  • org.usage.get(granularity=, from_=, to=) is what the Organisation is charged, in total and per Tenant, per hour, day or month. See Organisation usage.
  • org.usage.sessions(tenant, from_=, to=, limit=, cursor=) is one page of what each of the Tenant's sessions spent on AI calls. Keep passing page.next_cursor as cursor until it is None: a page can be empty and not be the last. With session_ids=[...] (1 to 50) instead of the range, it is those sessions' spend right now, each with settled (True once its latest task has ended and every charge for it has come in), and the page's as_of; cost_usd and model_calls are None when a session can't be read in full right now. See Session spend.
  • Both take org_id=, defaulting to the client's org_id (SAI_ORG_ID).

Errors

Every non-2xx response raises a SaiError subclass carrying status, code, message and retry_after:

ExceptionWhen
AuthenticationError401: the key is missing, unknown or revoked
BadRequestError400: for example several computers and no machine=
PermissionDeniedError403: plan or ownership, such as model_not_allowed_for_plan
ConflictError409: for example machine_busy, or an approval already answered
LinkOnlyApprovalErrorThe approval must be answered in a browser: e.approval_url
GoneError410: the control lease ended (e.body["reason"]). Open a new one
SpendCapReachedError403: the key reached its monthly spend limit. e.resets_at
RateLimitError429: a rate limit, or the free plan's daily computer time
ServiceUnavailableError503: the computer did not come online. Honor retry_after
BlockErrorA control helper's block failed on the computer

A task that ran out of credit is not an exception. It ends with result.status == "error" and result.error_code set to insufficient_credits or free_computer_time_exhausted. Stop retrying for today. See Billing and limits.

Configuration

ArgumentEnvironmentDefault
api_keySAI_API_KEYrequired
base_urlSAI_API_URLhttps://api.simular.ai
timeout60 seconds per request
org_idSAI_ORG_IDfor tenants.token() and usage
© 2026 Simular Inc. All rights reserved.