AgentDBDocs

AgentDB with Python

Use AgentDB as the database of your Python app. This page shows every call you need, with urllib from the standard library. No packages. With requests or httpx, the calls look the same: one function, the same headers.

You can copy each block into your own code. Together they form one program that our tests run.

This page is tested: its code runs locally and in CI against a fresh AgentDB on every change.

Server-side only. This code runs on your server. In Django, Flask or FastAPI, read the key from the environment at startup and call AgentDB from a view or a service module.

#Before you start

  • Python 3.9 or newer.
  • A workspace with the example schema: contact, company and works_at.
  • Three environment variables on your server: AGENTDB_URL, AGENTDB_API_KEY and AGENTDB_WORKSPACE. See Environment variables.

#Connect

Read the settings from the environment. The key never appears in the code.

Pythonexamples/languages/python/crm.py
BASE_URL = os.environ.get("AGENTDB_URL", "https://app.agentdb.link").rstrip("/")
API_KEY = os.environ.get("AGENTDB_API_KEY")  # a server-side secret: never in browser code
WORKSPACE = os.environ.get("AGENTDB_WORKSPACE")  # ws_...
if not API_KEY or not WORKSPACE:
    sys.exit("Set AGENTDB_API_KEY and AGENTDB_WORKSPACE")
API = f"{BASE_URL}/v1/workspaces/{WORKSPACE}"

Every call goes through one small helper. It sends the key in the Authorization: Bearer header, turns AgentDB errors into one error type, and retries when that is safe.

Pythonexamples/languages/python/crm.py
class AgentDBError(Exception):
    """An AgentDB error: HTTP status plus the error envelope {code, message, retryable, details}."""

    def __init__(self, status, error):
        error = error or {}
        super().__init__(f"{status} {error.get('code', 'HTTP_ERROR')}: {error.get('message', '')}")
        self.status = status
        self.code = error.get("code", "HTTP_ERROR")
        self.retryable = error.get("retryable") is True
        self.details = error.get("details") or {}


def api(method, path, json_body=None, body=None, idempotency_key=None, raw=False):
    """One API call. Sends the key in the Authorization header. Retries 429 and 503 with
    Retry-After (or exponential backoff), and network errors when the call is safe to repeat
    (GET, or a write with an Idempotency-Key). Returns the "data" part, or the raw bytes."""
    headers = {"Authorization": f"Bearer {API_KEY}"}
    data = None
    if json_body is not None:
        headers["Content-Type"] = "application/json"
        data = json.dumps(json_body).encode()
    if body is not None:
        headers["Content-Type"] = "application/octet-stream"
        data = body
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    safe_to_repeat = method == "GET" or bool(idempotency_key)
    attempt = 0
    while True:
        request = urllib.request.Request(API + path, data=data, method=method, headers=headers)
        try:
            with urllib.request.urlopen(request, timeout=60) as res:
                content = res.read()
                return content if raw else json.loads(content)["data"]
        except urllib.error.HTTPError as err:
            if err.code in (429, 503) and attempt < 4:
                retry_after = err.headers.get("Retry-After")
                time.sleep(float(retry_after) if retry_after else 0.5 * 2**attempt + random.random() / 4)
                attempt += 1
                continue
            try:
                envelope = json.loads(err.read())
            except ValueError:
                envelope = {}
            raise AgentDBError(err.code, envelope.get("error")) from None
        except urllib.error.URLError:
            if safe_to_repeat and attempt < 4:
                time.sleep(0.5 * 2**attempt)
                attempt += 1
                continue
            raise

Check the connection by reading the schema:

Pythonexamples/languages/python/crm.py
schema = api("GET", "/object-types")
print("Objects:", ", ".join(o["name"] for o in schema["objects"]))

#Create a record

Send the object name and the field values. AgentDB checks each value against its field type. The answer holds the new record with its id and version 1.

Pythonexamples/languages/python/crm.py
ada = api(
    "POST",
    "/records",
    json_body={"object": "contact", "data": {"name": "Ada Lovelace", "email": f"ada-{run}@example.com", "score": 72}},
    idempotency_key=str(uuid.uuid4()),  # safe to retry: the same key never writes twice
)
print("Created", ada["id"], "version", ada["version"])

The Idempotency-Key header makes a retry safe. See Idempotency keys.

#Read a record

Pythonexamples/languages/python/crm.py
record = api("GET", f"/records/{ada['id']}")
print(record["data"]["name"], record["data"]["email"], "version", record["version"])

#Update a record

An update names the version you read. If someone changed the record since then, AgentDB refuses with VERSION_CONFLICT (HTTP 409) and writes nothing. Read it again, apply your change, and try again:

Pythonexamples/languages/python/crm.py
def update_record(record_id, change, attempts=3):
    """Read, change, write with the current version. On VERSION_CONFLICT: read again and retry."""
    for i in range(1, attempts + 1):
        current = api("GET", f"/records/{record_id}")
        try:
            return api("PATCH", f"/records/{record_id}", json_body={"version": current["version"], "data": change(current["data"])})
        except AgentDBError as err:
            if err.code == "VERSION_CONFLICT" and i < attempts:
                continue
            raise


updated = update_record(ada["id"], lambda data: {"score": data["score"] + 10})
print("Score", updated["data"]["score"], "version", updated["version"])

This is what the conflict looks like:

Pythonexamples/languages/python/crm.py
try:
    api("PATCH", f"/records/{ada['id']}", json_body={"version": 1, "data": {"score": 0}})  # stale version
except AgentDBError as err:
    if err.code != "VERSION_CONFLICT":
        raise
    print("Conflict: the record is now at version", err.details.get("current_version"))

#Query with filters, sort and pages

A query takes an object, a where filter, a sort and a limit (at most 200). Every condition in all must match. Use the in operator for "one of several values". Operators: eq, neq, in, lt, lte, gt, gte, is_null, is_not_null.

When more records match, the answer holds a next_cursor. Send it as cursor with the same query to get the next page. A next_cursor of null means you have them all.

Pythonexamples/languages/python/crm.py
def query_all(object_name, where, sort, page_size=2):
    """Every record that matches, page by page (limit up to 200; follow next_cursor)."""
    out, cursor = [], None
    while True:
        body = {"object": object_name, "where": where, "sort": sort, "limit": page_size}
        if cursor:
            body["cursor"] = cursor
        page = api("POST", "/query", json_body=body)
        out.extend(page["records"])
        cursor = page["next_cursor"]  # None on the last page
        if not cursor:
            return out


good = query_all(
    "contact",
    {"all": [{"field": "score", "op": "gte", "value": 70}, {"field": "email", "op": "neq", "value": "nobody@example.com"}]},
    [{"field": "score", "order": "desc"}],
)
for c in good:
    print(c["data"]["score"], c["data"]["name"])

See Querying for text search, totals and saved views.

#Link records

A relationship type such as works_at links a contact to a company. Create a link, then list the records on the other side:

Pythonexamples/languages/python/crm.py
company = api("POST", "/records", json_body={"object": "company", "data": {"name": f"Example Ltd {run}"}})
api(
    "POST",
    "/links",
    json_body={"relationship": "works_at", "source_record_id": ada["id"], "target_record_id": company["id"]},
    idempotency_key=f"link-{ada['id']}-{company['id']}",
)
related = api("GET", f"/records/{ada['id']}/related?relationship=works_at")
print("Ada works at", ", ".join(r["data"]["name"] for r in related["records"]))

Add direction=incoming to list from the other side, for example all contacts of a company.

#Files

A file upload has three steps: announce the file with its name, type and size; send the raw bytes; attach it to a record. AgentDB checks that the bytes match the type.

Pythonexamples/languages/python/crm.py
content = f"Meeting notes for Ada ({run})\n".encode()
# 1. Announce the file, 2. send the raw bytes, 3. attach it to a record.
file = api("POST", "/files", json_body={"filename": "notes.txt", "content_type": "text/plain", "size": len(content)})
api("PUT", f"/files/{file['id']}/content", body=content)
api("POST", "/attachments", json_body={"file_id": file["id"], "record_id": ada["id"]})
# Download with the key (server side) ...
back = api("GET", f"/files/{file['id']}/content", raw=True)
# ... or make a signed link that expires, for an <img> or a download button in your page.
link = api("POST", f"/files/{file['id']}/links", json_body={"expires_in_seconds": 600})
print("Signed link until", link["expires_at"])

To show a file in a browser, give the page the signed link, never your key. The link expires and can be revoked. See Files and imports.

#Errors

Every error has a stable code, a message, a retryable flag and details, plus an HTTP status. Act on the code.

Pythonexamples/languages/python/crm.py
try:
    api("GET", "/records/rec_doesnotexist")
except AgentDBError as err:  # a network error raises URLError instead
    print(err.status, err.code, err)  # 404 NOT_FOUND ...
    if err.retryable:
        print("Safe to retry later")

Network errors raise URLError; the helper retries those only when the call is safe to repeat.

Common codes:

CodeHTTPWhat to do
VALIDATION_ERROR, FIELD_TYPE_MISMATCH400Fix the request; details names the field.
UNAUTHENTICATED401Check the key.
FORBIDDEN403The key's role or a permission rule does not allow this.
NOT_FOUND404Check the id and the workspace.
VERSION_CONFLICT409Read again and retry the update.
RATE_LIMITED429Wait for Retry-After, then retry.

The error codes page lists them all.

#Rate limits and retries

AgentDB limits how many requests a key and a workspace may send. Over the limit, it answers 429 RATE_LIMITED with a Retry-After header in seconds.

The request helper above already handles this:

  • On 429 or 503, it waits for Retry-After, or backs off (0.5, 1, 2, 4 seconds), then tries again.
  • On a network error, it retries only reads and writes with an idempotency key.
  • It gives up after a few attempts and reports the error.

To load many records, use one batch call instead of one call per record: POST /records/upsert takes up to 500 items. See records_upsert_batch.

#Idempotency keys

A timeout can leave you unsure whether a write happened. Send an Idempotency-Key header with each write you may retry. If the same key comes again with the same request, AgentDB returns the first result and writes nothing twice. Keys are kept for 7 days.

Pythonexamples/languages/python/crm.py
key = str(uuid.uuid4())  # one key per intention; reuse it only to retry the same request
request = {"object": "contact", "data": {"name": "Mary Somerville", "email": f"mary-{run}@example.com"}}
first = api("POST", "/records", json_body=request, idempotency_key=key)
retry = api("POST", "/records", json_body=request, idempotency_key=key)  # e.g. after a timeout
print("Same record, written once" if first["id"] == retry["id"] else "Duplicate!")

Use a new key for each new intention, such as each form submission. The same key with a different request fails with IDEMPOTENCY_KEY_REUSED.

#Run the full example

The complete program is examples/languages/python/crm.py. Set the three environment variables and run:

Shell
python3 crm.py

It prints one OK line per topic: OK connect, OK create, OK read, OK update, OK query, OK relationships, OK files, OK errors and OK idempotency.