快速开始:FastAPI
本快速开始给 FastAPI 应用接入 aidy。FastAPI 继续提供你的 API;aidy 作为独立进程(aidy-server serve)运行在旁边,由反向代理把 aidy 的路径转发给它。Python kit aidy 负责给路由加注解,并校验 aidy 每次调用时发送的断言。
贯穿全文的例子是位于 https://console.example.com 的云控制台,其中有一个 stop_vm 操作。
pip install "aidy[fastapi]"npm install -g @aidy-dev/cliPython 包 aidy 需要 Python 3.12 或更高版本。CLI 用来生成 aidy 的签名密钥。
2. 给路由加注解
Section titled “2. 给路由加注解”op() 为 FastAPI 的 openapi_extra 构造 x-aidy 对象。它接受 x-aidy 参考中的键,写成 snake case(timeout_seconds 对应 timeoutSeconds),并在不符合 schema 时抛出列出全部问题的 ValueError,所以错误的注解在导入时就会失败。
from fastapi import FastAPI, Requestfrom pydantic import BaseModel
from aidy import Identity, SearchHit, SearchResponse, load_public_keys, opfrom aidy.fastapi import AidyCall, AidyHost
app = FastAPI()
class Vm(BaseModel): id: str name: str status: str
class StopBody(BaseModel): forced: bool = False
@app.get("/api/vm/{vm_id}", openapi_extra=op("get_vm", description="Get a cloud server (VM) by id."))async def get_vm(vm_id: str, request: Request) -> Vm: return load_vm(current_user(request), vm_id)
@app.post( "/api/vm/{vm_id}/stop", openapi_extra=op( "stop_vm", title="Stop server", description="Stop a running cloud server (VM).", effect="update", open="/console/instance/{vm_id}", confirmation={ "title": "Stop server {resource_name}?", "fields": [{"key": "forced", "label": "Force", "values": {"true": "Yes", "false": "No"}}], "lookup": {"path": "/api/vm/{vm_id}", "labelPath": "name"}, }, ),)async def stop_vm(vm_id: str, body: StopBody, request: Request, aidy: AidyCall) -> Vm: if aidy is not None: # 委托调用:记录审计 audit(actor="aidy", run=aidy.rid, approval=aidy.apr) return stop(current_user(request), vm_id, forced=body.forced)stop_vm 是写操作(effect="update"),默认需要审批。它的请求体会被展开:agent 看到的是一个包含 vm_id 和 forced 的输入。见目录和操作与效果。
3. 添加身份和搜索
Section titled “3. 添加身份和搜索”@app.get("/api/me", openapi_extra=op("whoami", role="identity"))async def whoami(request: Request) -> Identity: user = current_user(request) return Identity(subject=user.id, tenant=user.tenant_id, name=user.name, locale="zh-CN")
@app.get("/api/vms/search", openapi_extra=op("search_vms", role="search"))async def search_vms(q: str, request: Request, 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(current_user(request), q, limit) ] )身份操作是无参数的 GET,每个目录只能有一个。搜索操作是带必填参数 q 的 GET。见身份和搜索与知识。
4. 生成密钥并校验断言
Section titled “4. 生成密钥并校验断言”aidy keys generate --kid aidy-2026-11 -o aidy-2026-11.private.jwk该命令打印用于宿主配置的公钥 JWK,并把私钥 JWK(aidy 的签名密钥)写入一个权限为 0600 的新文件。用 AidyHost 在 FastAPI 中固定(pin)公钥:
import jsonimport os
def caller(request: Request) -> tuple[str, str | None] | None: """请求凭据对应的 (subject, tenant),与 UI 的鉴权方式完全一致。""" 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,)不带 Aidy-Assertion 的请求原样放行。带有断言时,AidyHost 检查签名、有效期、audience、方法、URL、请求体哈希、重放、subject、tenant、操作和审批,失败时返回 401 aidy_assertion_invalid。端点通过 AidyCall 参数拿到 claims(用户直接调用时为 None)。
5. 运行 aidy-server
Section titled “5. 运行 aidy-server”@aidy-dev/server 包中的 aidy-server serve 把 aidy 作为独立的 HTTP 服务运行,配置全部来自环境变量:
export AIDY_URL=https://console.example.comexport AIDY_HOST_ORIGIN=https://console.example.comexport AIDY_HOST_BASE_URL=http://api:8000export AIDY_HOST_OPENAPI=/openapi.jsonexport AIDY_SIGNING_KEY="$(cat aidy-2026-11.private.jwk)"export AIDY_SECRET="$(openssl rand -base64 32)"export AIDY_DATABASE_URL=postgres://aidy@db:5432/aidyexport AIDY_MODELS='[{"id":"main","provider":"openai","model":"gpt-4.1-mini","apiKey":"sk-…"}]'export PORT=8787npx @aidy-dev/server serveAIDY_URL是这个 aidy 实例的公开 URL,即断言的iss。AIDY_HOST_ORIGIN是你的公开 origin,即断言的aud;它必须等于AidyHost中的audience。AIDY_HOST_BASE_URL是 aidy 访问 FastAPI 的地址,默认等于 origin。AIDY_HOST_OPENAPI用用户的凭据拉取;FastAPI 在/openapi.json提供 OpenAPI 3.1。默认值是/api/openapi.json。AIDY_SIGNING_KEY就是私钥 JWK 本身,JSON 格式。AIDY_SECRET至少 32 字节,用来加密设置中保存的模型 API key。AIDY_DATABASE_URL保存会话、事件、审批和设置:postgres://…或sqlite:<path>。AIDY_MODELS是默认的模型链,每一项都需要id。
同一个服务也以 Docker 镜像 ghcr.io/aidy-dev/aidy-server 提供。全部变量见部署。
6. 反向代理 aidy 的路径
Section titled “6. 反向代理 aidy 的路径”aidy 在你的 origin 下提供以下路径。把它们转发给 aidy-server,其余的转发给 FastAPI:
| 路径 | 用途 |
|---|---|
/aidy/v0/* |
HTTP API:会话、运行、目录、搜索、设置 |
/mcp |
基于 streamable HTTP 的 MCP |
/skill.md、/llms.txt |
生成的文档 |
/.well-known/aidy-keys.json |
aidy 的公钥 |
location /aidy/v0/ { proxy_pass http://aidy:8787; proxy_buffering off; }location = /mcp { proxy_pass http://aidy:8787; proxy_buffering off; }location = /skill.md { proxy_pass http://aidy:8787; }location = /llms.txt { proxy_pass http://aidy:8787; }location = /.well-known/aidy-keys.json { proxy_pass http://aidy:8787; }location / { proxy_pass http://api:8000; }运行以 server-sent events 流式输出,所以要对 /aidy/v0/ 和 /mcp 关闭响应缓冲。
7. 试一试
Section titled “7. 试一试”curl -H "Authorization: Bearer $TOKEN" https://console.example.com/aidy/v0/catalogcurl -H "Authorization: Bearer $TOKEN" https://console.example.com/skill.md
aidy login https://console.example.comaidy search "gpu"aidy stop-vm --vm-id vm-42aidy stop-vm 会在终端上请求确认,然后才执行写操作。想写成 aidy vm stop vm-42,就在 op() 中加上 cli={"command": "vm stop", "args": ["vm_id"]}。
应用内 agent 的 React 侧边栏,按快速开始:Workers 上的 Hono 第 8 步添加即可。
- FastAPI 指南:表单、resolve、链式调用和延迟任务。
- Python 参考:kit 的全部函数。
- 委托:
AidyHost校验什么、为什么。 - 部署:在生产环境运行
aidy-server。