Skip to content

Python SDK (AbtRunner)

abt exposes a programmatic entry point similar to dbt’s dbtRunner: you can invoke the same operations as the CLI from Python and inspect structured results.

Import

from abt import AbtRunner, AbtRunnerResult

AbtRunnerResult

Each invocation returns an AbtRunnerResult:

Field Meaning
success True if the command finished without an unhandled exception and (for run/test) command-specific success rules passed.
result Command output; type depends on the subcommand (see below).
exception Set when argument parsing fails (for example a ValueError for an unsupported flag combination) or an error escaped the command handler. invoke() does not raise these: check success and exception. The one exception is the running-event-loop RuntimeError described under Sync vs async.
plan Typed DryRunPlan populated on --dry-run; None otherwise.

Subcommands and result types

Command result when success
compile WritableManifest
list list[str] of agent names, dict[str, list[str]] if by_tags=True, or AgentWiringView when filter_agent is set (one agent's own compiled wiring — the CLI flag is --agent).
run RunResult, or a JSON-serializable dict when dry_run=True / --dry-run (plan preview only).
test list[TestCaseResult], or a dict when dry-run.
doctor DoctorReport (CLI renders it).
dispatch RunResult from the dispatched workflow's terminal node (single-node steps:, or the last node reached on a branch, for a multi-node workflow) — exposures run unless skipped.

For run, RunResult may include structured: the dict from model_dump() after a successful Pydantic contract check when the agent set output_schema (Agents — Structured output). Otherwise it is None.

For dispatch, the workflow executor runs every node in the workflow's workflows/ topology and rolls the whole run up into one RunResult: the terminal node's own result is the head, and every other executed node becomes a dep_results entry (each may itself nest dep_results) — this is what produces the single chain-total footnote and token rollup. For run, there is no workflow and no dependency chain — dep_results is empty; delegation via subagents: happens through LLM tool calls at runtime, not a pre-run dependency resolution, so it doesn't populate dep_results, and dag_summary.json has one row for a run. agent_name is set by the orchestrator for each node. elapsed_seconds records that node's wall time (not summed across parallel waves). Read-only properties total_input_tokens and total_output_tokens aggregate this node plus all nested dep_results. The stream footnote ends with a single Tokens used: … in · … out line for the full chain when upstream nodes contributed usage (the redundant head-only line from streaming is omitted). The same totals appear under target/run_results/run_results.json and in dag_summary.json (including elapsed_s per row; see Configuration — Workspace path).

Basic examples

from abt import AbtRunner

runner = AbtRunner(project_root="/path/to/project")

# Compile (writes manifest.json like `abt compile`)
res = runner.invoke(["compile"])
assert res.success
manifest = res.result

# List agents (`abt list`)
res = runner.invoke(["list"])
assert "my_agent" in res.result

# Run an agent — the name goes after -s, same as the CLI
res = runner.invoke(["run", "-s", "my_agent", "-p", "Hello"])  # sync
res = runner.invoke(["dispatch", "-s", "my_workflow"])

# In async code, use `await runner.ainvoke([...])` instead of `invoke`.

run/dispatch argv: -s is required

AbtRunner.invoke()'s argv parser mirrors the CLI for run/dispatch: the name goes after -s/--select, and it is required. There is no positional form.

runner.invoke(["run", "-s", "my_agent", "-p", "Hello"])
runner.invoke(["dispatch", "-s", "my_workflow"])

# WRONG — no -s:
res = runner.invoke(["dispatch"])
res.success     # False
res.exception   # ValueError: dispatch requires -s/--select (same as the abt CLI's `abt dispatch -s NAME`).

A bare name on run runs that agent plus its full subagents: tree, unbounded, and never a workflow neighbor.

Passing an agent name to dispatch is a project-shape error at run time, not a parser error — see CLI reference.

For the CLI's exact list-then-print-entrypoints behavior, prefer abt.sdk.run(agent, prompt, ...) / abt.sdk.dispatch(workflow, ...) (already-positional Python function signatures, a separate surface from AbtRunner.invoke()) or shell out to the abt CLI directly.

CLI-style args and kwargs

Args mirror the CLI (first token is the subcommand), including the -s agent/workflow name on run/dispatch. Kwargs override parsed flags (same idea as dbt’s invoke([...], select=..., fail_fast=True)). Any other keyword gives a failed result with a ValueError (typos are not ignored).

runner.invoke(["run", "-s", "my_agent"], prompt="Do the thing")
runner.invoke(["compile"], vars={"ticket_id": "DATA-123"})  # template vars dict

Boolean and path options map to kwargs: project_root, workspace, target, profiles_dir, fail_fast, no_manifest, final_response, debug, show_llm_output, by_tags, context_file, vars, vars_raw, deep (for doctor only), filter_tag (for doctor only), filter_agent (for list only — one agent name, spelled --agent on the CLI: that agent's own resource wiring), only_agent (for test only — --only-agent isolates that one agent's own suite, no subagents: wired; mutually exclusive with -s/--select), test_name (for test only — -n/--name), dry_run (for run and test), stateless, artifact_dir, checkpoint_backend, checkpoint_ephemeral, auto_approve_tools (run only — same as CLI -y/--yes: auto-approves every in-shell tool-call confirmation for the run), mock_sources (dispatch only — dict of source name → mock payload, same as CLI --mock-sources).

When stateless=True, the runner always uses an auto-created temp workspace; any workspace argument is ignored (same as CLI --stateless overriding --workspace). Supported for run, dispatch, and compile; artifact_dir applies only to run/dispatch. See Stateless runs.

When dry_run is true, bootstrap compiles with external context stubbed (same as ABT_MOCK_EXTERNAL_CONTEXT=1 for that compile only), and source payloads used by prompts are placeholders where applicable, so previews do not need cloud credentials, Slack tokens, or similar.

Unsupported flag/command combinations return a failed result whose exception is a ValueError (matching CLI intent), for example invoke(["run", "--tags"]) or invoke(["compile", "--fail-fast"]) or invoke(["compile", "--dry-run"]).

Constructor defaults

AbtRunner(
    project_root=".",
    manifest=None,           # optional cached WritableManifest
    callbacks=None,          # list[Callable[[str, Any], None]]
    target=None,
    profiles_dir=None,
    vars=None,               # default template vars dict (merged with CLI --vars)
    profile=None,            # inline profile dict (see sdk-inline-profiles)
    load_dot_env=False,      # load a .env file from the project root
    configure_logging=True,  # False leaves the root logger alone
)

Callbacks receive (phase, data) strings such as before:compile / after:compile, before:run / after:run, before:dispatch / after:dispatch, before:doctor / after:doctor, etc.

Reusing a compiled manifest

Pass manifest= to skip a full recompile on subsequent calls when the project on disk has not changed:

c = runner.invoke(["compile"])
cached = c.result
runner2 = AbtRunner(project_root="...", manifest=cached)
runner2.invoke(["run", "-s", "my_agent", "-p", "hi"])

Sync vs async

  • invoke() — synchronous; uses asyncio.run internally. Cannot be used if an event loop is already running; it raises RuntimeError (rather than returning a failed result) with a hint to use await ainvoke().
  • ainvoke() — async; safe under pytest-asyncio or other async hosts.

Heavy sync work (compile, bootstrap, list) runs in a worker thread when ainvoke() is used so MCP/tool discovery that expects “no running loop” stays compatible with async test runners.

Parallel execution

Like dbt-core, do not rely on multiple concurrent AbtRunner invocations in the same process for production automation. Prefer separate processes if you need parallelism.

CLI parity

For run, Python kwargs mirror -p/--prompt as prompt=.

CLI invoke example
abt compile invoke(["compile"])
abt list invoke(["list"])
abt list -s tag:x invoke(["list", "-s", "tag:x"]) — same shared -s as other commands, but list's -s only accepts a bare agent name or tag:<name> (see Selectors)
abt list --agent my_agent invoke(["list", "--agent", "my_agent"]) or filter_agent="my_agent" — one agent's own resource wiring
abt dispatch -s my_workflow invoke(["dispatch", "-s", "my_workflow"]) — see run/dispatch argv; optional -p overrides the first composed prompt for that run
abt run -s X -p Y invoke(["run", "-s", "X", "-p", "Y"]) — see run/dispatch argv
abt test invoke(["test"])
abt test -s X invoke(["test", "-s", "X"])
abt test --only-agent X invoke(["test", "--only-agent", "X"]) or only_agent="X" — isolates that one agent's own suite, no subagents: wired; mutually exclusive with -s/--select
abt doctor invoke(["doctor"]) — success is true when the report completes (warnings do not set success to false).
abt doctor --deep invoke(["doctor", "--deep"]) or invoke(["doctor"], deep=True)
abt doctor --fail-on warning CLI only. In Python, read result.result.findings and apply your own threshold.
abt doctor --tag X invoke(["doctor", "--tag", "X"]) or filter_tag="X"
abt doctor -s Y invoke(["doctor", "-s", "Y"]) — agent Y plus its full subagents: closure, unbounded
abt discover QUERY Use the abt CLI; AbtRunner does not parse this subcommand yet. In Python: await abt.sdk.discover(query, project_root, top_k=…) (returns DiscoverMatch rows with kind always "agents" — discover ranks agents only).
abt run --auto CLI only for confirmation UX; in Python use await abt.sdk.route(query, project_root, …) → RoutingDecision, then invoke abt.sdk.dispatch / abt.sdk.run as appropriate.

Shared implementation

AbtRunner.invoke() and the abt CLI run the same code paths, so results and errors match on both surfaces. A tag selector such as invoke(["list", "-s", "tag:infra"]) filters the names of a full compile (abt list -s tag:infra). With filter_agent= (abt list --agent), list returns an AgentWiringView (stem, name, agent, retrievers, downstream_consumers; sources, prompts and exposures are workflow nodes and are not part of it). Combining by_tags=True with filter_agent= raises, because --tags is incompatible with --agent.