Files
aiagent/docs/architecture.md
renjianbo beff3fac8d fix: delete agent 500 error + dynamic personality + deployment guide
- Fix delete agent 500: clean up FK records (agent_llm_logs, permissions,
  schedules, executions, team_members) and unbind goals/tasks before delete
- Remove hardcoded personality templates in Android, replace with dynamic
  system prompt generation from name + description
- Set promptSectionsEnabled=false to bypass PromptComposer for personality
- Add Tencent Cloud Linux deployment guide (Docker Compose)
- Accumulated backend service updates, frontend UI fixes, Android app changes

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-06-29 01:17:21 +08:00

413 lines
21 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 🏛️ 架构设计文档
> **Architecture Design Document**
---
## 一、系统概述
天工智能体平台是一个企业级 AI 智能体Agent平台提供智能对话、知识库管理、智能体编排等核心能力采用**前后端分离** + **异步任务队列** 的架构设计。
---
## 二、技术选型
| 层级 | 技术 | 版本 | 选型理由 |
|:----|:-----|:-----|:---------|
| **前端框架** | Vue 3 (Composition API) | 3.4+ | 轻量、响应式、TypeScript 友好 |
| **前端构建** | Vite | 5+ | 极速 HMR开发体验优异 |
| **状态管理** | Pinia | 2+ | Vue 3 官方推荐TypeScript 支持完善 |
| **路由** | Vue Router | 4+ | SPA 路由,支持导航守卫 |
| **HTTP 客户端** | Axios | 1+ | 请求/响应拦截,统一错误处理 |
| **后端框架** | FastAPI | 0.110+ | 高性能异步框架,自动生成 OpenAPI 文档 |
| **ORM** | SQLAlchemy | 2.0+ | 成熟的 Python ORM异步支持 |
| **数据验证** | Pydantic | 2+ | 类型安全,与 FastAPI 深度集成 |
| **数据库迁移** | Alembic | 1.13+ | 版本化管理数据库变更 |
| **数据库** | MySQL (腾讯云) | 8.0+ | 稳定可靠的关系型数据库 |
| **缓存** | Redis | 7+ | 高性能缓存 + 消息队列 |
| **任务队列** | Celery | 5.3+ | 分布式异步任务处理 |
| **认证** | JWT | — | 无状态认证,支持 Token 刷新 |
| **容器化** | Docker + Docker Compose | 最新 | 简化部署,环境一致 |
---
## 三、架构分层
```
┌─────────────────────────────────────────────────────────────┐
│ 客户端层 (Client Layer) │
│ 浏览器 (Chrome/Edge) │ 移动端 │ 第三方 API 调用 │
└───────────────────────┬─────────────────────────────────────┘
│ HTTPS
┌───────────────────────▼─────────────────────────────────────┐
│ 接入层 (Gateway Layer) │
│ Nginx 反向代理 │ SSL 终止 │ 静态资源服务 │ 端口 8038/8037 │
└───────────────────────┬─────────────────────────────────────┘
┌───────────────────────▼─────────────────────────────────────┐
│ 前端应用层 (Frontend Layer) │
│ Vue 3 SPA │ Pinia Store │ Vue Router │ Axios Client │
│ ┌─────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐ │
│ │ Views │ │Components│ │ Stores │ │ Utils │ │
│ │ 页面组件 │ │ 公共组件 │ │ 状态管理 │ │ 工具/请求封装│ │
│ └─────────┘ └──────────┘ └──────────┘ └──────────────┘ │
└───────────────────────┬─────────────────────────────────────┘
│ HTTP/JSON
┌───────────────────────▼─────────────────────────────────────┐
│ 后端服务层 (Backend Layer) │
│ FastAPI │ 中间件 │ 路由 │ 依赖注入 │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ API 路由层 │ │ 认证/授权中间件 │ │
│ │ (api/v1/*) │ │ (JWT、CORS) │ │
│ ├──────────────┤ ├──────────────────┤ │
│ │ Service 层 │ │ 任务调度 │ │
│ │ (业务逻辑) │ │ (Celery 任务) │ │
│ ├──────────────┤ ├──────────────────┤ │
│ │ Models 层 │ │ Schemas 层 │ │
│ │ (ORM 定义) │ │ (数据验证) │ │
│ └──────────────┘ └──────────────────┘ │
└──────┬────────────────────────────┬─────────────────────────┘
│ │
▼ ▼
┌──────────────┐ ┌──────────────────┐
│ MySQL 8.0 │ │ Redis 7 │
│ (腾讯云) │ │ 缓存 / 任务队列 │
│ 持久化存储 │ │ 会话 / 锁 │
└──────────────┘ └──────────────────┘
┌──────────────────┐
│ Celery Worker │
│ 异步任务处理 │
│ 文件处理 / 通知 │
└──────────────────┘
```
---
## 四、核心业务模块
### 1. 用户与权限模块
- **注册/登录**:用户名 + 密码JWT Token 发放
- **Token 刷新**Access Token (30min) + Refresh Token (7d)
- **个人中心**:信息查看与修改
- **角色权限**admin / workspace_admin / member支持 14 个权限端点
- **多租户**Workspace 级数据隔离,飞书应用按 workspace 隔离
### 2. 智能体模块 (Agent)
- 智能体的创建、配置、发布、下架
- **Agent 类型**specialist专家/ main主路由
- 工作流配置 `workflow_config`nodes + edges
- 执行预算 `budget_config`max_steps / max_llm_invocations / max_tool_calls
- 输入/输出 Schema 约束JSON Schema
- **Agent 市场**:发布/安装/评分(Fork)/收藏/升级
- **Agent 编排**5 种模式route / sequential / debate / pipeline / graph
- **Agent 蜂群**Swarm Leader 分解任务 → Teammate 并行执行 → 聚合结果
### 3. 知识库模块
- 文档上传与解析PDF、TXT、Markdown、HTML、CSV、JSON
- 文档分块 → 向量嵌入(支持 OpenAI / DeepSeek Embedding
- 语义检索(余弦相似度 + 混合检索)
- **RAG 增强生成**:检索 → 增强 Prompt → 生成
- **知识图谱**KnowledgeEntity节点+ KnowledgeRelation关系边
- **知识进化**Celery Beat 定时提取 → LLM 提炼 → 入库
- **知识仪表盘**:增长曲线、复用排行、类别分布
### 4. 对话模块
- 用户与智能体的实时对话SSE 流式输出)
- **事件类型**plan / think / tool_call / tool_result / final / done
- 上下文管理与会话恢复session_id
- 对话分支Branch分支创建 / 查看 / 恢复
- **记忆系统**:短期记忆(向量 RAG+ 长期记忆PersistentUserMemory+ 全局知识池
### 5. 工作流模块
- 可视化 DAG 工作流(开始 → LLM/工具/条件/循环 → 结束)
- **节点类型**start / llm / tool / condition / code / switch / parallel / subworkflow / orchestrator / evaluator
- **节点配置**:提示词模板(支持 `{{variable}}` 变量)、工具列表、模型参数
- **节点级功能**自动重试retry_config、错误处理error_handler、人工审批HITL
- 版本管理WorkflowVersion保存 / 列表 / 回滚
- 版本对比:节点变更可视化
- 节点搜索/筛选、自动布局Dagre 算法)
- 工作流验证:死循环检测、孤立节点检测、类型兼容性检查
- **Subworkflow**:嵌套子工作流,含深度防护
### 6. 工具系统
- **内置工具**56 个开箱即用工具(文件 / 文本 / HTTP / 代码 / 搜索 / 计算 / 日期 / JSON / 知识图谱 等)
- **工具分类**file_ops / text_processing / web / code / data / knowledge / search / math
- **工具参数过滤**:防止注入、类型校验
- **工具动态注册**HTTP 工具 / 代码工具 / 工作流工具,支持热更新
- **工具市场**:发布 / 安装 / 版本管理
### 7. 监控与告警
- **系统监控**:概览 / 执行统计 / 节点类型用量 / 最近动态
- **Agent 监控**LLM 调用统计 / Agent 统计 / 工具用量 / 每日趋势
- **告警系统**:规则 CRUD + 告警日志 + 通知(邮件/Webhook/站内)
- **Prometheus 指标**`/metrics` 端点,业务指标 + 系统指标
- **Grafana 仪表板**:系统/业务双面板
- **ELK 日志聚合**Filebeat → Logstash → Elasticsearch → Kibana
### 8. 商业化模块
- **模板市场**11 个行业模板(客服/研发/PR Review/面试调度/竞品监控/测试报告/入职引导/风险预警/学习助手/日报/日志分析)
- **场景契约 DSL**:统一输入契约(目标/约束/产物/验收),模板复用
- **定时任务**Cron 表达式,支持手动触发
- **Android App**:原生 Kotlin + Compose对话/历史/语音/TTS/推送
- **飞书 Bot**6 个 BotWebSocket 长连接,交互卡片,对话上下文连续性
- **PWA 移动端**manifest + Service Worker + 离线缓存 + 浏览器推送
### 9. 集成与通知
- **第三方集成**:飞书 / 微信 / SlackWebhook
- **推送通知**PushSubscription 模型 + push_service + 浏览器 Push API
- **FCM 推送**Firebase Cloud Messaging for Android
- **WebSocket 实时推送**:执行状态实时更新
- **审批系统**approval_manager + 危险工具自动审批流程
---
## 五、Agent 运行时架构
### ReAct 循环
```
用户输入 → [Think → Act → Observe] × N → Final Answer
每个迭代:
1. Think: LLM 分析当前状态,决定下一步
2. Act: 调用工具或执行操作
3. Observe: 获取工具结果,更新上下文
```
### 核心执行流程
```
AgentRuntime.execute()
├── 加载 Agent 配置workflow_config, system_prompt, tools
├── 初始化上下文memory, conversation_history, session_state
├── ReAct 循环(最多 max_iterations 轮)
│ ├── _think(): LLM 推理,决定调用哪个工具
│ ├── _act(): 执行工具调用
│ │ ├── 参数过滤(防止注入)
│ │ ├── 审批检查HITL — 危险工具需人工审批)
│ │ └── 执行工具(内置 / HTTP / 代码 / 工作流)
│ ├── _observe(): 记录结果,更新记忆
│ └── _should_continue(): 判断是否继续(任务完成?达到上限?)
├── 聚合结果 → Final Answer
└── 记录执行日志AgentLLMLog + AgentExecutionLog + ExecutionLog
```
### 记忆系统三层架构
```
┌──────────────────────────────────────────┐
│ 第一层:短期记忆(对话上下文) │
│ • 当前会话的历史消息 │
│ • memory_max_history 条消息 │
│ • 滑动窗口自动截断 │
├──────────────────────────────────────────┤
│ 第二层:向量记忆(语义检索) │
│ • AgentVectorMemory 表 │
│ • Embedding → 向量相似度检索 │
│ • 跨会话语义相关性查找 │
│ • 配置memory_vector_top_k 条 │
├──────────────────────────────────────────┤
│ 第三层:长期记忆(持久化) │
│ • PersistentUserMemory 表 │
│ • 关键信息跨会话保存 │
│ • 用户画像、偏好、学习进度 │
│ • memory_persist + memory_learning │
└──────────────────────────────────────────┘
```
### 多 Agent 编排模式
| 模式 | 描述 | API |
|------|------|------|
| **route** | 主 Agent 分析输入 → 路由到最合适的子 Agent | `/agent-chat/orchestrate` |
| **sequential** | 多个 Agent 按顺序执行,前者输出为后者输入 | `/agent-chat/orchestrate` |
| **debate** | 多个 Agent 同时回答,汇总比较 | `/agent-chat/orchestrate` |
| **pipeline** | 流水线模式,每个 Agent 处理一个阶段 | `/agent-chat/orchestrate` |
| **graph** | DAG 图模式,任意拓扑结构,并行分支 | `/agent-chat/orchestrate/graph` |
| **swarm** | Leader 分解 → Teammate 并行 → 聚合 | `/swarm/run` |
---
## 六、实时通信架构
### SSEServer-Sent Events
```
Client Server
│ │
│ POST /agent-chat/{id}/stream │
│ Accept: text/event-stream │
│───────────────────────────────>│
│ │
│ event: plan │
│ data: {"title":"...", │
│ "steps":[...]} │
│<───────────────────────────────│
│ │
│ event: think │
│ data: {"content":"...", │
│ "iteration":0} │
│<───────────────────────────────│
│ │
│ event: tool_call │
│ data: {"tool_name":"...", │
│ "tool_input":"..."} │
│<───────────────────────────────│
│ │
│ event: tool_result │
│ data: {"tool_name":"...", │
│ "tool_result":"..."} │
│<───────────────────────────────│
│ │
│ event: final │
│ data: {"content":"...", │
│ "iterations_used":3} │
│<───────────────────────────────│
│ │
│ event: done │
│ data: {"session_id":"..."} │
│<───────────────────────────────│
```
### WebSocket
```
Client Server
│ │
│ WS /ws/executions/{execution_id} │
│────────────────────────────────────>│
│ │
│ {"type":"progress","pct":50} │
│<────────────────────────────────────│
│ │
│ {"type":"node_start", │
│ "node_id":"llm-1"} │
│<────────────────────────────────────│
│ │
│ {"type":"node_complete", │
│ "node_id":"llm-1", │
│ "output":"..."} │
│<────────────────────────────────────│
│ │
│ {"type":"execution_complete", │
│ "status":"success"} │
│<────────────────────────────────────│
```
---
## 七、数据库架构
### 核心表关系
```
users (用户)
├── agents (智能体)
│ ├── agent_ratings (评分)
│ ├── agent_favorites (收藏)
│ ├── agent_schedules (定时任务)
│ ├── agent_llm_logs (LLM 调用日志)
│ ├── agent_vector_memories (向量记忆)
│ └── agent_learning_patterns (学习模式)
├── workflows (工作流)
│ └── workflow_versions (版本历史)
├── executions (执行记录)
│ └── execution_logs (执行日志)
├── knowledge_bases (知识库)
│ ├── documents (文档)
│ └── document_chunks (文档分块)
├── notifications (通知)
├── feedback_records (用户反馈)
├── conversation_branches (对话分支)
├── goals (目标)
│ └── tasks (任务)
├── orchestration_templates (编排模板)
├── node_templates (节点模板)
├── plugins (插件)
├── alert_rules (告警规则)
│ └── alert_logs (告警日志)
├── persistent_user_memories (长期记忆)
├── knowledge_entities (知识图谱节点)
├── knowledge_relations (知识图谱关系)
├── push_subscriptions (推送订阅)
├── fcm_tokens (FCM Token)
├── user_feishu_open_ids (飞书绑定)
├── scene_contracts (场景契约 DSL)
└── workspaces (工作区)
└── workspace_memberships (成员关系)
```
### 数据库索引策略
- 所有外键列均有索引
- 常用查询列status / category / is_public / created_at索引
- 时间范围查询列timestamp / triggered_at索引
- 复合索引用于高频组合查询agent_id + created_at
---
## 八、安全架构
| 安全措施 | 实现方式 | 位置 |
|:---------|:---------|:------|
| JWT 认证 | HS256 签名30min Access + 7d Refresh | `auth.py` middleware |
| 密码安全 | bcrypt 哈希12 rounds | `auth.py` |
| CORS 保护 | FastAPI CORSMiddleware白名单域名 | `main.py` |
| 输入验证 | Pydantic v2 严格验证所有 endpoint 输入 | 全部 schemas |
| SQL 注入防护 | SQLAlchemy 2.0+ 参数化查询 | 全部 models |
| XSS 防护 | CSP 头 + 输出转义(前端 Vue 3 | 前端 `index.html` |
| CSRF 防护 | SameSite Cookie + Token Header | 前端 axios 配置 |
| Rate Limiting | Redis 滑动窗口(登录 5/minWebhook 60/min | `rate_limiter.py` |
| 安全头 | HSTS / X-Content-Type-Options / X-Frame-Options | `security_headers.py` |
| 文件上传安全 | 类型检查 + 大小限制 + 病毒扫描 | `uploads.py` |
| HTTPS | Nginx 侧 SSL 终止 | nginx.conf |
| 密钥管理 | `.env` 文件 + `.env.example` 模板,不提交 Git | root |
---
## 九、可扩展性设计
- **水平扩展**FastAPI 无状态 → 多实例 + Nginx 负载均衡
- **数据库读写分离**MySQL 主从复制(生产环境可配置)
- **缓存策略**Redis 缓存热点数据用户信息、Agent 配置)
- **异步任务**Celery Worker 独立扩展,处理 LLM 调用、文件处理、通知推送
- **日志聚合**ELK StackFilebeat → Elasticsearch → Kibana
- **监控告警**Prometheus + Grafana业务/系统双面板
- **CI/CD**GitHub Actionsci.yml + deploy.yml + security.yml
- **容器化部署**Docker Composedev/staging/prod 三套环境)
- **多环境管理**ENVIRONMENT 变量驱动的配置切换
---
## 十、前端架构
```
src/
├── api/ # API 调用封装axios 实例 + 拦截器)
├── components/ # 公共组件库
│ ├── chat/ # 聊天相关StreamingText, MarkdownRenderer
│ ├── workflow/ # 工作流编辑器DAG 画布、节点面板)
│ ├── charts/ # 图表组件ECharts
│ └── common/ # 通用组件(按钮、表单、弹窗)
├── composables/ # 组合式 APIuseSpeechRecognition, useTTS, usePWA
├── layouts/ # 布局组件MainLayout, AdminLayout
├── router/ # 路由配置32 个路由,全部懒加载)
├── stores/ # Pinia 状态管理
├── views/ # 页面组件28 个页面)
│ ├── MainConsole # 主控台仪表盘
│ ├── AgentDesigner # Agent 设计器
│ ├── WorkflowEditor# 工作流编辑器
│ ├── TemplateMarket# 模板市场
│ ├── AgentMarket # Agent 市场
│ ├── KnowledgeBase # 知识库管理
│ ├── Monitoring # 系统监控
│ └── ... # 更多
└── utils/ # 工具函数
```
---
> 相关文档:[项目结构概览](./project-structure.md) | [开发指南](./development-guide.md) | [API 参考](./api-reference.md) | [插件开发指南](./plugin-development-guide.md)