Agents APIReference
Python SDK
latentcode_sandbox_agents 0.1.4: the same client as the TypeScript one, in sync and asyncio variants. Python 3.10+, one dependency (httpx).
Install
pip install https://latentstack.dev/dl/latentcode_sandbox_agents-0.1.4-py3-none-any.whlWorks with uv pip install and poetry add too. In requirements.txt, list the URL on its own line. To pin a copy, download the wheel and install the file.
Create a client
import os
from latentcode_sandbox_agents import LatentStack
client = LatentStack(api_key=os.environ["LS_API_KEY"])
sessions = client.agents.sessions
# ... and when you're done (or use "with LatentStack(...) as client:")
client.close()LatentStack(api_key: str, *, base_url: str | None = None,
transport: httpx.BaseTransport | None = None,
timeout: float | httpx.Timeout | None = 60.0)| Argument | |
|---|---|
| api_key | Required. Your ls-… key. |
| base_url | Your LatentStack URL, if it isn't https://latentstack.dev. |
| transport | Your own httpx transport, for proxies or tests. |
| timeout | Per-request timeout in seconds. The event stream is not bounded by it. |
asyncio
AsyncLatentStack takes the same arguments. Its methods are coroutines, and events() is an async iterator. Close the stream explicitly if you break out of it early:
import asyncio
import os
from contextlib import aclosing
from latentcode_sandbox_agents import AsyncLatentStack
async def main() -> None:
async with AsyncLatentStack(api_key=os.environ["LS_API_KEY"]) as client:
sessions = client.agents.sessions
session = await sessions.create(
agent={"model": "anthropic/claude-sonnet-5.5", "instructions": "Answer briefly."},
input="Name three uses of a lighthouse.",
)
try:
# aclosing() closes the stream when you break out early.
async with aclosing(sessions.events(session["id"])) as events:
async for event in events:
if event["type"] == "text.ended":
print(event["data"]["text"])
if event["type"] in ("run.completed", "run.failed"):
break
finally:
await sessions.delete(session["id"])
asyncio.run(main())client.agents.sessions
Responses are plain dicts with the same fields as the TypeScript types. The package's TypedDicts (Session, StreamFrame, Event, …) give your editor the keys. All options are keyword-only.
Lifecycle
create(*, agent, environment=None, input=None, metadata=None,
idempotency_key=None, limits=None, files=None, outputs=None,
end_after_run=None, webhook=None) -> Sessionenvironment["network"] sets what the sandbox can reach; limits caps what the session may spend. idempotency_key makes the call safe to retry. files, outputs and end_after_run are on Outputs, and webhook on Webhooks.get(session_id) -> Sessionlimits, stop_reason and usage.list(*, limit=None, after=None) -> SessionListnext_after as after for the next page.delete(session_id) -> Sessionpause(session_id) -> Sessionresume(session_id) -> Sessionvolume_kept_until).fork(session_id, *, input=None, metadata=None, limits=None, outputs=None,
end_after_run=None, webhook=None, idempotency_key=None) -> Sessionupdate(session_id, *, limits) -> SessionNone removes one.Input
message(session_id, text, *, delivery=None, files=None) -> InputAccepteddelivery: "steer" (default) or "queue". files: workspace paths of images (png, jpeg, gif or webp) to put in front of the model with the text.approve(session_id, request_id, reply, message=None) -> InputAcceptedreply: "once", "always" or "reject".cancel(session_id) -> InputAcceptedsend(session_id, input) -> InputAcceptedFollowing
events(session_id, *, after=None, stop=None, retry_delay=None) -> Iterator[StreamFrame]stopped or failed, or when stop is set.| Argument | |
|---|---|
| after | Start after this seq. Default: from the beginning. |
| stop | A threading.Event (asyncio.Event for the async client). It may take a few seconds to stop. |
| retry_delay | Fixed seconds between reconnects. Default: 1, 2, 3 … per failed attempt; gives up after 5. |
wait(session_id, *, until=None, timeout=600.0, poll=2.0) -> Sessionuntil (default SETTLED). Raises LatentStackError(type="timeout") after timeout seconds. Right after create() a session is briefly idle before its first message starts, so follow events() to know a task is done.Artifacts
artifacts(session_id) -> ArtifactListartifact(session_id, name="patch", *, repo=None) -> strrepo is required with several repositories.Files
Paths are relative to the workspace, like uploads/photo.png. A path with a . or .. segment, or a leading or trailing slash, raises invalid_request before anything is sent. See Files.
upload_file(session_id, path, data, *, content_type="application/octet-stream") -> FileInfodata at path: bytes, an open binary file, or a path to a file to read. A str is a path, not content. Missing folders are created, and an existing file is replaced. Returns the stored file's path, size and sha256.download_file(session_id, path) -> byteslist_files(session_id, *, prefix=None, limit=None) -> FileListprefix, in path order, up to limit (1,000 at most). .git is left out. truncated is true when there were more.delete_file(session_id, path) -> NoneErrors
from latentcode_sandbox_agents import LatentStackError
try:
sessions.get("ags_missing")
except LatentStackError as e:
print(e.status, e.type, e.message) # 404 not_found No session 'ags_missing'.status is 0 when no response arrived (network_error). See Errors for all types.
Exports
| Export | What |
|---|---|
| LatentStack · AsyncLatentStack | The clients. |
| Sessions · AsyncSessions · Agents · AsyncAgents | The classes behind client.agents.sessions. |
| Webhooks · Events · Schedules (and Async…) | The classes behind client.agents.webhooks, client.agents.events and client.agents.schedules. |
| LatentStackError | The error: status, type, message. |
| verify_webhook · WebhookVerificationError | Checks a webhook delivery and returns its event, or raises. See Verify the signature. |
| SETTLED · DEFAULT_BASE_URL · __version__ | Constants. |
| TypedDicts | Session, SessionList, SessionStatus, SessionStatusName, Agent, Rule, Effect, Environment, EnvironmentNone, EnvironmentRepos, RepoSpec, Network, Limits, LimitsView, Spent, SubagentSpent, Usage, StopReason, Event, StreamFrame, ApprovalRequested, PendingApproval, SessionInput, MessageInput, ApprovalInput, CancelInput, ApprovalReply, Delivery, InputAccepted, Artifact, ArtifactList, FileChange, FileInfo, FileList, InstanceContext, ApiError, Output, OutputList, InlineWebhook, WebhookEndpoint, WebhookEndpointList, WebhookDelivery, WebhookDeliveryList, WebhookAttempt, DeliveryStatus, WebhookEvent, EventList, EventSession, Schedule, ScheduleList, ScheduleRun, ScheduleRunList, ScheduleOutcome, StagedFile, Concurrency |
Upgrading
- Each new version has its own install URL; see Install above. Reinstall from the new URL.
latentcode_sandbox_agents.__version__tells you what you have.0.1.2addedlimitsandenvironment["network"]oncreate(), andlimits,usageandstop_reasonon the session.0.1.3addedupload_file(),download_file(),list_files(),delete_file()and thefilesargument onmessage().0.1.4addedclient.agents.webhooks,client.agents.eventsandclient.agents.schedules;outputs(),delete_output()andwebhook_deliveries()on sessions; thefiles,outputs,end_after_runandwebhookarguments oncreate(); andverify_webhook()withWebhookVerificationError; andupdate()to raise a session's limits. A spend limit now pauses a session instead of stopping it, andresume()brings back a stopped one for 7 days. See Webhooks, Outputs and Schedules.