Use the API from Python
Call the API from Python with the standard library only: a small client, a first run, safe retries and paging through receipts.
This guide repeats the Quickstart in Python, then adds what a script needs next: retries that do not blindly repeat a paid model call, and paging. The code runs on Python 3.9 or later and uses only the standard library, so there is no third-party package to install.
Before you start
- A key with the
runscope in the environment variableCOA_API_KEY.runincludesread. A workspace admin creates keys in the web workspace; see Authentication. - An activated agent and a workspace model key. The Quickstart explains both.
export COA_API_KEY="ak_..."A small client
Save this as coa.py. call sends one request with the key as a bearer token and returns the parsed JSON body. A 4xx or 5xx response raises ApiError, which carries the HTTP status, the error code, the parsed body and the response headers.
"""A minimal API client. Python 3.9 or later, standard library only."""
import http.client
import json
import os
import urllib.error
import urllib.parse
import urllib.request
BASE_URL = "https://centerofagentic.com/api"
API_KEY = os.environ["COA_API_KEY"] # raises KeyError when the variable is not set
class ApiError(Exception):
"""A 4xx or 5xx response."""
def __init__(self, status, code, body, headers):
super().__init__(f"HTTP {status} {code}")
self.status = status # the HTTP status, for example 429
self.code = code # the "error" value, for example "rate_limited"
self.body = body # the parsed JSON body
self.headers = headers # the response headers, for example Retry-After
def call(method, path, body=None, query=None, headers=None, timeout=30):
"""Send one request and return the parsed JSON response."""
url = BASE_URL + path
if query:
url += "?" + urllib.parse.urlencode(query)
request = urllib.request.Request(url, method=method)
request.add_header("Authorization", "Bearer " + API_KEY)
for name, value in (headers or {}).items():
request.add_header(name, value)
if body is not None:
request.data = json.dumps(body).encode("utf-8")
request.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return json.loads(response.read())
except urllib.error.HTTPError as error:
raw = error.read().decode("utf-8", "replace")
try:
parsed = json.loads(raw)
except ValueError:
parsed = {"raw": raw}
code = parsed.get("error") if isinstance(parsed, dict) else None
raise ApiError(error.code, code, parsed, error.headers) from None
except http.client.HTTPException as error: # the response was cut off or malformed
raise ConnectionError(f"Incomplete response: {error!r}") from Nonetimeout is in seconds. A synchronous run can take up to 60 seconds, so the examples below pass 90 for that call. A connection failure, a timeout or a response that is cut off raises an OSError from the standard library, such as urllib.error.URLError, not ApiError.
From key to receipt
first_run.py makes the calls of the Quickstart in order: verify the key, list agents and pick an activated one, request a launch ticket, run the agent, read the verdict and fetch the stored receipt. Save it in the same folder as coa.py and run it with python3 first_run.py.
import time
import uuid
from coa import call
PROTOCOL = {"X-CoA-Agent-Protocol": "agent-active-grants/1"}
# 1. Verify the key. Any valid key can call /me.
me = call("GET", "/me")
print("Key", me["userId"], "in workspace", me["tenant"]["slug"])
# 2. List agents and pick an activated one.
agents = call("GET", "/agents")["agents"]
agent = next((a for a in agents if a.get("activeGrant", {}).get("state") == "available"), None)
if agent is None:
raise SystemExit("No activated agent in this workspace")
print("Running", agent["name"], agent["id"])
# 3. Request a launch ticket for exactly the body the run will send.
run_body = {
"agentId": agent["id"],
"prompt": "List three renewal risks for a mid-market software customer.",
}
ticket = call("POST", "/agent-runtime/ticket", headers=PROTOCOL, body={
"agentId": agent["id"],
"purpose": "run",
"nonce": str(uuid.uuid4()),
"request": run_body,
})
# 4. Run the agent: the same body, the ticket and a request identity.
result = call("POST", "/run", body=run_body, timeout=90, headers={
**PROTOCOL,
"X-CoA-Agent-Ticket": ticket["ticketId"],
"X-CoA-Model-Request": f"{int(time.time() * 1000)}.{uuid.uuid4()}",
})
# 5. Read the verdict. A refusal is also HTTP 200.
print(result["decision"], result["reasonCode"])
if result["decision"] == "allow":
print(result["output"])
# 6. Fetch the stored receipt, which is the record to keep.
receipt = call("GET", "/receipts/" + result["receipt"]["id"])
print("Receipt", receipt["id"], receipt["assuranceTier"], receipt["evidenceClass"])Key api-key:5d0e7c2a-41b8-4c6f-9f0a-2b7e6d1c3a90 in workspace example-workspace
Running Renewal brief writer 3f1c2a9e-0b7d-4e55-9a51-6f2f1c0e8d11
allow ALLOWED
1. Budget pressure at renewal time. 2. Low adoption of paid features. 3. A change of executive sponsor.
Receipt e7b1c9a4-3d52-4f8e-a6c0-1f9d2b7e5a38 2 enforcementtenantin theGET /api/meresponse is your workspace, anduserIdidentifies the key.- An activated agent reports
activeGrant.stateasavailable. An agent that is not under managed activation has noactiveGrantfield. - The script runs the first activated agent in the list. If the workspace has several, select yours by
idinstead: an agent with connections can call the systems it is connected to. - The run sends exactly the JSON object the ticket was requested for. Key order does not matter; any other difference is refused with
409 agent_admission_unavailable. X-CoA-Agent-Protocolgoes on both calls.X-CoA-Agent-TicketandX-CoA-Model-Requestgo on the run.X-CoA-Model-Requestis the Unix time in milliseconds, a dot and a UUID, and identifies the request for usage accounting.- A ticket is valid for ten minutes and starts one run. Its
nonceis a new UUID. - The receipt inside the run response is written before
assuranceTierandevidenceClassare set, so step 6 fetches the stored one. - When a step fails, the
ApiErrorshows the status and the code. If a call is refused lists the causes.
Refusals and errors
ApiError means an HTTP error status. A governed refusal is not one: a run refused by policy or by a monthly spend cap answers 200 with decision set to deny, so read decision on every result. Some budget refusals are HTTP errors instead, as the table shows.
| What the code sees | Meaning | What to do |
|---|---|---|
A result with decision set to deny | A governed refusal. reasonCode says why, for example SPEND_OVER_BUDGET, and a receipt records it. | Record reasonCode. Do not loop: a refusal is an answer, not a transport error. |
A result with replayed set to true | The ticket was already used. No new run started, and the result has no decision. | Do not run again. Find the first attempt's receipt; see After a replayed response. |
ApiError with status 429 and code rate_limited | The run limit was reached before any model call. The Retry-After header gives the wait in seconds. | Wait, request a new launch ticket and send the run again. |
ApiError with status 429 and code agent_launch_limit | The key requested 120 launch tickets within the past hour, or the agent or the workspace has reached its limit of stored launch tickets or runs. The response has no Retry-After. | Back off for minutes, not seconds. If the code is still returned an hour after the key last received a ticket, a storage limit is reached and waiting does not clear it: tell your workspace admin. |
ApiError whose body has invoked set to false, such as spend_reservation_refused | A budget or accounting refusal with status 402, 409 or 503. The refused model call was not sent to the model provider. | Do not retry automatically. Change the budget or wait, then run again deliberately. |
ApiError with any other 5xx, or an OSError | The outcome may be unknown. 500 model_call_failed can occur after the model provider was called. | Do not send the run again blindly. Look for its receipt first. |
ApiError with 401, 403 or another 4xx | A credential, scope, request or agent-state problem. Nothing ran. | Fix the cause. Never retry. |
Errors lists the shared codes and Runs the ones that belong to a run.
Retry only what is safe
These helpers apply the rules from Automation and CI. Save them as coa_retry.py in the same folder.
import random
import time
import uuid
from coa import ApiError, call
PROTOCOL = {"X-CoA-Agent-Protocol": "agent-active-grants/1"}
def retry_after(error, fallback):
"""Seconds to wait: the Retry-After header when it is a number, else the fallback."""
try:
return float(error.headers.get("Retry-After"))
except (TypeError, ValueError): # no header, or a date instead of seconds
return fallback
def get(path, query=None, attempts=5):
"""GET with a bounded retry. Reads are safe to repeat."""
for attempt in range(attempts):
last = attempt == attempts - 1
try:
return call("GET", path, query=query)
except ApiError as error:
if last or (error.status != 429 and error.status < 500):
raise
delay = retry_after(error, 2 ** attempt)
except OSError: # no connection, a timeout or an incomplete response
if last:
raise
delay = 2 ** attempt
time.sleep(delay + random.random())
def run_agent(agent_id, prompt, attempts=3):
"""Run an activated agent once. Only 429 rate_limited is sent again."""
body = {"agentId": agent_id, "prompt": prompt}
identity = f"{int(time.time() * 1000)}.{uuid.uuid4()}" # one per intended run
for attempt in range(attempts):
# A launch ticket starts one run, so every attempt needs a new one.
ticket = call("POST", "/agent-runtime/ticket", headers=PROTOCOL, body={
"agentId": agent_id,
"purpose": "run",
"nonce": str(uuid.uuid4()),
"request": body,
})
try:
result = call("POST", "/run", body=body, timeout=90, headers={
**PROTOCOL,
"X-CoA-Agent-Ticket": ticket["ticketId"],
"X-CoA-Model-Request": identity,
})
except ApiError as error:
if error.code != "rate_limited" or attempt == attempts - 1:
raise # anything else: find out what happened before running again
time.sleep(retry_after(error, 5) + random.random())
continue
if result.get("replayed"):
raise RuntimeError("Ticket already used; no new run was started")
return result # decision is "allow" or "deny"; both carry a receiptgetrepeats a read on429, on5xxand on anOSError, with at most five attempts.run_agentsends a run again only after429 rate_limited, when the model was not called, and makes at most three attempts. Each attempt requests a new ticket, because the refused request has already used its own.- The
X-CoA-Model-Requestvalue is generated once for the intended run and sent again unchanged. - A denied run is returned like an allowed one. Every other error reaches the caller: catch
ApiErrorandOSErrorthere, and before you run again look for the receipt withGET /api/receipts?agentId=…&user=….GET /api/mereturns theuservalue asuserId.
Page through receipts
GET /api/receipts returns receipts, total and hasMore, newest first. Paging uses a cursor, not an offset: pass the last receipt's createdAt as createdBefore and its id as beforeId, keep the filters identical, and stop when hasMore is false. limit is at most 200.
import json
from coa_retry import get
def export_receipts(**filters):
"""Return every receipt that matches the filters, newest first."""
query = {"limit": 200, **filters}
receipts = []
while True:
page = get("/receipts", query)
receipts.extend(page["receipts"])
if not page["hasMore"]:
break
last = page["receipts"][-1]
query["createdBefore"] = last["createdAt"]
query["beforeId"] = last["id"]
if len(receipts) < page["total"]:
print("Got", len(receipts), "of", page["total"], "receipts; run the export again")
return receipts
with open("receipts.ndjson", "w", encoding="utf-8") as out:
for receipt in export_receipts(decision="deny"):
out.write(json.dumps(receipt) + "\n")The script writes every denied run to receipts.ndjson; a read-scope key is enough. total counts every match for the filters, and a receipt written in the same millisecond as the last one on a page can be missed, so the script compares the two numbers. Receipts contain prompts and outputs: store the file accordingly. Export evidence for review lists the filters.
Streamed runs
call reads one complete JSON body, so it does not fit POST /api/run/stream, which answers with server-sent events. Run examples covers reading a streamed run.
Next steps
Something missing or unclear? Tell us and we will improve this page.