跳转至

指南 08 · 网关鉴权与部署

1. 两种启动方式怎么选

场景
开箱即用,快速起服务 serve(apps)
要挂鉴权 / 自定义中间件 / 精确控制 create_app(reg) + 自己 uvicorn.run

serve() 内部也是「注册 → create_appuvicorn.run」,只是把后两步封装了。要插入自定义逻辑(如 API Key 鉴权)就用 create_app

2. 最小鉴权:API Key(中间件)

做法:用 create_app 拿 FastAPI 实例 → 挂一个 HTTP 中间件校验 Authorization: Bearer <key> → 自己启动。完整可运行版见 auth_gateway 示例

from agentframework.gateway.app import create_app
from agentframework.gateway.registry import AppRegistry
import uvicorn


def install_api_key_auth(app, api_key: str):
    @app.middleware("http")
    async def require_key(request, call_next):
        if request.headers.get("Authorization") != f"Bearer {api_key}":
            # 返回 jsonRes 错误结构,前端无感
            from starlette.responses import JSONResponse

            return JSONResponse(
                status_code=401,
                content={
                    "code": 401,
                    "statusText": "Unauthorized",
                    "message": "invalid api key",
                    "data": None,
                },
            )
        return await call_next(request)

    return app


reg = AppRegistry()
reg.register("customer_service", compiled_graph)  # 注册你的工作流
key = os.environ.get("AGENT_API_KEY", "dev-key-123")
app = install_api_key_auth(create_app(reg), key)
uvicorn.run(app, host="0.0.0.0", port=8080)

CORS 默认 ["*"] 全放行(方便浏览器直连);鉴权靠 header,不受 CORS 影响。需要收紧 CORS 时给 create_app(cors_origins=[...])

3. 部署要点

  • 异步 + 持久化:网关是异步(SSE),涉及断点持久化时用各 saver 的异步版,见指南 06
  • 同会话并发门控:生产网关对同一 chatId 并发会拒绝冲突,防止同一会话重入乱序。
  • 鉴权建议:外部暴露一定挂鉴权;内网调试可先 serve 裸跑。

4. 完整可运行示例

完整源码、运行与验证步骤见 auth_gateway 示例(KEY 默认 dev-key-123,请求需带 Authorization: Bearer <key>,否则 401)。

下一步

  • 想完全自定义对外的协议(不加鉴权)→ 运行时与网关
  • 接口字段 / 错误结构的权威定义 → 仓库 doc/Agent接口契约.md