229 lines
7.2 KiB
Markdown
229 lines
7.2 KiB
Markdown
# LangChain 学习平台(langchain-learning-kit)
|
||
|
||
> 目标:提供一个**企业级目录结构**和**简洁可运行**的示例系统,用来学习 LangChain 的关键功能:MySQL 配置与持久化、模型管理(可切换 LLM)、知识库管理(向量库 + 元数据)、多轮对话(会话状态)、自定义智能体(Agent)、以及常用运维/安全/测试准备。设计偏教学但架构接近生产可演示性。
|
||
|
||
------
|
||
|
||
# 一、总体概览
|
||
|
||
- 用户 → 前端/CLI → API Server (FastAPI) → 服务层:
|
||
- Auth & UserManager(MySQL)
|
||
- ModelManager(LLM 配置/版本)
|
||
- KnowledgeBaseManager(向量索引 + 文档元数据)
|
||
- ConversationManager(会话/历史)
|
||
- Agent Orchestrator(RAG + 多工具)
|
||
- Jobs / Workers(异步任务:索引、embed、清理)
|
||
- 向量存储:FAISS(本地)
|
||
- Embeddings:OpenAI
|
||
- LLM:OpenAI
|
||
- 持久化:MySQL(元数据、用户、会话索引等) + 本地磁盘或 S3(FAISS 索引快照、文档原文)
|
||
|
||
------
|
||
|
||
# 二、技术选型
|
||
|
||
- 后端框架:FastAPI
|
||
- LangChain:核心库 + langchain-community(Vectorstores)
|
||
- 向量 DB:FAISS(本地,开发)
|
||
- Embeddings/LLM:OpenAI(示例),兼容层支持自托管模型(via ModelManager)
|
||
- 异步任务:Celery / RQ(演示可用内置 asyncio)
|
||
- 数据库:MySQL(演示使用 SQLAlchemy + Alembic)
|
||
- Docker:容器化
|
||
- CI:pytest + GitHub Actions
|
||
- 配置管理:dotenv / Env vars
|
||
- 日志/监控:结构化日志(uvicorn/structlog)、Prometheus(可选)
|
||
|
||
------
|
||
|
||
# 三、关键组件说明
|
||
|
||
## 1. ModelManager(模型管理)
|
||
|
||
职责:
|
||
|
||
- 管理可用的 embedding 模型与 LLM(名称、type、endpoint、apikey、可用状态)
|
||
- 提供统一接口 `get_embedding_provider(name)` / `get_llm(name)`
|
||
- 支持“默认模型”与按请求切换模型
|
||
示例 DB 表:`models`(id, name, type (embedding|llm), config JSON, status, created_at)
|
||
|
||
## 2. KnowledgeBaseManager(知识库/向量管理)
|
||
|
||
职责:
|
||
|
||
- 管理多个知识库(kb),每个 kb 对应一套文档集合和向量索引
|
||
- 提供接口:`create_kb(name)`, `ingest_documents(kb, docs)`, `query_kb(kb, query, k)`
|
||
- 支持本地 FAISS 索引持久化:`save_local(kb)`, `load_local(kb)`
|
||
- 元数据保存在 MySQL(document 表:id, kb_id, title, source, content, embedding_id,...)
|
||
- 支持分片、版本(snapshot)
|
||
|
||
## 3. ConversationManager(多轮对话)
|
||
|
||
职责:
|
||
|
||
- 管理会话对象(session_id, user_id, messages[], metadata)
|
||
- 提供 conversation memory(短期与长期)
|
||
- 支持将检索到的片段注入 prompt(RAG)
|
||
- 支持对话转写为文档入库(长期记忆)
|
||
|
||
DB 表:`conversations` (id, user_id, title, created_at),`messages` (id, conversation_id, role, text, metadata, created_at)
|
||
|
||
## 4. Agent Orchestrator(自定义智能体)
|
||
|
||
职责:
|
||
|
||
- 将 LangChain Agent 与工具(retriever、calculator、external API)组合
|
||
- 提供 Agent 模板配置:工具集合、策略(单步/多步/chain-of-thought 开/关)
|
||
- 记录 `agent_scratchpad` 用于审计与回溯
|
||
- 提供 API 启动/停止智能体、获取工具调用日志
|
||
|
||
## 5. Jobs / Workers
|
||
|
||
职责:
|
||
|
||
- 异步嵌入计算(batch embedding)、文档分块、定期 reindex
|
||
- 可使用 Celery + Redis(或简单的线程池)实现
|
||
|
||
------
|
||
|
||
# 四、MySQL 设计(简化版 schema)
|
||
|
||
```sql
|
||
-- models: 存放模型信息(embedding/llm)
|
||
CREATE TABLE models (
|
||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||
name VARCHAR(128) NOT NULL,
|
||
type VARCHAR(32) NOT NULL, -- 'embedding' or 'llm'
|
||
config JSON NOT NULL, -- 存放 endpoint/api_key/其他配置
|
||
is_default BOOLEAN DEFAULT FALSE,
|
||
status VARCHAR(32) DEFAULT 'active',
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
);
|
||
|
||
-- knowledge bases
|
||
CREATE TABLE knowledge_bases (
|
||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||
name VARCHAR(128) UNIQUE,
|
||
description TEXT,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
);
|
||
|
||
-- documents
|
||
CREATE TABLE documents (
|
||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||
kb_id INT,
|
||
title VARCHAR(512),
|
||
content LONGTEXT,
|
||
source VARCHAR(512),
|
||
metadata JSON,
|
||
embedding_id VARCHAR(128), -- 可选 linkage 到向量存储的 id
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
FOREIGN KEY (kb_id) REFERENCES knowledge_bases(id)
|
||
);
|
||
|
||
-- conversations + messages
|
||
CREATE TABLE conversations (
|
||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||
user_id INT,
|
||
title VARCHAR(255),
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
);
|
||
CREATE TABLE messages (
|
||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||
conversation_id BIGINT,
|
||
role VARCHAR(32), -- user, assistant, system, tool
|
||
content LONGTEXT,
|
||
metadata JSON,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
FOREIGN KEY (conversation_id) REFERENCES conversations(id)
|
||
);
|
||
|
||
-- audit log for agent/tool calls
|
||
CREATE TABLE tool_calls (
|
||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||
agent_id VARCHAR(128),
|
||
tool_name VARCHAR(128),
|
||
call_input JSON,
|
||
call_output JSON,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
);
|
||
```
|
||
|
||
------
|
||
|
||
# 五、目录结构(企业级示例)
|
||
|
||
```
|
||
langchain-learning-kit/
|
||
├── docker/
|
||
│ ├── Dockerfile
|
||
│ ├── docker-compose.yml
|
||
│ └── nginx/
|
||
├── app/
|
||
│ ├── main.py # FastAPI entry
|
||
│ ├── config.py
|
||
│ ├── api/
|
||
│ │ ├── v1/
|
||
│ │ │ ├── models.py # model management endpoints
|
||
│ │ │ ├── kb.py # knowledge base endpoints
|
||
│ │ │ ├── conv.py # conversation endpoints
|
||
│ │ │ └── agent.py # agent endpoints
|
||
│ ├── services/
|
||
│ │ ├── model_manager.py
|
||
│ │ ├── kb_manager.py
|
||
│ │ ├── conv_manager.py
|
||
│ │ └── agent_orchestrator.py
|
||
│ ├── db/
|
||
│ │ ├── models.py # SQLAlchemy models
|
||
│ │ ├── session.py
|
||
│ │ └── alembic/
|
||
│ ├── embeddings/
|
||
│ │ ├── openai_provider.py
|
||
│ │ └── providers.py
|
||
│ └── utils/
|
||
│ ├── text_splitter.py
|
||
│ ├── faiss_helper.py
|
||
│ └── logger.py
|
||
├── tests/
|
||
│ ├── unit/
|
||
│ └── integration/
|
||
├── docs/
|
||
│ ├── architecture.md
|
||
│ └── runbook.md
|
||
├── scripts/
|
||
│ ├── ingest_docs.py
|
||
│ └── reindex_faiss.py
|
||
├── .env
|
||
├── requirements.txt
|
||
└── README.md
|
||
```
|
||
|
||
------
|
||
|
||
# 六、关键 API 设计
|
||
|
||
## 1. Model 管理
|
||
|
||
- `POST /api/v1/models` — 添加模型(body: name,type,config)
|
||
- `GET /api/v1/models` — 列表
|
||
- `PUT /api/v1/models/{id}` — 更新
|
||
- `DELETE /api/v1/models/{id}`
|
||
|
||
## 2. 知识库
|
||
|
||
- `POST /api/v1/kb` — 创建知识库
|
||
- `POST /api/v1/kb/{kb_id}/ingest` — 上传文档(文本/URL),触发分割+嵌入(异步)
|
||
- `POST /api/v1/kb/{kb_id}/query` — query(query, model, k)
|
||
- `GET /api/v1/kb/{kb_id}/status` — index 状态
|
||
|
||
## 3. 会话
|
||
|
||
- `POST /api/v1/conversations` — 新会话
|
||
- `POST /api/v1/conversations/{id}/messages` — 追加消息(会触发 RAG/Agent)
|
||
- `GET /api/v1/conversations/{id}` — 获取对话历史
|
||
|
||
## 4. Agent
|
||
|
||
- `POST /api/v1/agent/run` — {agent_name, input, model?}
|
||
- `GET /api/v1/agent/logs/{run_id}`
|
||
|