Files
ailine/backend/app/README.md
root ad345e635d
Some checks failed
构建并部署 AI Agent 服务 / deploy (push) Failing after 6m9s
docs: 更新 backend/app/README.md,按模块整理已实现功能
2026-04-26 12:09:37 +08:00

357 lines
11 KiB
Markdown
Raw Permalink 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.

# 后端模块 (backend/app/)
这是一个基于 LangGraph 的个人助手系统提供对话、工具调用、记忆管理、RAG 检索和子图功能。
---
## 📂 目录结构
```
backend/app/
├── agent/ # Agent 服务层
│ ├── service.py # AIAgentService - 主服务类
│ ├── rag_initializer.py # RAG 工具初始化
│ ├── history.py # 对话历史管理
│ └── prompts.py # 提示词模板
├── agent_subgraphs/ # 子图模块 ✅ 已实现
│ ├── common/ # 公共工具
│ │ ├── state_base.py # 状态基类
│ │ ├── intent.py # 意图理解React 模式)
│ │ ├── formatter.py # 格式化输出工具
│ │ └── human_review.py # 人工审核节点
│ ├── contact/ # 通讯录子图
│ ├── dictionary/ # 词典子图
│ ├── news_analysis/ # 资讯分析子图
│ ├── research/ # 研究分析子图(规划中)
│ └── README.md
├── graph/ # LangGraph 主图构建
│ ├── graph_builder.py # 图构建器
│ ├── graph_tools.py # 工具定义
│ ├── state.py # 状态定义
│ ├── retrieve_memory.py # 记忆检索节点
│ ├── rag_nodes.py # RAG 集成节点
│ └── visualize_graph.py # 图可视化
├── memory/ # 记忆模块
│ └── mem0_client.py # Mem0 客户端
├── model_services/ # 模型服务层 ✅ 已重构
│ ├── __init__.py
│ ├── base.py # 基类和降级机制
│ ├── chat_services.py # 生成式大模型服务
│ ├── embedding_services.py # 嵌入服务
│ └── rerank_services.py # 重排服务
├── nodes/ # LangGraph 节点实现
│ ├── llm_call.py # LLM 调用节点
│ ├── tool_call.py # 工具调用节点
│ ├── router.py # 路由节点
│ ├── summarize.py # 摘要节点
│ ├── finalize.py # 最终节点
│ └── memory_trigger.py # 记忆触发节点
├── rag/ # RAG 检索模块 ✅ 已重构
│ ├── pipeline.py # RAG 流水线
│ ├── tools.py # RAG 工具
│ ├── rerank.py # 重排业务逻辑
│ ├── retriever.py # 检索器
│ ├── query_transform.py # 查询转换
│ └── fusion.py # 结果融合
├── utils/ # 工具函数
├── __init__.py
├── backend.py # FastAPI 后端入口
├── config.py # 配置管理
└── logger.py # 日志模块
```
---
## ✅ 已实现功能
### 1. Agent 服务 (agent/)
- **AIAgentService** - 主服务类
- 接收外部 checkpointer管理图生命周期
- 支持多模型动态切换
- 提供流式和非流式接口
- **多模型支持** - 通过 chat_services
- 智谱 AI (glm-4.7-flash)
- DeepSeek (deepseek-reasoner)
- 本地模型 (vLLM/llama.cpp)
- **对话历史** - 基于 LangGraph 状态持久化
### 2. LangGraph 主图 (graph/)
- **GraphBuilder** - 图构建器
- 模块化节点创建,依赖注入
- 支持 Mem0 客户端集成
- **状态管理**
- MessagesState - 对话状态消息、token、时间、摘要轮数
- GraphContext - 执行上下文(用户 ID
- **工具定义**
- get_current_temperature - 示例温度工具
- read_local_file - 读取本地文件
- read_pdf_summary - 读取 PDF
- read_excel_as_markdown - 读取 Excel
- fetch_webpage_content - 抓取网页
- **React 模式** - 循环推理 + 超时重试 + 结构化错误处理
### 3. 节点实现 (nodes/)
- **llm_call** - LLM 调用节点
- **tool_call** - 工具调用节点
- **router** - 路由节点should_continue
- **summarize** - 记忆摘要节点
- **finalize** - 最终响应节点
- **memory_trigger** - 记忆触发节点
### 4. 记忆管理 (memory/)
- **Mem0Client** - Mem0 记忆客户端
- 异步初始化和连接测试
- 支持记忆检索和添加
- 可集成到 LangGraph 中
### 5. 模型服务层 (model_services/)
架构:纯服务层 + 业务逻辑分离
#### 5.1 基类与公共机制 (base.py)
- **BaseServiceProvider** - 服务提供者基类
- 统一接口is_available() 和 get_service()
- **FallbackServiceChain** - 链式降级机制
- 优先尝试主服务,失败自动尝试备用服务
- **SingletonServiceManager** - 单例管理器
- 全局单例,避免重复创建
#### 5.2 生成式大模型 (chat_services.py)
- **LocalVLLMChatProvider** - 本地 VLLM 服务gemma-4-E4B-it
- **ZhipuChatProvider** - 智谱 AI 服务glm-4.7-flash
- **DeepSeekChatProvider** - DeepSeek 服务deepseek-reasoner
- **get_chat_service()** - 默认服务(自动降级)
- **get_all_chat_services()** - 获取所有可用模型
#### 5.3 嵌入服务 (embedding_services.py)
- **LocalLlamaCppEmbeddingProvider** - 本地 llama.cpp 嵌入
- **ZhipuEmbeddingProvider** - 智谱 AI 嵌入
- **get_embedding_service()** - 统一接口,自动降级
#### 5.4 重排服务 (rerank_services.py)
- **LocalLlamaCppRerankProvider** - 本地 llama.cpp 重排
- **ZhipuRerankProvider** - 智谱 AI 重排
- **get_rerank_service()** - 统一接口,自动降级
### 6. RAG 检索模块 (rag/)
架构:业务逻辑层 + 服务层分离
- **RAGPipeline** - RAG 流水线
- 查询改写 → 并行检索 → RRF 融合 → 重排 → 返回结果
- **DocumentReranker** - 重排业务逻辑rag/rerank.py
- **ParentDocumentRetriever** - 父文档检索器
- **查询转换** - MultiQueryGenerator
- **结果融合** - Reciprocal Rank Fusion
### 7. 子图模块 (agent_subgraphs/) ✅ 已实现
#### 7.1 公共工具 (common/)
- **state_base.py** - TypedDict 类型安全的状态基类
- **intent.py** - 意图理解React 模式)- 是否调用 RAG、是否重新检索
- **formatter.py** - 格式化输出工具Jinja2 + Markdown
- **human_review.py** - 人工审核节点LangGraph interrupt
#### 7.2 通讯录子图 (contact/)
- 联系人管理CRUD
- 邮件读取与审核
- 外发邮件
- 智能嗅探
- API 客户端
- 精美格式化展示
#### 7.3 词典子图 (dictionary/)
- 翻译、查词
- 每日一词
- 专业名词提炼
- 生词本管理
- API 客户端
- 精美格式化展示
#### 7.4 资讯分析子图 (news_analysis/)
- 资讯获取
- 内容分析
- API 客户端
- 精美格式化展示
#### 7.5 研究分析子图 (research/)
- 规划中
### 8. FastAPI 后端 (backend.py)
- POST /chat - 非流式对话
- POST /chat/stream - 流式对话
- 子图 API 端点
- 人工审核交互端点(确定/取消/继续)
### 9. 配置管理 (config.py)
- 集中管理环境变量
- 智谱 AI 配置
- ZHIPUAI_API_KEY
- ZHIPU_EMBEDDING_MODEL默认 embedding-3
- ZHIPU_RERANK_MODEL默认 rerank-2
- ZHIPU_API_BASE
- DeepSeek 配置
- DEEPSEEK_API_KEY
- 本地模型配置
- VLLM_BASE_URL主 LLM
- LLAMACPP_EMBEDDING_URL嵌入
- LLAMACPP_RERANKER_URL重排
- LLM_API_KEY / LLAMACPP_API_KEY
- 数据库和 Qdrant 配置
---
## 🚧 待完善功能
### 1. 子图模块
- **research/** - 研究分析子图(联网搜索、报告生成、引用溯源、可视化)
### 2. 其他
- 更完善的错误处理和日志
- 监控和指标收集
- API 文档完善OpenAPI/Swagger
- 单元测试和集成测试
---
## 🛠️ 技术栈
| 层级 | 组件 | 技术选型 |
|------|------|---------|
| Agent 框架 | 工作流编排 | LangGraph + LangChain |
| LLM 服务 | 模型调用 | 智谱 AI / DeepSeek / 本地模型 (llama.cpp/vLLM) |
| Embedding | 向量嵌入 | 本地 llama.cpp / 智谱 AI |
| Rerank | 重排序 | 本地 llama.cpp / 智谱 AI |
| 向量数据库 | 语义检索 | Qdrant |
| 关系数据库 | 结构化存储 | PostgreSQL |
| 后端框架 | API 服务 | FastAPI + Uvicorn |
| 记忆服务 | 长期记忆 | Mem0 |
---
## 📝 使用指南
### 快速开始
1. **配置环境变量**
复制 `.env` 文件并配置:
- 数据库配置PostgreSQL
- Qdrant 配置
- LLM 配置(智谱/DeepSeek/本地)
- 嵌入和重排服务配置
2. **启动后端**
```bash
cd backend
python -m app.backend
```
3. **API 接口**
- POST /chat - 非流式对话
- POST /chat/stream - 流式对话
### 配置说明
#### 必需配置
```env
# 数据库
DB_HOST=your_db_host
DB_PORT=5432
DB_USER=your_db_user
DB_PASSWORD=***
DB_NAME=langgraph_db
# Qdrant
QDRANT_URL=http://your_qdrant_host:6333
QDRANT_API_KEY=your_qdrant_api_key
# 至少配置一个 LLM
ZHIPUAI_API_KEY=***
DEEPSEEK_API_KEY=***
```
#### 可选配置
```env
# 本地模型服务
VLLM_BASE_URL=http://localhost:8000/v1
LLAMACPP_EMBEDDING_URL=http://localhost:8001/v1
LLAMACPP_RERANKER_URL=http://localhost:8002/v1
LLM_API_KEY=***
LLAMACPP_API_KEY=***
# 智谱其他配置
ZHIPU_EMBEDDING_MODEL=embedding-3
ZHIPU_RERANK_MODEL=rerank-2
```
### 使用模型服务
#### 生成式大模型
```python
from app.model_services import get_chat_service, get_all_chat_services
# 自动选择可用服务(优先本地,降级智谱,再降级 DeepSeek
llm = get_chat_service()
# 获取所有可用模型(用于多模型切换)
all_llms = get_all_chat_services() # Dict[str, BaseChatModel]
```
#### 嵌入服务
```python
from app.model_services import get_embedding_service
# 自动选择可用服务(优先本地,降级智谱)
embeddings = get_embedding_service()
# 使用
vector = embeddings.embed_query("hello")
```
#### 重排服务
```python
from app.model_services import get_rerank_service
from app.rag.rerank import create_document_reranker
# 获取原始重排服务(仅计算分数)
rerank_service = get_rerank_service()
scores = rerank_service.compute_scores("query", ["doc1", "doc2"])
# 使用业务逻辑层(完整的文档重排)
reranker = create_document_reranker()
sorted_docs = reranker.compress_documents(docs, "query", top_n=5)
```
---
## 📁 架构说明
### 模型服务层架构
```
model_services/
├── base.py # 基类BaseServiceProvider, FallbackServiceChain, SingletonServiceManager
├── chat_services.py # 生成式大模型(纯服务层)
├── embedding_services.py # 嵌入服务(纯服务层)
└── rerank_services.py # 重排服务(纯服务层)
业务逻辑层
├── rag/rerank.py # 重排业务逻辑(使用 model_services
└── agent/service.py # Agent 服务(使用 model_services
```
### 子图架构
```
agent_subgraphs/
├── common/ # 公共工具(所有子图共享)
│ ├── state_base.py # 状态基类
│ ├── intent.py # 意图理解
│ ├── formatter.py # 格式化输出
│ └── human_review.py # 人工审核
├── contact/ # 每个子图独立目录
│ ├── state.py # 状态定义
│ ├── nodes.py # 节点实现
│ ├── graph.py # 图构建
│ ├── api_client.py # API 客户端
│ └── __init__.py
└── dictionary/
└── (同 contact)
```