AI Service
AI Service 是三层架构中负责 Agent 推理、工具执行、RAG 检索和记忆管理的独立服务层。它是 Agent Engine 的宿主环境。
#type / concept
#status / evergreen
#tech / ai
#tech / architecture
[!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 是三层架构(React + Go + Python)中的 Python 服务层,负责 Agent 推理、工具执行、RAG 检索、记忆管理和可观测性。它不直接面对用户,而是通过 Go 后端间接提供服务。
它解决什么问题
如果把 Agent 推理逻辑放在 Go 后端里,会遇到:
- Python 的 AI/ML 生态(LangChain、LlamaIndex、PyTorch)比 Go 丰富得多
- LLM SDK(OpenAI、Anthropic)的 Python 版本更成熟
- 向量检索、Embedding 等操作在 Python 生态中更方便
如果让 Python 直接面对前端,会遇到:
- 缺少统一的鉴权、审计、会话管理
- 与业务系统(用户、订单、权限)的集成困难
- 不同团队的技术栈冲突
AI Service 作为独立服务层,专注 Agent 能力,通过 API 与 Go 后端通信。
核心原理
职责边界
AI Service 负责: AI Service 不负责:
├─ Agent 推理循环 ├─ 用户鉴权
├─ LLM 调用与模型路由 ├─ 业务数据 CRUD
├─ 工具注册与执行 ├─ 会话持久化
├─ RAG 检索与重排序 ├─ SSE 直接推送到前端
├─ 记忆管理 ├─ 文件上传/下载
├─ 结构化输出解析 └─ 支付/通知等业务逻辑
└─ Trace 与可观测性
内部架构
┌─────────────────────────────────────────────┐
│ 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
典型工程实现
FastAPI 服务结构
# 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")
模块目录结构
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,避免 AI Service 直接查业务库。
4. SSE 事件流
AI Service 通过 SSE 流式输出事件,Go 后端透传到前端。
常见坑
- AI Service 直接查业务数据库: 打破了层间边界,应该由 Go 后端在 Context Bundle 中提供
- 不做模型 Fallback: 一个 Provider 挂了整个服务不可用
- 不追踪 Token 用量: 无法监控成本
- 不记录 Trace: 出问题无法复现和调试
- 同步阻塞调用: 工具执行或 LLM 调用阻塞了整个服务
和其他概念的关系
- 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 能力封装成一个独立的、可复用的服务层。它不关心用户鉴权、不关心业务数据、不关心前端渲染,只专注于 Agent 推理和执行。