FastAPI
PyPI 上的 aidy 包是 Python 的宿主套件。它生成 x-aidy 标注,实现身份与搜索契约,并校验 aidy 每次调用携带的 Aidy-Assertion 头。运行时本身通过 aidy-server 运行在你的应用旁边。
pip install "aidy[fastapi]"需要 Python 3.12 或更高版本。
用 op() 标注操作
Section titled “用 op() 标注操作”op() 返回 {"x-aidy": {...}},直接传给 FastAPI 的 openapi_extra。它接受 x-aidy 的各个键,写成 snake case(timeout_seconds 对应 timeoutSeconds)。嵌套对象保持线上格式的 camelCase,类型为 Confirmation、Next、Reference 和 Cli。值为 None 的参数会被省略,使用目录默认值。标注不合法时,模块导入阶段就会抛出 ValueError,列出所有问题。
from fastapi import FastAPIfrom 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]: ...POST 默认 effect: create、approval: always。确认卡片的 lookup 路径必须由目录中的某个 GET 操作提供,所以 GET /api/vm/{vm_id} 也要有自己的 op(...)。resolve 让用户可以说 gpu-train-01,而 API 需要的是 vm-42,详见 Resolve。
表单与链式调用
Section titled “表单与链式调用”role: form 操作接收目标调用的参数,返回一个表单。问题 id 是它所填写参数的点分路径。
@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 在调用成功后、模型回复之前执行后续调用,后续操作自身的审批规则依然生效。详见链式调用。
目录中恰好有一个操作声明 role: identity。搜索操作接受必填的 q 和可选的 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) ] )搜索结果还可以带 content,即正文段落本身(最多 4000 个字符),只有模型会读:SearchHit(..., excerpt=vm.summary, content=vm.description)。这些模型序列化为 camelCase 并省略缺失的字段,在响应和 FastAPI 的 OpenAPI 文档中都一样,因此 aidy 读取的目录展示的就是线上格式。Identity 序列化时省略空字段。拥有 aidy:admin(导出为 ADMIN_SCOPE)的用户可以修改模型设置。
用 AidyHost 校验断言
Section titled “用 AidyHost 校验断言”AidyHost 安装一个 ASGI 中间件。没有 Aidy-Assertion 的请求原样放行;带有断言的请求会依次检查:固定公钥下的签名、有效期与 audience、方法、URL 和请求体哈希、重放、调用者的 (subject, tenant)、路由实际分派到的操作,以及操作需要审批时的审批 id。
import jsonimport os
from aidy import load_public_keysfrom 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)校验失败时返回 401 {"detail": "aidy_assertion_invalid", "code": "<code>"},code 指出失败的检查项(bad_signature、expired、url、body、replay、subject、operation、approval_missing 等)。identity 抛出的 HTTPException 会原样返回。
公钥 JWK 由 aidy keys generate 生成,见部署。轮换密钥期间,把新旧两把公钥都传给 load_public_keys。
位于代理之后
Section titled “位于代理之后”断言绑定的是 htu:宿主的公开源(aud)加上 aidy 调用的路径和查询串,即使 aidy 通过内部基础地址(host.baseUrl)访问你的应用也是如此。AidyHost 用 public_url 加上原始请求路径和查询串重建这个 URL,public_url 默认等于 audience,无论 aidy 用哪个内部地址都无需改动。只有当代理在请求到达应用前剥掉了路径前缀时才需要设置它:
AidyHost(app, ..., public_url="https://console.example.com/gw")用 Redis 做重放缓存
Section titled “用 Redis 做重放缓存”默认的 MemoryReplayCache 只在单个进程内有效。多 worker 或多副本部署时,传入一个共享存储,签名与 redis-py 的 set(key, value, *, nx=True, ex=seconds) 一致,同步或异步均可:
from redis.asyncio import Redis
AidyHost(app, ..., replay_cache=Redis.from_url("redis://cache:6379/0"))键名为 aidy:jti:<jti>,在断言不再可能被接受时过期。
用 AidyCall 记录审计
Section titled “用 AidyCall 记录审计”AidyCall 是一个依赖项,值为校验通过的 AssertionClaims;用户直接发起的请求则为 None。
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) ...在审计日志中记录 actor = aidy、rid 和 apr。
不使用 FastAPI
Section titled “不使用 FastAPI”其他框架可以直接调用校验函数:
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")完整 API 见 Python 参考。