Skip to content

FastAPI

The aidy package on PyPI is the host kit for Python. It builds x-aidy annotations, answers the identity and search contracts, and verifies the Aidy-Assertion header on every call aidy makes. The runtime itself runs beside your app with aidy-server.

Terminal window
pip install "aidy[fastapi]"

Python 3.12 or later is required.

op() returns {"x-aidy": {...}} for FastAPI’s openapi_extra. It takes the keys of x-aidy in snake case (timeout_seconds becomes timeoutSeconds). Nested objects keep the wire’s camelCase and are typed as Confirmation, Next, Reference and Cli. Arguments left as None are omitted, so catalog defaults apply. An invalid annotation raises ValueError listing every problem when the module is imported.

from fastapi import FastAPI
from pydantic import BaseModel
from aidy import op
app = FastAPI(title="Cloud Console")
class StopBody(BaseModel):
forced: bool = False
@app.post(
"/api/vm/{vm_id}/stop",
openapi_extra=op(
"stop_vm",
title="Stop server",
description="Stop a running cloud server (VM). Also called instance or machine.",
open="/console/instance/{vm_id}",
resolve={"vm_id": {"op": "list_vms"}},
confirmation={
"title": "Stop server {resource_name}?",
"fields": [{"key": "forced", "label": "Force", "values": {"true": "Yes", "false": "No"}}],
"lookup": {"path": "/api/vm/{vm_id}", "labelPath": "name"},
"risk": "medium",
},
),
)
async def stop_vm(vm_id: str, body: StopBody) -> dict[str, str]: ...

A POST defaults to effect: create and approval: always. The confirmation lookup path must be served by a GET operation in the catalog, so GET /api/vm/{vm_id} needs its own op(...). resolve lets the user say gpu-train-01 where the API wants vm-42; see Resolve.

A role: form operation receives the target call’s arguments and answers a form. Question ids are the dotted paths of the arguments they fill.

@app.post("/api/clusters/form", openapi_extra=op("cluster_form", role="form"))
async def cluster_form(args: dict) -> dict:
zones = await list_zones()
return {
"prompt": "Create a Kubernetes cluster",
"questions": [
{"id": "name", "prompt": "Name", "kind": "text", "required": True},
{
"id": "zone_id",
"prompt": "Zone",
"kind": "choice",
"required": True,
"options": [{"id": z.id, "label": z.name} for z in zones],
},
],
}
@app.post(
"/api/clusters/drafts",
openapi_extra=op(
"prepare_cluster",
form="cluster_form",
next={
"op": "commit_cluster_draft",
"arguments": {"draft_id": "id", "revision": "revision"},
"when": {"status": "prepared"},
},
),
)
async def prepare_cluster(body: ClusterDraft) -> Draft: ...

next runs the follow-up call after success, before the model speaks. The next operation’s own approval still applies. See Chains.

Exactly one operation answers role: identity. Search operations take a required q and an optional limit.

from fastapi import Request
from aidy import Identity, SearchHit, SearchResponse
@app.get("/api/me", openapi_extra=op("whoami", role="identity"))
async def whoami(request: Request) -> Identity:
user = current_user(request)
scopes = ["aidy:admin"] if user.is_admin else []
return Identity(subject=user.id, tenant=user.tenant_id, name=user.name, locale="zh-CN", scopes=scopes)
@app.get("/api/vms/search", openapi_extra=op("search_vms", role="search"))
async def search_vms(q: str, limit: int = 10) -> SearchResponse:
return SearchResponse(
hits=[
SearchHit(type="vm", id=vm.id, title=vm.name, url=f"/console/instance/{vm.id}")
for vm in find_vms(q, limit)
]
)

A search hit may also carry content, the passage itself (up to 4000 characters), which only the model reads: SearchHit(..., excerpt=vm.summary, content=vm.description). The models serialize in camelCase without absent fields, in responses and in FastAPI’s OpenAPI document alike, so the catalog aidy reads shows the wire shapes. Identity omits absent fields when serialized. aidy:admin (exported as ADMIN_SCOPE) lets the user change model settings.

AidyHost installs an ASGI middleware. A request without Aidy-Assertion passes untouched. With one, it checks the signature against your pinned keys, lifetime and audience, method, URL and body hash, replay, the caller’s (subject, tenant), the operation the router dispatches to, and the approval when the operation needs one.

import json
import os
from aidy import load_public_keys
from aidy.fastapi import AidyHost
def caller(request: Request) -> tuple[str, str | None] | None:
"""(subject, tenant) of the request's Authorization, as the UI authenticates it."""
user = current_user(request)
return (user.id, user.tenant_id) if user else None
AidyHost(
app,
keys=load_public_keys([json.loads(os.environ["AIDY_PUBLIC_JWK"])]),
audience="https://console.example.com",
identity=caller, # sync or async
)

Failure answers 401 {"detail": "aidy_assertion_invalid", "code": "<code>"}, where code names the failed check (bad_signature, expired, url, body, replay, subject, operation, approval_missing, …). An HTTPException raised by identity is answered as is.

The public JWK comes from aidy keys generate; see Deploy. During key rotation, pass both keys to load_public_keys.

The assertion binds htu: the host’s public origin (aud) followed by the path and query aidy called, even when aidy reaches your app at an internal base URL (host.baseUrl). AidyHost rebuilds it as public_url plus the raw request path and query. public_url defaults to audience, which is right whatever internal address aidy uses. Set it only when a proxy strips a path prefix before the app:

AidyHost(app, ..., public_url="https://console.example.com/gw")

The default MemoryReplayCache is per process. With several workers or replicas, pass a shared store with redis-py’s set(key, value, *, nx=True, ex=seconds) signature, sync or async:

from redis.asyncio import Redis
AidyHost(app, ..., replay_cache=Redis.from_url("redis://cache:6379/0"))

Keys are aidy:jti:<jti> and expire when the assertion can no longer be accepted.

AidyCall is a dependency holding the verified AssertionClaims, or None for a direct user call.

from aidy.fastapi import AidyCall
@app.post("/api/vm/{vm_id}/stop", openapi_extra=op("stop_vm", ...))
async def stop_vm(vm_id: str, body: StopBody, aidy: AidyCall) -> dict[str, str]:
if aidy is not None:
audit(actor="aidy", user=aidy.sub, run=aidy.rid, call=aidy.cid, approval=aidy.apr)
...

Record actor = aidy, rid and apr in your audit log.

Other frameworks call the verifier directly:

from aidy import check_call, verify_assertion
claims = verify_assertion(
token,
keys=keys,
audience="https://console.example.com",
method="POST",
url=full_url_as_sent,
body=raw_body,
remember=lambda jti, until: cache.add(jti, until), # False when seen before
)
check_call(claims, subject=user.id, tenant=user.tenant_id, op="stop_vm", approval="always")

The full API is in the Python reference.