Python
v0.4.0The 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 before1.0.0.
Install
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
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 taskmachinecan 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:
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()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:
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.
session.run("Export last month's invoices to CSV", autonomous=True)Files, models, stopping
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.
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_invalidsend() 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:
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.
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.
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 resultstemplate 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.
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 anExecResultwithresult,logs,error,screenshot,screenshot_mime_typeandduration_ms. A block that throws still returns: checkr.error.kind(exception,timeout,interrupted).- Use
var, notletorconst, 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 raisesBlockError, 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
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 manysai.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 firstHand 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.
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 revokedlive_urlandexpires_at(Unix time in milliseconds) areNonewhere the server does not offer the page.live_urlis left out ofrepr(), likewebsocket_url, because it carries a token.websocket_urlis the same screen as a Guacamole tunnel for a viewer of your own. It takes input too.machines.revoke_live(machine) -> intrevokes everylive_urlhanded 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.
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: passtoken.tokenasSai(api_key=...).org_idis needed only for the exchange. It defaults toSAI_ORG_ID;token()andclient()also takeorg_id=.org.tenants.list(status=, external_id=, limit=, cursor=)returns one page:page.tenantsandpage.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)andorg.tenant_machines.revoke(tenant, machine).
A Tenant can also have cloud machines that Sai hosts:
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).osis"windows"or"linux". Pass the samerequest_idwhen you retry a create. Withwait=Trueit gets the machine every 5 seconds until itsstateisready. Afailedordeletingmachine raisesSaiErrorwith the machine ine.body. Noreadywithintimeoutseconds raisesTimeoutError.org.tenant_machines.list(tenant)and.get(tenant, machine_id)return both kinds. Each machine haskind,state,machine_class(cloud only) andcreated_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=Noneremoves the limit.residential_proxyhas no effect yet.- A refused create raises the usual
SaiErrorsubclass. Its details are ine.body:limitandused,scopeandresetsAt, orerrorId.
See Tenants for every field and error.
What your Tenants spent
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, perhour,dayormonth. 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 passingpage.next_cursorascursoruntil it isNone: a page can be empty and not be the last. Withsession_ids=[...](1 to 50) instead of the range, it is those sessions' spend right now, each withsettled(Trueonce its latest task has ended and every charge for it has come in), and the page'sas_of;cost_usdandmodel_callsareNonewhen a session can't be read in full right now. See Session spend.- Both take
org_id=, defaulting to the client'sorg_id(SAI_ORG_ID).
Errors
Every non-2xx response raises a SaiError subclass carrying status, code, message and retry_after:
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.