AI Service
AI Service 封装模型调用、可选 Agent 执行与检索能力;以 React / Go / Python 分工说明运行时与业务授权、数据所有权的边界。
[!info] related notes
- 所属 MOC: AI Agent Application MOC
- 核心组件: Agent Engine, Tool Registry, RAG Engine, Memory Manager
- 上游: Backend For Frontend (Go)
- 下游: LLM Provider Abstraction
AI Service
一句话定义
AI Service 是提供模型推理、Agent 执行或检索等能力的服务。下文采用 React + Go + Python 的分工示例:Python 可作为 Agent Engine 的宿主,由 Go 后端调用;语言、三层部署、RAG 和长期记忆都不是概念成立的必要条件。
它解决什么问题
当推理依赖 Python 库、需要单独扩容或团队职责明确时,独立服务便于管理 AI 依赖和执行生命周期。代价是增加跨服务鉴权、网络故障、版本兼容和观测成本。
Python 可以直接提供带鉴权和持久化的用户 API;Go 也可以调用模型与实现 Agent。是否拆服务取决于实际边界,不能用语言选择代替设计。组合方案见 agentic-application-stack。
核心原理
职责边界
在本例分工中:
- AI Service 管理模型调用、受控工具执行、上下文与可选 RAG / memory、runtime 状态和遥测。
- Go 业务层拥有用户、订单、支付等业务规则与数据;AI 工具通过受控接口请求业务动作。
- 上游鉴权不免除 AI Service 的入口信任校验、租户隔离和工具执行授权;不能信任客户端任意传入的用户 ID。
- 会话、checkpoint、业务记录分别明确 owner;部署中允许共享数据库时,也要限制表、接口和写入职责。
- SSE 是否直达前端、文件上传由谁处理属于 API 和部署选择,不是 AI Service 的固有禁令。
内部架构
┌─────────────────────────────────────────────┐
│ AI Service (FastAPI) │
│ │
│ ┌─────────────────────────────────────────┐│
│ │ API Layer ││
│ │ /chat (SSE stream) ││
│ │ /tools (工具列表) ││
│ │ /health ││
│ └────────────────┬────────────────────────┘│
│ │ │
│ ┌────────────────▼────────────────────────┐│
│ │ Agent Engine ││
│ │ Agent Loop · Planner · Output Parser ││
│ └───┬────────┬────────┬──────────┬────────┘│
│ │ │ │ │ │
│ ┌───▼──┐ ┌───▼──┐ ┌───▼───┐ ┌───▼────┐ │
│ │ LLM │ │ Tool │ │ RAG │ │ Memory │ │
│ │Gateway│ │Runtime│ │ Engine│ │Manager │ │
│ └──────┘ └──────┘ └───────┘ └────────┘ │
│ │
│ ┌─────────────────────────────────────────┐│
│ │ Observability Layer ││
│ │ Trace · Metrics · Token Tracking ││
│ └─────────────────────────────────────────┘│
└─────────────────────────────────────────────┘
与 Go 后端的通信协议示例
Go → Python: POST /chat
Body: Context Bundle (JSON)
Headers: X-Session-ID, X-Turn-ID, X-User-ID
Python → Go: SSE stream
Events: text_delta, tool_call_start, tool_call_result,
progress, error, done
上面的 X-User-ID 等只是关联字段,必须由经过认证的上游生成或绑定,不能充当身份凭证。Context Bundle 还需明确权限范围、数据版本与有效期;业务动作执行时再检查当前状态。
典型工程实现
FastAPI 服务结构
以下仅展示组装与流返回的伪代码,ChatRequest、Context、engine 和 event 类型为项目自定义接口,不是 FastAPI 内置类。真实 handler 需先认证调用方、校验上下文与授权,再创建流;输出按公开事件合同筛选。
# main.py(省略依赖初始化与入口验证)
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
@app.post("/chat")
async def chat(request: ChatRequest):
# 1. 解析 Context Bundle
context = Context.from_bundle(request.context_bundle)
# 2. 启动 Agent Engine
engine = AgentEngine(
llm=llm_gateway.get_model(context.model),
tools=tool_registry.get_tools(context),
memory=memory_manager,
rag=rag_engine,
)
# 3. 流式返回
async def event_stream():
async for event in engine.run(context):
yield f"event: {event.type}\ndata: {event.json()}\n\n"
return StreamingResponse(event_stream(), media_type="text/event-stream")
流启动后还需处理错误事件、取消、上游资源释放与持久化终态;HTTP 200 或流 EOF 本身不证明任务成功。
模块目录结构示例
apps/ai-service/
├── main.py # FastAPI 入口
├── api/
│ ├── chat.py # /chat 路由
│ └── tools.py # /tools 路由
├── engine/
│ ├── agent_engine.py # Agent Engine
│ ├── planner.py # 任务规划
│ └── output_parser.py # 输出解析
├── tools/
│ ├── registry.py # Tool Registry
│ ├── executor.py # Tool Executor
│ └── sandbox.py # 执行沙箱
├── rag/
│ ├── retriever.py # 检索器
│ ├── reranker.py # 重排序
│ └── chunker.py # 文档分块
├── memory/
│ ├── short_term.py # 对话历史
│ └── long_term.py # 用户画像
├── llm/
│ ├── provider.py # Provider 抽象
│ ├── gateway.py # Model Gateway
│ └── router.py # Model Router
└── observability/
├── tracer.py # Trace 记录
└── token_tracker.py # Token 用量追踪
常见设计模式
1. LLM Provider 抽象
通过统一接口对接多个 LLM Provider;fallback 仅在能力、数据与授权策略允许时采用,不兼容时应明确失败或升级。
2. 工具动态加载
根据用户角色和场景动态加载工具,而不是全量暴露。
3. Context Bundle 模式
Go 后端可组装 Bundle,AI Service 按约定使用快照或通过授权接口补取;固定 Bundle 不保证执行时业务状态仍未变化。
4. SSE 事件流
AI Service 通过 SSE 输出事件,Go 按公开事件合同转发;内部 trace、工具凭据和未授权数据不能无条件透传。
常见坑
- 绕过数据 owner 写业务状态:破坏不变量;不能仅凭工具参数合法就执行。
- 无条件 Fallback:备用模型可能不满足工具、结构化输出或数据策略要求。
- 用量和预算不明:缺失 usage 应标为未知,计费还需模型与价格版本。
- 记录了 Trace 就认为可复现:记录范围、工具环境和配置快照决定回放边界。
- 阻塞事件循环:在 async 路径执行同步 I/O 或 CPU 密集工作可能拖慢同 worker 的其他请求,需按负载采用异步接口、线程池或独立 worker。
和其他概念的关系
- vs Agent Engine: Engine 是 AI Service 的核心模块
- vs BFF (Go): BFF 是上游,AI Service 是下游
- vs LLM Provider Abstraction: Provider 抽象是 AI Service 的内部组件
- vs Agent Runtime: Runtime 的概念更广,AI Service 是 Runtime 的一种实现
总结
AI Service 的核心价值是把 AI/ML 能力封装成一个独立的、可复用的服务层。它可以聚焦 AI 执行,但仍必须遵守身份、权限、业务数据所有权与交付合同。