Python SDK
Use the duun Python package to start and follow runs, resolve asks, apply workflow versions and verify webhooks, with sync and asyncio clients.
On this page
The duun package is the official Python client for the Duun API. It has a synchronous client and an asyncio client with the same methods, typed models, automatic pagination, safe retries and webhook verification. It needs Python 3.10 or later.
Install
pip install duunWith uv or Poetry: uv add duun or poetry add duun.
Create a client
Create an API key in Settings → API keys & secrets → Duun API keys with the scopes your code needs, and keep it in the DUUN_API_KEY environment variable.
from duun import Duun
client = Duun() # reads DUUN_API_KEYPass options to override the defaults:
import os
from duun import Duun
client = Duun(
api_key=os.environ["DUUN_API_KEY"], # duun_sk_…
api_version="2026-11-01", # pins a dated revision via Duun-Version
max_retries=2,
timeout=60.0, # seconds
)| Option | Default | Description |
|---|---|---|
api_key | DUUN_API_KEY | API key (duun_sk_…). |
base_url | https://api.duun.ai/v1 | API base URL. Also read from DUUN_API_URL. |
api_version | None | Sends Duun-Version to pin a dated revision. |
max_retries | 2 | Retries for 429, 5xx and connection errors, with exponential backoff. |
timeout | 60.0 | Request timeout in seconds. |
http_client | built in | A custom httpx.Client (or httpx.AsyncClient for AsyncDuun), for proxies or tests. |
The client keeps a connection pool. Create one per process and reuse it, or use it as a context manager to close connections when you’re done: with Duun() as client: ….
Start a run
run = client.runs.create(
factory_id="fac_platform",
prompt="Add idempotency keys to refund webhooks",
issue_url="https://linear.app/acme/issue/PLT-482",
inputs={"priority": "urgent"},
)
print(run.id, run.status) # run_7f3aK2pQ queuedResponses are typed models with attribute access (run.cost.spent_usd). Call run.to_dict() for a plain dict or run.to_json() for a JSON string.
Retrieve and control runs by id:
run = client.runs.retrieve("run_7f3aK2pQ")
client.runs.pause("run_7f3aK2pQ") # after the current step
client.runs.resume("run_7f3aK2pQ")
client.runs.cancel("run_7f3aK2pQ") # worktree and thread are kept
client.runs.restart("run_7f3aK2pQ")List and paginate
List methods return a page you can iterate directly. Iteration fetches further pages as needed.
for run in client.runs.list(status="waiting", factory_id="fac_platform"):
print(f"{run.id} is waiting on: {run.ask.title if run.ask else '-'}")To work page by page:
page = client.runs.list(limit=50)
print(len(page.data), page.has_more)
while page.has_more:
page = page.next_page()
print(len(page.data))limit is 1–100 and defaults to 20. See Pagination, errors and limits.
Stream logs
With follow=True, runs.logs keeps the connection open and yields lines until the run finishes.
for line in client.runs.logs("run_7f3aK2pQ", follow=True):
print(f"{line.at} {line.step:<10} {line.text}")Pass step="implement" for one step, or since= a datetime to skip older lines.
Resolve asks
When a run is waiting, run.ask.kind tells you which actions apply: approve or request_changes for approve_plan; allow_once or request_changes for allow_command; answer with answers for answer; merge or request_changes for review_pr; approve_once with amount_usd, or stop, for budget.
run = client.runs.retrieve("run_7f3aK2pQ")
if run.ask and run.ask.kind == "budget":
client.runs.asks.resolve(
run.id,
run.ask.id,
action="approve_once",
amount_usd=2.50,
note="Finish the contract tests, then stop.",
)The resolution appears in the run’s conversation and fires an ask.resolved webhook. Approvals still follow your workspace’s Action approvals settings.
Apply a workflow version
Send the full config and the revision you based it on. If someone applied a newer version first, the API answers 409 and the client raises duun.ConflictError. Invalid configs raise duun.ValidationError with the list of problems.
import copy
import duun
from duun import Duun
client = Duun()
workflow = client.workflows.retrieve("wf_base9c1d")
config = copy.deepcopy(workflow.config.to_dict())
config["limits"]["budget_usd"] = 10
result = client.workflows.diff(workflow.id, config=config)
errors = [p for p in result.problems if p.severity == "error"]
if errors:
raise SystemExit(errors[0].message)
try:
version = client.workflows.versions.create(
workflow.id,
config=config,
expected_revision=workflow.live_revision,
label="Raise budget to $10",
)
print(f"Applied v{version.revision}")
except duun.ConflictError as err:
# Someone applied a newer version: fetch it, re-apply your change, try again.
print(err.message)
except duun.ValidationError as err:
for p in err.problems:
print(f"{p.step_id or 'workflow'}: {p.message}")Roll back with client.workflows.restore(workflow.id, revision=3, expected_revision=...) and test with client.workflows.test(workflow.id, mode="dry"). See Versions and rollback.
Async client
AsyncDuun has the same methods as coroutines, and lists and log streams are async iterators.
import asyncio
from duun import AsyncDuun
async def main() -> None:
async with AsyncDuun() as client:
run = await client.runs.create(factory_id="fac_platform", prompt="Fix the flaky settlement test")
async for line in client.runs.logs(run.id, follow=True):
print(line.text)
async for waiting in client.runs.list(status="waiting"):
print(waiting.id, waiting.ask.title if waiting.ask else "")
asyncio.run(main())Verify webhooks
client.webhooks.construct_event checks the X-Duun-Signature header against the raw body and your endpoint’s signing secret, enforces the 300-second tolerance, and returns the parsed event. It raises duun.WebhookSignatureError when the check fails. It doesn’t call the API, so it works the same on Duun and AsyncDuun.
import os
import duun
from duun import Duun
from fastapi import FastAPI, HTTPException, Request
app = FastAPI()
client = Duun()
SECRET = os.environ["DUUN_WEBHOOK_SECRET"] # whsec_…
@app.post("/webhooks/duun")
async def duun_webhook(request: Request) -> dict:
raw_body = await request.body() # raw bytes, not request.json()
try:
event = client.webhooks.construct_event(
raw_body,
request.headers.get("x-duun-signature", ""),
SECRET,
)
except duun.WebhookSignatureError:
raise HTTPException(status_code=400, detail="Invalid signature")
if event.type == "run.failed":
run = event.data.object
print(f"{run.id} failed at {run.current_step}")
elif event.type == "budget.threshold":
alert = event.data.object
print(f"Budget {alert.budget_id} at {alert.pct}%")
return {"ok": True}Deduplicate on event.id and do slow work in a background task, so you answer within 10 seconds. See Verifying signatures for the scheme.
Errors
API errors raise subclasses of duun.APIError with the fields of the error object: status_code, type, code, message, param and request_id.
| Exception | Status | When |
|---|---|---|
duun.BadRequestError | 400 | invalid_request |
duun.AuthenticationError | 401 | Missing, invalid or revoked key |
duun.PermissionDeniedError | 403 | The key lacks a scope, or the action isn’t allowed |
duun.NotFoundError | 404 | The id doesn’t exist in this workspace |
duun.ConflictError | 409 | conflict or idempotency_error |
duun.ValidationError | 422 | Has .problems for workflow configs |
duun.RateLimitError | 429 | Has .retry_after in seconds |
duun.InternalServerError | 5xx | api_error, service_unavailable |
duun.APIConnectionError | none | Network failure or timeout |
import duun
try:
client.runs.retrieve("run_doesnotexist")
except duun.NotFoundError as err:
print(err.message, err.request_id)
except duun.APIError as err:
print(err.status_code, err.type, err.code)Include request_id (req_…) when you contact support.
Retries and idempotency
The client retries 429, 5xx and connection errors up to max_retries times with exponential backoff and honours Retry-After. Every POST carries an Idempotency-Key, and retries reuse it, so a retried runs.create never starts two runs.
Pass your own key when the same work might be requested twice, for example from a job queue that can redeliver:
client.runs.create(
factory_id="fac_platform",
issue_url="https://linear.app/acme/issue/PLT-482",
idempotency_key="linear-PLT-482-ready",
)Override retries and timeouts for one call with client.with_options(max_retries=5, timeout=20.0).runs.create(...). Keys are remembered for 24 hours; reusing one with a different body raises duun.ConflictError with type idempotency_error.
Other resources
The client mirrors the API reference one to one:
client.factories—list,create,retrieve,update,pause,resume,archive. Factories APIclient.workflows—list,create,retrieve,diff,versions.create,versions.list,versions.retrieve,restore,test,pause,resume. Workflows APIclient.agents,client.skills(withpublish),client.commands. Agents, Skills, Commandsclient.webhook_endpoints(withrotate_secret,test,deliveries.list,deliveries.redeliver) andclient.trigger_urls. Webhook endpoints APIclient.usage.retrieve,client.usage.credits(),client.budgets.list(). Usage and budgets