Skip to main content

esoul — build agent networks in Python

esoul is the official Python SDK for the ExternalSoul platform.

Two headline surfaces:

  • Track training runs — use a workspace as your TensorBoard. One run.log({...}) in your PyTorch loop (~1.5 µs, never blocks), live curves with min/max bands, per-epoch sample images, 50-run comparison, crash-resume, DDP-aware — and an agent that can read the curves and tell you the run has plateaued.
  • The agent-network builder — declare a multi-agent network in a few lines of Python, get a clean auto-laid-out graph, create it in a workspace, run it, fan it out over your data, and durably resume it if it fails partway.
pip install esoul
import esoul
from esoul.agent_builder import AgentNetwork

client = esoul.Esoul()                         # auto-detects credentials

# Declare an agent network — nodes + edges, no positions, no JSON blob.
net = AgentNetwork("Researcher", model="anthropic/claude-3-5-haiku-20241022")
trigger = net.trigger()                        # fires on agent_builder/run
agent   = net.agent("Researcher", system_prompt="Answer concisely, then save to Notes.")
notes   = net.tool_binding("My Notes", application_type="note_editor")
trigger >> agent                               # wire edges with `>>`
agent   >> notes

# Auto-laid-out (no overlapping cards) + created as a workspace app.
app = net.create(client, workspace_id="ws_abc", instance_name="researcher")

# Run it and wait for the result.
result = client.agents.invoke(
    app.node_id, workspace_id="ws_abc",
    input="Summarise the Q3 metrics into My Notes.",
).wait()
print(result.text)

The builder — esoul.agent_builder.AgentNetwork

AgentNetwork produces the exact state the agent-builder UI persists, so a code-built network opens, edits, and runs identically to a hand-built one.

Nodes

Each constructor returns a NodeRef (its .id is the generated node id):

Method Node
net.trigger(event=…, prompt_template=…, run_mode=…) a trigger — what the network waits for (default agent_builder/run)
net.agent(name, system_prompt=…, model=…, description=…, context_apps=…) an agent
net.tool_binding(app, application_type=…) a Tool Binding — gives an agent a workspace app's full toolkit
net.workspace_tool(tool_names, label=…) a Workspace Tool node (e.g. ["return_result_to_router"])
net.sub_agent_mapper(sub_agent_app_node_id=…, source_mode=…, source_config=…) a Sub-Agent Mapper (fan-out — see below)
net.add_node(node_type, data, node_id=…) generic escape hatch for any other node type (image_edit_agent, search, open_app, …)

Node ids are unique per network (a short token is stamped in), so two code-built networks never collide.

Edges

trigger >> agent >> mapper        # chainable; `a >> b` returns b
net.connect(router, billing, routing_prompt="billing questions")   # agent→agent routing label
net.connect(driver, mapper, mapper_meta={"iterationMode": "per_row", "label": "fill each row"})

Models

model= accepts a gateway string ("anthropic/claude-3-5-haiku-20241022"), a {"provider", "model"} dict, or None (network default). Set it per-network (AgentNetwork(..., model=…)) or per-agent (net.agent(..., model=…)).

Layout, serialise, create

net.auto_layout()          # clean, non-overlapping positions (also runs inside to_state)
state = net.to_state()     # the raw dict — pass to apps.create(initial_state=...) yourself
app   = net.create(client, workspace_id=ws, instance_name="my-net")   # …or one call

The layout is a pure, deterministic layered (Sugiyama-style) placement; from esoul.agent_builder import assert_no_overlap lets your tests prove a graph is clean.


Fan out over data — the Sub-Agent Mapper

Point a sub_agent_mapper node at a spreadsheet column and it runs one sub-agent per cell, in parallel:

sub  = AgentNetwork("Filler", model="anthropic/claude-3-5-haiku-20241022")
t = sub.trigger(); a = sub.agent("Filler", system_prompt="Fill one cell.")
t >> a; a >> sub.tool_binding("Cities", application_type="spreadsheet")
sub_app = sub.create(client, workspace_id=ws, instance_name="filler")

main = AgentNetwork("Driver", model="anthropic/claude-3-5-haiku-20241022")
driver = main.agent("Driver", system_prompt="Hand off to the mapper.")
mapper = main.sub_agent_mapper(
    sub_agent_app_node_id=sub_app.node_id,
    source_mode="spreadsheet",
    source_config={"spreadsheetName": "Cities", "inputColumnName": "City", "filters": []},
)
main.connect(driver, mapper, mapper_meta={"iterationMode": "per_row"})
main_app = main.create(client, workspace_id=ws, instance_name="driver")

client.agents.invoke(main_app.node_id, workspace_id=ws, input="go").wait()
inv = client.mapper.get_latest(workspace_id=ws, mapper_node_id=mapper.id)
print(inv.completed_count, "/", inv.expected_count)   # e.g. 100 / 100

Durable resume — recover an interrupted run without redoing work

A 100-sub-agent run that drops mid-flight (network error, a batch that errored) doesn't have to start over. Per-item state lives server-side, so resume re-dispatches only the unfinished items:

res = client.mapper.resume(inv.id, retry="incomplete")
#                                  ^ heuristic for which items re-run:
#   "incomplete" (default): everything not completed  — resume without loss
#   "errored":   only failures — retry, leave good work
#   "stalled":   only queued/running — a run that died mid-flight
print(res.resumed, res.pending)        # pending = items still not completed

Completed work is never redone; safe to call repeatedly.


Test agents — esoul.evals

Hermetically test an agent network before you publish: run it on graded inputs, grade with contains / regex / jsonSchema / llmJudge, and assert structural invariants over the event log. Same engine as the in-UI EVALS tab.

from esoul.evals import CastMember, run_eval, make_agent_judge

res = run_eval(
    client, workspace_id=ws,
    cast=[CastMember("pos", agent.node_id, "I love this!")],
    cases=[{"id": "p", "target": "pos", "expected": [{"graderId": "contains", "expected": "POSITIVE"}]}],
)
print(res.summary())   # PASS/FAIL + per-case ✓/✗

Use Haiku for tests; one case = one CastMember + one case spec. Agent output that ends on return_result_to_router is read from router_handoff (handled for you). To surface results in the in-UI EVALS tab, persist Eval/EvalRun/ EvalCaseResult rows keyed by agentRef.agentNodeId. Full how-to (graders, judge, invariants, persistence, the EVALS-tab hollow-circle meaning, ops): docs/esoul-llm-reference.md → "Testing harness". Worked example: tests/fairy_comprehensive.py + ../../scripts/eval-tests/persist-fairy-evals.ts.


Track PyTorch training — esoul.track

Use an ExternalSoul workspace as your TensorBoard: live loss curves, per-epoch sample images, hyperparameter comparison across runs, and an agent that can read the curves and tell you whether the run has plateaued.

pip install esoul
export ESOUL_TOKEN=esoul_pat_...          # Settings → Access Tokens
import esoul.track as track

run = track.init(
    workspace="ml",                        # by NAME — omit if your token is workspace-scoped
    monitor="Training",                    # the monitor app; created on first use
    config={"lr": 3e-4, "batch_size": 64, "arch": "resnet50"},
    total_steps=len(loader) * EPOCHS,      # drives the progress ring + ETA
)

for epoch in range(EPOCHS):
    for i, batch in enumerate(loader):
        loss = train_step(batch)
        run.log({"train/loss": loss, "lr": sched.get_last_lr()[0]}, step=global_step)

    run.log({"val/loss": val_loss, "val/acc": val_acc}, step=global_step, epoch=epoch)
    run.log_images("samples", model.sample(8), step=global_step, epoch=epoch)

run.finish()

That is the whole integration. loss may be a live CUDA tensor — it is detached on the spot and resolved later, off the training thread.

What it costs your training loop

log() is a queue push: ~1.5 µs, no formatting, no .item() (which would synchronise the GPU), no I/O. A background thread batches, writes a crash-recovery journal, and posts. Measured on a real run: 5,516 points in 2 HTTP requests, 1.3 µs per log() call.

The reason it batches so hard is architectural, not lazy: each workspace write is a transactional append, and app state is folded on every one. So the SDK sends one event per flush and the platform folds each metric into a bounded sketch — a fixed ~5 KB per metric whether the run logs 500 points or 5 million. A 50-run sweep at 20k steps × 6 metrics (6 million datapoints) lives in under 900 KB of workspace state, and the charts open instantly at any scale.

Crash, resume, and DDP

Situation What happens
Network drops mid-run Frames queue on disk (~/.esoul/runs/<id>/wal.jsonl), retry automatically. Training never blocks or fails.
Process is killed Unsent frames stay on disk. track.init(resume="<run id>") replays them and continues the same run.
Exception in your loop with track.init(...) as run: marks the run failed and records the traceback on the run card.
torchrun / DDP Rank 0 logs; other ranks get an inert handle, so no if rank == 0: guards are needed. Pass all_ranks=True to override.
Duplicate delivery Each frame carries a monotonic seq; the platform folds it exactly once.
run = track.init(monitor="Training", resume=os.environ.get("RESUME_RUN_ID"))
print(run.id)      # save this to resume after a preemption

Design the dashboard from Python

Omit this entirely and the monitor infers a layout from your metric names (losses together, accuracies together, LR on a log axis, a sample strip if you log images). When you want control, declare it:

from esoul.track import Dashboard, Line, Tiles, Images, Config, System

run = track.init(
    monitor="Training",
    dashboard=Dashboard(
        title="ImageNet sweep",
        hero=["train/loss", "val/acc"],          # the two big readouts up top
        panels=[
            Tiles(["train/loss", "val/acc", "lr", "grad_norm"]),
            Line("Loss", ["train/loss", "val/loss"], span=2, height=240),
            Line("Accuracy", ["train/acc", "val/acc"]),
            Line("Learning rate", ["lr"], y="log"),
            Images("samples", title="Samples per epoch"),
            System(),                             # throughput / ETA / GPU
            Config(),                             # the hyperparameter table
        ],
    ),
)

Line(...) accepts a glob: Line("All losses", ["*/loss"]). Panels re-render live as points arrive; the spec is stored with the app, so it survives reloads and applies to every run in that monitor.

The rest of the API

run.log({"train/loss": 0.42}, step=i, epoch=e)   # scalars (float / np / torch)
run.log_images("samples", imgs, step=i)          # PIL, numpy HWC/CHW, bytes or paths
run.system(loss_scale=65536, temperature_c=71)   # ONLY what the SDK can't know:
#   throughput, ETA and (when torch is already imported) GPU util + memory are
#   derived from the step count and the clock — no calls needed in your loop.
run.note("lr warmup was too short")              # sticks to the run, agents read it
run.finish()                                     # or finish(status="killed")
run.stats                                        # points emitted, frames sent, µs/log

Ask an agent about your run

The monitor is a real workspace app, so an agent in that workspace — or your own script — can read the curves and reason about them:

import json

tools = client.workspaces.apps.tools(app_id=app_id)          # discover per-app tools
verdicts = json.loads(
    client.workspaces.apps.call_tool(app_id=app_id, tool_name="analyze_run_Training")
)
# {"name": "resnet-baseline", "status": "finished",
#  "verdicts": [{"series": "val/loss", "verdict": "plateaued",
#                "best": 0.2726, "bestStep": 880, "changeFraction": -0.004}, ...]}

analyze_run compares the last quarter of the run against the quarter before it and returns improving / plateaued / worsening per metric, with the best value and the step it happened at. Other tools: list_runs, read_run, read_series (the actual curve), compare_runs (overlays them and reports the differences), add_run_note, set_dashboard.

So "wake me when val_loss plateaus" is a workspace trigger, not a cron job you have to write.

Files in your workspace

f = client.files.upload(name="checkpoint-best.pt", content=open(path, "rb").read())
data = client.files.download(f.blob_url)     # ranged; a plain GET is 100× slower

Streaming anything else — esoul.stream

track is a thin facade over esoul.stream.EventStream, which is generic: an in-process queue, a batching daemon thread, a write-ahead log, retries, and one event per flush. Any high-rate producer (robot telemetry, a crawler's progress, throughput counters) can use it directly with its own reducer.

Beyond agents: events + typed resources

ExternalSoul workspaces are event-sourced — every mutation is a typed event on a per-workspace timeline. The UI, agents, and your scripts all dispatch through the same reducers, so audit logging is automatic. Drop to the raw event layer or the typed resources whenever you need to:

client.describe()                               # what workspaces / apps / events exist
client.dispatch_event(app_id=…, event_name="spreadsheet_add_row", event_data={…})
Resource What it does
client.spreadsheet Create / seed / read spreadsheets — create, add_column, add_rows, set_cell, get_rows.
client.workspaces.apps App lifecycle — list, create (with initial_state), rename, delete.
client.agents Invoke agent_builder runs — invoke(...).wait().
client.mapper Sub-Agent Mapper introspection (list_invocations, get_latest) + resume (resume, resume_latest).
client.questions Human-in-the-loop — ask(...) against the workspace question queue.
client.drive Google Drive ops on the workspace's connected Drive.
client.revert Run-revert kernel (preview).
client.files Workspace files — upload, list, ranged download.
client.workspaces.overview / .find The named project → workspace hierarchy; resolve a workspace BY NAME instead of pasting a UUID.

Build apps in the Forge — esoul.forge and esoul-forge

The Forge is where an ExternalSoul app is built: a cloud workbench holding a clone of the platform on the app's branch, a live preview in the person's board, and a journal of everything the running app got wrong. esoul.forge drives it from Python as data — the same handler the board's own tools use, reached with the workspace owner's token.

from esoul import Esoul

wb = Esoul().forge(workspace="Sparkling Water").workbench("stream-lab", name="Stream Lab", icon="Activity")

r = wb.sync("./stream-lab")          # the files that changed since the last sync: ONE checkpoint, ONE health probe
if r.preview.down:
    print(r.preview.detail)          # the dev server's own error lines
for p in r.problems:                 # what the running app hit since your last call — fix these first
    print(p.id, p.source, p.where, p.message)

wb.preview()                         # start the dev server; waits for the first answer
d = wb.drive(
    [{"select": ["select[aria-label='Customer']", "143"]}, {"wait": 3000}, {"say": "section[aria-label='Playback']"}],
    viewer="visitor-a?grant=customer&customer=143",
)
assert d.ok, d.problems              # console errors, throws and failed app calls while it was used

wb.op("find-faults", {"customer": 204}, viewer="owner")   # straight at the running app
assert wb.check().ok                 # everything the pull request will run; `skipped` is not a pass

for issue in wb.issues(open_only=True):                   # the board's Issues rows (they outlive restarts)
    ...                                                   # fix it, then say what you did in one line:
    wb.resolve(issue.id, "bridge start now reads bridge.log for the reason")
Method What it does
forge.board(create=False) The workspace's Forge board; never created unless you ask.
forge.workbench(id, name=, icon=) Open the app's box (merges the platform's main; scaffolds the package once).
wb.status() Branch, preview URL, whether it runs, whether someone has the board open, whether a long action holds the box.
wb.sync(folder, prune=False) Changed files only (a hash manifest .esoul-sync.json); never .esoul/*; prune deletes only what a sync wrote.
wb.write / edit / read / delete / restore / files One file at a time, each answering with the preview's health and new problems.
wb.pull_generated(folder) The box's generated .esoul/db.d.ts and migration, after check.
wb.preview() · wb.look(viewer=, critique=) Start the dev server · screenshots (desktop/phone, light/dark), on-screen text, clipped content, confirmed critic findings.
wb.drive(steps, viewer=) Drive it on the platform's browser; ok only when the page said nothing wrong.
wb.op / route / kick The running app's own doors, as a persona.
wb.tool(name, args) · wb.state() One of the app's tools in the preview (near-miss names healed and named) · the preview's fold.
wb.test() · wb.check() The app's tests (seconds) · the full bar.
wb.journal() · wb.issues() · wb.resolve(id, note) · wb.watch_issues() The box's journal · the board's rows · a green row with your line · a stream of entries as they land.
wb.commit / ship · wb.close(force=False) Commit, pull request · stop the box.

The box is the person's live surface. drive with clicks and close answer board_in_use while a board polled the preview in the last 30 s — pass force=True only with their leave. A second long action (open, check, ship) on the same box answers busy. Every refusal is an APIError carrying the server's code and sentence; a failure the workbench answered for is a ForgeError.

The same loop from a shell:

export ESOUL_TOKEN=esoul_pat_…  ESOUL_WORKSPACE="Sparkling Water"  ESOUL_PLUGIN=stream-lab
esoul-forge open --name "Stream Lab" --icon Activity
esoul-forge sync ./stream-lab                      # exit 1 on problems or a preview DOWN
esoul-forge drive steps.json --viewer 'visitor-a?grant=customer&customer=143'   # exit 1 unless clean
esoul-forge check                                  # exit 1 unless every gate is green
esoul-forge issues --open
esoul-forge resolve p_3f2a9c1d "bridge start reads bridge.log for the reason"
esoul-forge watch

MCP server — drive ExternalSoul from Claude Desktop / Cursor / any MCP client

The whole SDK is also available as a Model Context Protocol server, so any MCP client can read app state, dispatch events, run and build agent networks, search, manage the human-in-the-loop queue, and scrub the timeline — using your PAT.

pip install "esoul[mcp]"
ESOUL_TOKEN=esoul_pat_… esoul-mcp                    # stdio (default)
ESOUL_TOKEN=… esoul-mcp --transport streamable-http --port 8765
ESOUL_TOKEN=… ESOUL_MCP_READONLY=1 esoul-mcp         # browse, don't touch

Add to your client (claude_desktop_config.json → mcpServers):

{
  "mcpServers": {
    "externalsoul": {
      "command": "esoul-mcp",
      "env": {
        "ESOUL_TOKEN": "esoul_pat_…",
        "ESOUL_WORKSPACE_ID": "6d735936-…"
      }
    }
  }
}

49 tools across every resource (21 in read-only mode). Set ESOUL_WORKSPACE_ID to omit workspace_id on most calls. Long-running work (agent runs, HIL questions) is fire-then-poll so calls stay short. Full reference: .cursor/rules/docs/esoul-mcp-server.md.

Authentication

esoul.Esoul() auto-detects credentials in this order:

  1. Explicit token= kwarg
  2. ESOUL_TOKEN environment variable
  3. /var/run/esoul/token (the 0600 token every E2B sandbox writes at boot — Esoul() inside a sandbox Just Works)
  4. ~/.config/esoul/credentials (TOML with a [default] section: token = "esoul_pat_...")

For off-platform use (laptop, CI), create a Personal Access Token in workspace settings → "Access Tokens", pick the workspaces it can mutate, then:

export ESOUL_TOKEN="esoul_pat_..."

Workspace isolation

A credential is scoped to specific workspaces. Cross-workspace dispatch is structurally impossible — a server invariant, not a check in your script.

Idempotency

Every write is automatically idempotent — the SDK generates a UUID per call and reuses it across retries; the server caches the response under (session, key) for 24h. Override with idempotency_key="…" for application-level retry control.

Async client

esoul.AsyncEsoul() mirrors the sync API exactly:

import asyncio, esoul

async def main():
    async with esoul.AsyncEsoul() as client:
        await client.mapper.resume_latest(workspace_id="ws_abc", mapper_node_id="…")

asyncio.run(main())

Typed errors

Failures surface as exception classes mapped from the server's error.code; esoul.EsoulError catches everything:

try:
    client.dispatch_event(...)
except esoul.WorkspaceAccessDenied as e:
    print(f"Token cannot reach workspace {e.details['workspaceId']}")
except esoul.RateLimitError as e:
    time.sleep(e.retry_after_seconds or 1)
except esoul.AuthError:
    print("Token expired or revoked")
except esoul.EsoulError as e:
    print(f"{e.code}: {e.message}")

Status

Beta. The agent-builder, mapper, spreadsheet, and low-level dispatch_event / read_state surfaces are stable and used in production automations. See CHANGELOG.md for release notes.

License

MIT.

Metadata

Release files for esoul 0.17.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for esoul 0.17.0
File Size Uploaded Provenance Actions
esoul-0.17.0.tar.gz 353.2 kB Without provenance Details for esoul-0.17.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for esoul 0.17.0
File Interpreter ABI Platform Actions
esoul-0.17.0-py3-none-any.whl Python 3 none any Details for esoul-0.17.0-py3-none-any.whl

Total release size: 734.6 kB

Release files / esoul-0.17.0.tar.gz

Download URL esoul-0.17.0.tar.gz
Size 353.2 kB
Tags Source
SHA-256 checksum
How to use checksums
6ae12f7df45dec353b1443791fb470aa88d6eb54a6629345363419984b06a614
BLAKE2b-256 checksum
How to use checksums
add31af3e0a4fefff472e77ca76ba6b6ae87a1a6ca2353bdeea0290ed198a523
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.2

Release files / esoul-0.17.0-py3-none-any.whl

Download URL esoul-0.17.0-py3-none-any.whl
Size 381.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c3d29808cad9538dc6a55d880e917448306a961eee8de7e5386ea01d1f1ee628
BLAKE2b-256 checksum
How to use checksums
968f5beea5c2fd5a2374daf46519fe157a1ab81ee0964486b2c1a14ec22226a6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.2

Security for esoul 0.17.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page