feat: Revamp conversation configuration management and enhance localization
- Removed outdated DEVELOPMENT.md, consolidating development instructions into relevant documentation. - Updated conversation configuration to include new parameters such as max rounds, embedding thresholds, and rewrite prompts. - Enhanced UI components to support new conversation settings, including AgentSettings.vue and related views. - Improved localization in English, Russian, and Chinese for new conversation configuration fields and UI elements. - Implemented logic to apply tenant-specific conversation settings, ensuring defaults are respected.
This commit is contained in:
-527
@@ -1,527 +0,0 @@
|
||||
# WeKnora Agent Mode 文档
|
||||
|
||||
## 概述
|
||||
|
||||
WeKnora Agent Mode 是基于 ReAct (Reasoning + Acting) 框架实现的智能代理系统,能够通过工具调用和迭代推理来回答复杂问题。
|
||||
|
||||
### 核心特性
|
||||
|
||||
- **ReAct 框架**: Thought → Action → Observation 循环
|
||||
- **工具系统**: 7个知识库相关工具
|
||||
- **可选规划**: 可在执行前生成任务计划
|
||||
- **事件追踪**: 完整的执行过程可视化
|
||||
- **灵活配置**: 支持多种参数调整
|
||||
|
||||
## 架构设计
|
||||
|
||||
### Agent 工作流程
|
||||
|
||||
```
|
||||
用户查询
|
||||
↓
|
||||
[可选] 生成执行计划
|
||||
↓
|
||||
┌─────────────────┐
|
||||
│ ReAct 循环开始 │
|
||||
├─────────────────┤
|
||||
│ 1. Think (思考) │ → LLM 分析当前状态
|
||||
│ 2. Act (行动) │ → 调用工具获取信息
|
||||
│ 3. Observe (观察)│ → 处理工具返回结果
|
||||
│ [可选] Reflect │ → 反思当前步骤
|
||||
│ 4. Decide (决策)│ → 继续或结束?
|
||||
└─────────────────┘
|
||||
↓
|
||||
生成最终答案
|
||||
```
|
||||
|
||||
### 组件结构
|
||||
|
||||
```
|
||||
internal/agent/
|
||||
├── engine.go # Agent 执行引擎
|
||||
├── prompts.go # System prompts
|
||||
└── tools/ # 工具系统
|
||||
├── tool.go
|
||||
├── registry.go
|
||||
├── knowledge_search.go
|
||||
├── multi_kb_search.go
|
||||
├── list_knowledge_bases.go
|
||||
├── get_chunk_detail.go
|
||||
├── get_related_chunks.go
|
||||
├── query_knowledge_graph.go
|
||||
└── get_document_info.go
|
||||
```
|
||||
|
||||
## 配置说明
|
||||
|
||||
### Agent 配置结构
|
||||
|
||||
```go
|
||||
type AgentConfig struct {
|
||||
Enabled bool // 是否启用 Agent 模式
|
||||
EnablePlanning bool // 是否先规划
|
||||
MaxIterations int // 最大迭代次数 (1-20)
|
||||
ReflectionEnabled bool // 是否启用反思
|
||||
AllowedTools []string // 允许的工具列表
|
||||
Temperature float64 // LLM 温度 (0-2)
|
||||
ThinkingModelID string // 推理模型 ID
|
||||
KnowledgeBases []string // 可访问的知识库 ID
|
||||
}
|
||||
```
|
||||
|
||||
### 全局配置 (config.yaml)
|
||||
|
||||
```yaml
|
||||
agent:
|
||||
enabled: true
|
||||
default_max_iterations: 5
|
||||
default_temperature: 0.7
|
||||
reflection_enabled: false
|
||||
default_tools:
|
||||
- knowledge_search
|
||||
- multi_kb_search
|
||||
- list_knowledge_bases
|
||||
- get_chunk_detail
|
||||
- get_related_chunks
|
||||
- query_knowledge_graph
|
||||
- get_document_info
|
||||
```
|
||||
|
||||
## 可用工具
|
||||
|
||||
### 1. knowledge_search
|
||||
搜索指定知识库中的相关内容。
|
||||
|
||||
**参数:**
|
||||
- `knowledge_base_id` (必需): 知识库ID
|
||||
- `query` (必需): 搜索查询内容
|
||||
- `top_k` (可选): 返回结果数量,默认5
|
||||
|
||||
**示例:**
|
||||
```
|
||||
knowledge_search(knowledge_base_id="kb123", query="什么是RAG", top_k=5)
|
||||
```
|
||||
|
||||
### 2. multi_kb_search
|
||||
在多个知识库中智能搜索,自动选择最相关的知识库。
|
||||
|
||||
**参数:**
|
||||
- `query` (必需): 搜索查询内容
|
||||
- `top_k` (可选): 每个知识库返回的结果数量,默认3
|
||||
|
||||
**适用场景:** 跨知识库查询,不确定信息在哪个知识库中
|
||||
|
||||
### 3. list_knowledge_bases
|
||||
列出当前可访问的所有知识库。
|
||||
|
||||
**参数:** 无
|
||||
|
||||
**用途:** 了解有哪些知识库可以搜索
|
||||
|
||||
### 4. get_chunk_detail
|
||||
获取指定chunk的详细信息,包括完整内容、来源文档。
|
||||
|
||||
**参数:**
|
||||
- `chunk_id` (必需): Chunk ID
|
||||
|
||||
**用途:** 当搜索结果不够详细时获取完整内容
|
||||
|
||||
### 5. get_related_chunks
|
||||
获取与指定chunk相关的其他chunks。
|
||||
|
||||
**参数:**
|
||||
- `chunk_id` (必需): Chunk ID
|
||||
- `relation_type` (可选): "sequential" (顺序) 或 "semantic" (语义)
|
||||
- `limit` (可选): 返回数量,默认5
|
||||
|
||||
**用途:** 发现相关信息,扩展上下文
|
||||
|
||||
### 6. query_knowledge_graph
|
||||
查询知识图谱中的实体和关系。
|
||||
|
||||
**参数:**
|
||||
- `knowledge_base_id` (必需): 知识库ID
|
||||
- `query` (必需): 查询内容(实体名称或查询文本)
|
||||
|
||||
**前提:** 知识库已配置知识图谱抽取
|
||||
|
||||
### 7. get_document_info
|
||||
获取文档的元数据信息。
|
||||
|
||||
**参数:**
|
||||
- `knowledge_id` (必需): 文档/知识ID
|
||||
|
||||
**用途:** 了解文档的整体情况
|
||||
|
||||
## 使用指南
|
||||
|
||||
### 创建 Agent Session
|
||||
|
||||
```bash
|
||||
POST /api/v1/sessions
|
||||
|
||||
{
|
||||
"knowledge_base_id": "kb123",
|
||||
"session_strategy": {
|
||||
"summary_model_id": "model123",
|
||||
...
|
||||
},
|
||||
"agent_config": {
|
||||
"enabled": true,
|
||||
"enable_planning": false,
|
||||
"max_iterations": 5,
|
||||
"reflection_enabled": false,
|
||||
"allowed_tools": [
|
||||
"knowledge_search",
|
||||
"multi_kb_search",
|
||||
"list_knowledge_bases"
|
||||
],
|
||||
"temperature": 0.7,
|
||||
"knowledge_bases": ["kb123", "kb456"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 发起 Agent 查询
|
||||
|
||||
```bash
|
||||
POST /api/v1/sessions/{session_id}/agent-qa
|
||||
|
||||
{
|
||||
"query": "请解释RAG技术的工作原理"
|
||||
}
|
||||
```
|
||||
|
||||
### 响应格式
|
||||
|
||||
Agent 会返回 SSE (Server-Sent Events) 流式响应:
|
||||
|
||||
1. **知识引用** (可选)
|
||||
```json
|
||||
{
|
||||
"response_type": "references",
|
||||
"knowledge_references": [...]
|
||||
}
|
||||
```
|
||||
|
||||
2. **Agent 思考过程** (可选,用于调试)
|
||||
```json
|
||||
{
|
||||
"response_type": "agent_thought",
|
||||
"content": "我需要先搜索相关知识..."
|
||||
}
|
||||
```
|
||||
|
||||
3. **工具调用** (可选)
|
||||
```json
|
||||
{
|
||||
"response_type": "agent_action",
|
||||
"content": "调用工具: knowledge_search"
|
||||
}
|
||||
```
|
||||
|
||||
4. **最终答案**
|
||||
```json
|
||||
{
|
||||
"response_type": "answer",
|
||||
"content": "RAG技术的工作原理是...",
|
||||
"done": true
|
||||
}
|
||||
```
|
||||
|
||||
## 最佳实践
|
||||
|
||||
### 1. 工具选择策略
|
||||
|
||||
- **已知知识库**: 使用 `knowledge_search`
|
||||
- **不确定位置**: 使用 `multi_kb_search`
|
||||
- **需要上下文**: 使用 `get_related_chunks`
|
||||
- **探索阶段**: 先用 `list_knowledge_bases`
|
||||
|
||||
### 2. 迭代次数设置
|
||||
|
||||
- **简单查询**: 3-5 次
|
||||
- **复杂问题**: 5-10 次
|
||||
- **探索性任务**: 10-15 次
|
||||
- **最大限制**: 20 次 (防止无限循环)
|
||||
|
||||
### 3. 温度参数
|
||||
|
||||
- **精确查询**: 0.3-0.5 (更确定性)
|
||||
- **创造性任务**: 0.7-1.0 (更多样性)
|
||||
- **默认推荐**: 0.7
|
||||
|
||||
### 4. Planning 启用时机
|
||||
|
||||
- **复杂多步骤任务**: 启用
|
||||
- **简单直接查询**: 禁用
|
||||
- **探索性问题**: 启用
|
||||
|
||||
### 5. Reflection 启用时机
|
||||
|
||||
- **关键任务**: 启用 (提高准确性)
|
||||
- **快速响应**: 禁用 (减少延迟)
|
||||
- **默认**: 禁用
|
||||
|
||||
## 工作原理详解
|
||||
|
||||
### ReAct Prompt Template
|
||||
|
||||
```
|
||||
你是一个智能知识库助手。你的任务是通过使用提供的工具来回答用户问题。
|
||||
|
||||
工作流程:
|
||||
1. 分析用户问题,确定需要什么信息
|
||||
2. 使用合适的工具获取信息(可以多次调用不同工具)
|
||||
3. 基于获取的信息,提供准确、完整的答案
|
||||
|
||||
注意事项:
|
||||
- 优先使用 multi_kb_search 进行跨知识库搜索
|
||||
- 如果需要特定知识库,先用 list_knowledge_bases 查看可用知识库
|
||||
- 如果搜索结果不够详细,使用 get_chunk_detail 获取完整内容
|
||||
- 使用 get_related_chunks 发现相关信息
|
||||
- 如果涉及实体关系,使用 query_knowledge_graph
|
||||
- 引用信息时,说明来源(chunk_id 或 knowledge_base)
|
||||
- 如果找不到相关信息,诚实告知用户
|
||||
|
||||
当前可访问的知识库:
|
||||
{knowledge_bases}
|
||||
|
||||
{plan_context}
|
||||
```
|
||||
|
||||
### 工具调用解析
|
||||
|
||||
Agent 会尝试从 LLM 输出中解析工具调用,支持的格式:
|
||||
|
||||
```
|
||||
tool_name(arg1="value1", arg2="value2")
|
||||
```
|
||||
|
||||
例如:
|
||||
```
|
||||
knowledge_search(knowledge_base_id="kb123", query="RAG技术")
|
||||
```
|
||||
|
||||
### 循环控制
|
||||
|
||||
Agent 会在以下情况停止:
|
||||
|
||||
1. LLM 输出包含 "最终答案" 或 "Final Answer"
|
||||
2. 达到最大迭代次数
|
||||
3. 工具调用失败且无法恢复
|
||||
4. 检测到重复循环模式
|
||||
|
||||
## 事件追踪
|
||||
|
||||
Agent 执行过程中会发送以下事件 (通过 Event Bus):
|
||||
|
||||
### agent.plan
|
||||
```go
|
||||
type AgentPlanData struct {
|
||||
Query string
|
||||
Plan []string
|
||||
Duration int64
|
||||
}
|
||||
```
|
||||
|
||||
### agent.step
|
||||
```go
|
||||
type AgentStepData struct {
|
||||
Iteration int
|
||||
Thought string
|
||||
ToolCalls []ToolCall
|
||||
Duration int64
|
||||
}
|
||||
```
|
||||
|
||||
### agent.tool
|
||||
```go
|
||||
type AgentActionData struct {
|
||||
Iteration int
|
||||
ToolName string
|
||||
ToolInput map[string]interface{}
|
||||
ToolOutput string
|
||||
Success bool
|
||||
Error string
|
||||
Duration int64
|
||||
}
|
||||
```
|
||||
|
||||
## 示例场景
|
||||
|
||||
### 场景 1: 简单知识查询
|
||||
|
||||
**用户问题**: "什么是 RAG?"
|
||||
|
||||
**Agent 执行流程**:
|
||||
1. **Think**: 需要搜索 RAG 相关知识
|
||||
2. **Act**: `multi_kb_search(query="RAG")`
|
||||
3. **Observe**: 获得3条相关结果
|
||||
4. **Think**: 信息足够,可以回答
|
||||
5. **Final Answer**: 基于搜索结果生成答案
|
||||
|
||||
**迭代次数**: 2
|
||||
|
||||
### 场景 2: 跨文档关联查询
|
||||
|
||||
**用户问题**: "比较 RAG 和微调的优缺点"
|
||||
|
||||
**Agent 执行流程**:
|
||||
1. **Think**: 需要分别查找 RAG 和微调的信息
|
||||
2. **Act**: `multi_kb_search(query="RAG优缺点")`
|
||||
3. **Observe**: 获得 RAG 相关信息
|
||||
4. **Think**: 还需要微调的信息
|
||||
5. **Act**: `multi_kb_search(query="模型微调优缺点")`
|
||||
6. **Observe**: 获得微调相关信息
|
||||
7. **Think**: 信息完整,进行对比
|
||||
8. **Final Answer**: 综合两者信息生成对比答案
|
||||
|
||||
**迭代次数**: 4
|
||||
|
||||
### 场景 3: 深入探索
|
||||
|
||||
**用户问题**: "详细解释向量数据库的工作原理"
|
||||
|
||||
**Agent 执行流程**:
|
||||
1. **Think**: 先查看有哪些知识库
|
||||
2. **Act**: `list_knowledge_bases()`
|
||||
3. **Observe**: 发现有"数据库技术"知识库
|
||||
4. **Think**: 在该知识库中搜索
|
||||
5. **Act**: `knowledge_search(knowledge_base_id="db_kb", query="向量数据库")`
|
||||
6. **Observe**: 找到相关 chunk
|
||||
7. **Think**: 需要更多细节
|
||||
8. **Act**: `get_chunk_detail(chunk_id="chunk123")`
|
||||
9. **Observe**: 获得完整内容
|
||||
10. **Think**: 查看相关内容
|
||||
11. **Act**: `get_related_chunks(chunk_id="chunk123", relation_type="sequential")`
|
||||
12. **Observe**: 获得上下文
|
||||
13. **Final Answer**: 基于详细信息生成深入解释
|
||||
|
||||
**迭代次数**: 7
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: Agent 和普通 RAG 有什么区别?
|
||||
|
||||
**A**:
|
||||
- **普通 RAG**: 一次性检索 → 生成答案
|
||||
- **Agent**: 可以多次迭代,根据中间结果调整策略,调用不同工具
|
||||
|
||||
### Q: 什么时候使用 Agent 模式?
|
||||
|
||||
**A**:
|
||||
- 需要多步推理的复杂问题
|
||||
- 需要在多个知识库中查找信息
|
||||
- 需要深入探索和关联分析
|
||||
- 问题模糊,需要澄清和逐步细化
|
||||
|
||||
### Q: Agent 模式的成本如何?
|
||||
|
||||
**A**:
|
||||
- **Token 消耗**: 比普通 RAG 高 (多次 LLM 调用)
|
||||
- **响应时间**: 较长 (迭代执行)
|
||||
- **准确性**: 通常更高 (多步验证)
|
||||
|
||||
### Q: 如何优化 Agent 性能?
|
||||
|
||||
**A**:
|
||||
1. 合理设置 `max_iterations` (避免过多)
|
||||
2. 选择必要的工具 (`allowed_tools`)
|
||||
3. 禁用不需要的功能 (planning, reflection)
|
||||
4. 使用更快的模型作为 thinking_model
|
||||
|
||||
### Q: 工具调用失败怎么办?
|
||||
|
||||
**A**: Agent 会:
|
||||
1. 在 Observation 中记录错误
|
||||
2. 尝试使用其他工具
|
||||
3. 如果多次失败,会在最终答案中说明
|
||||
|
||||
## 技术限制与注意事项
|
||||
|
||||
### 当前限制
|
||||
|
||||
1. **工具调用解析**: 使用简单的模式匹配,可能无法处理复杂格式
|
||||
2. **Function Calling**: 当前使用 prompt-based 方式,未来可升级为原生 function calling
|
||||
3. **并行工具调用**: 当前不支持,工具按顺序执行
|
||||
4. **图谱查询**: 当前使用 hybrid search,完整图谱功能开发中
|
||||
|
||||
### 未来改进
|
||||
|
||||
- [ ] 支持 LLM 原生 function calling (GPT-4, Claude 等)
|
||||
- [ ] 并行工具执行
|
||||
- [ ] 更智能的循环检测
|
||||
- [ ] 工具结果缓存
|
||||
- [ ] 自定义工具注册
|
||||
- [ ] Agent 执行可视化 UI
|
||||
|
||||
## 开发指南
|
||||
|
||||
### 创建自定义工具
|
||||
|
||||
```go
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
type CustomTool struct {
|
||||
BaseTool
|
||||
// 添加依赖
|
||||
}
|
||||
|
||||
func NewCustomTool() *CustomTool {
|
||||
return &CustomTool{
|
||||
BaseTool: NewBaseTool(
|
||||
"custom_tool",
|
||||
"工具描述",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
func (t *CustomTool) Parameters() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"param1": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "参数描述",
|
||||
},
|
||||
},
|
||||
"required": []string{"param1"},
|
||||
}
|
||||
}
|
||||
|
||||
func (t *CustomTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
|
||||
// 实现工具逻辑
|
||||
param1 := args["param1"].(string)
|
||||
|
||||
// 执行操作
|
||||
result := doSomething(param1)
|
||||
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: result,
|
||||
Data: map[string]interface{}{},
|
||||
}, nil
|
||||
}
|
||||
```
|
||||
|
||||
### 注册自定义工具
|
||||
|
||||
在 `agent_service.go` 的 `registerTools` 方法中添加:
|
||||
|
||||
```go
|
||||
case "custom_tool":
|
||||
registry.RegisterTool(tools.NewCustomTool())
|
||||
```
|
||||
|
||||
## 总结
|
||||
|
||||
WeKnora Agent Mode 提供了强大的迭代推理能力,适用于复杂的知识查询场景。通过合理配置和工具选择,可以在准确性和效率之间找到最佳平衡点。
|
||||
|
||||
如有问题或建议,请提交 Issue 或 Pull Request。
|
||||
|
||||
@@ -1,401 +0,0 @@
|
||||
# LLM Context Manager - 大模型上下文管理器
|
||||
|
||||
## 概述
|
||||
|
||||
LLM Context Manager 是一个专门用于管理大模型对话上下文的组件,它**独立于消息存储系统**,专注于管理发送给大模型的上下文窗口。
|
||||
|
||||
### 关键特性
|
||||
|
||||
1. **独立管理**: 与消息的数据库存储分离,专门管理发送给 LLM 的上下文
|
||||
2. **Token 限制管理**: 自动监控和管理上下文的 Token 数量
|
||||
3. **智能压缩**: 当上下文超出限制时,自动应用压缩策略
|
||||
4. **按 Session 维护**: 每个会话独立管理其上下文
|
||||
5. **灵活配置**: 支持会话级别的自定义配置
|
||||
|
||||
## 为什么需要 Context Manager?
|
||||
|
||||
### 问题背景
|
||||
|
||||
- **消息存储** vs **LLM 上下文**:
|
||||
- 消息存储:完整保存所有对话历史,用于展示和审计
|
||||
- LLM 上下文:有 Token 限制,需要精简管理
|
||||
|
||||
- **Token 限制**: 不同模型有不同的上下文窗口限制(如 4K, 8K, 16K tokens)
|
||||
|
||||
- **性能优化**: 过长的上下文会增加推理时间和成本
|
||||
|
||||
### 解决方案
|
||||
|
||||
Context Manager 提供:
|
||||
- 自动管理上下文窗口大小
|
||||
- 智能压缩历史消息
|
||||
- 保留最重要的上下文信息
|
||||
- 与消息存储解耦
|
||||
|
||||
## 架构设计
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Session Service │
|
||||
│ │
|
||||
│ ┌──────────────────┐ ┌──────────────────┐ │
|
||||
│ │ Message Repo │ │ Context Manager │ │
|
||||
│ │ (Complete │ │ (LLM Context │ │
|
||||
│ │ History) │ │ Window) │ │
|
||||
│ └──────────────────┘ └──────────────────┘ │
|
||||
│ │ │ │
|
||||
│ │ Save all messages │ Manage LLM │
|
||||
│ │ for display │ context │
|
||||
│ ▼ ▼ │
|
||||
│ ┌──────────────────┐ ┌──────────────────┐ │
|
||||
│ │ Database │ │ In-Memory │ │
|
||||
│ │ (Persistent) │ │ (Session-based) │ │
|
||||
│ └──────────────────┘ └──────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 压缩策略
|
||||
|
||||
### 1. 滑动窗口策略 (Sliding Window)
|
||||
|
||||
保留最近的 N 条消息,丢弃更早的消息。
|
||||
|
||||
**优点:**
|
||||
- 简单高效
|
||||
- 不需要额外的 LLM 调用
|
||||
- 适合短期对话
|
||||
|
||||
**配置示例:**
|
||||
```json
|
||||
{
|
||||
"enabled": true,
|
||||
"max_tokens": 8192,
|
||||
"compression_strategy": "sliding_window",
|
||||
"recent_message_count": 20
|
||||
}
|
||||
```
|
||||
|
||||
**工作原理:**
|
||||
```
|
||||
原始消息: [system, msg1, msg2, msg3, ..., msg18, msg19, msg20, msg21, msg22]
|
||||
↑
|
||||
保留最近20条消息
|
||||
压缩结果: [system, msg3, msg4, ..., msg20, msg21, msg22]
|
||||
└─────┘ └──────────────────────────────────┘
|
||||
保留系统消息 保留最近的20条消息
|
||||
```
|
||||
|
||||
### 2. 智能压缩策略 (Smart Compression)
|
||||
|
||||
使用 LLM 总结旧消息,保留最近消息的完整内容。
|
||||
|
||||
**优点:**
|
||||
- 保留历史关键信息
|
||||
- 更好的上下文连贯性
|
||||
- 适合长期对话
|
||||
|
||||
**配置示例:**
|
||||
```json
|
||||
{
|
||||
"enabled": true,
|
||||
"max_tokens": 8192,
|
||||
"compression_strategy": "smart",
|
||||
"recent_message_count": 10
|
||||
}
|
||||
```
|
||||
|
||||
**工作原理:**
|
||||
```
|
||||
原始消息: [system, msg1, msg2, ..., msg15, msg16, msg17, msg18, msg19, msg20]
|
||||
└───────────────┘ └─────────────────────────────┘
|
||||
旧消息(总结) 最近消息(保留)
|
||||
|
||||
压缩结果: [system, summary, msg16, msg17, msg18, msg19, msg20]
|
||||
└─────┘ └──────┘ └──────────────────────────────┘
|
||||
系统消息 总结 保留最近的10条消息(完整)
|
||||
```
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 1. 默认配置
|
||||
|
||||
如果不设置 `context_config`,系统使用默认配置:
|
||||
- 最大 Token: 8192
|
||||
- 策略: 滑动窗口
|
||||
- 保留消息数: 20
|
||||
|
||||
```go
|
||||
// 不需要特别配置,自动使用默认设置
|
||||
session := &types.Session{
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
// context_config 为 nil,使用默认配置
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 自定义配置 - 滑动窗口
|
||||
|
||||
```go
|
||||
session := &types.Session{
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
ContextConfig: &types.ContextConfig{
|
||||
Enabled: true,
|
||||
MaxTokens: 16384, // GPT-4 的上下文窗口
|
||||
CompressionStrategy: types.ContextCompressionSlidingWindow,
|
||||
RecentMessageCount: 30, // 保留最近30条消息
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 自定义配置 - 智能压缩
|
||||
|
||||
```go
|
||||
session := &types.Session{
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
SummaryModelID: "gpt-4", // 用于总结的模型
|
||||
ContextConfig: &types.ContextConfig{
|
||||
Enabled: true,
|
||||
MaxTokens: 8192,
|
||||
CompressionStrategy: types.ContextCompressionSmart,
|
||||
RecentMessageCount: 15, // 保留最近15条完整消息
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 通过 API 创建/更新会话
|
||||
|
||||
```bash
|
||||
# 创建带上下文配置的会话
|
||||
curl -X POST http://localhost:8080/api/v1/sessions \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-Tenant-ID: 1" \
|
||||
-d '{
|
||||
"knowledge_base_id": "kb-123",
|
||||
"context_config": {
|
||||
"enabled": true,
|
||||
"max_tokens": 8192,
|
||||
"compression_strategy": "sliding_window",
|
||||
"recent_message_count": 20
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
## 工作流程
|
||||
|
||||
### 对话流程
|
||||
|
||||
```
|
||||
1. 用户发送消息
|
||||
↓
|
||||
2. 保存消息到数据库 (Message Repo)
|
||||
↓
|
||||
3. 添加消息到上下文管理器 (Context Manager)
|
||||
↓
|
||||
4. Context Manager 检查 Token 限制
|
||||
↓
|
||||
5. 如果超出限制,应用压缩策略
|
||||
↓
|
||||
6. 获取压缩后的上下文
|
||||
↓
|
||||
7. 发送给 LLM
|
||||
↓
|
||||
8. 保存响应到数据库
|
||||
↓
|
||||
9. 添加响应到上下文管理器
|
||||
```
|
||||
|
||||
### 代码示例
|
||||
|
||||
```go
|
||||
// 在 AgentQA 中的使用
|
||||
func (s *sessionService) AgentQA(ctx context.Context, sessionID, query string, assistantMessageID string) (
|
||||
[]*types.SearchResult, <-chan types.StreamResponse, error,
|
||||
) {
|
||||
// 1. 获取会话配置
|
||||
session, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
|
||||
|
||||
// 2. 从上下文管理器获取 LLM 上下文(自动应用压缩)
|
||||
history, err := s.getContextForSession(ctx, session, sessionID)
|
||||
// history 是压缩后的,适合发送给 LLM 的消息列表
|
||||
|
||||
// 3. 执行 Agent
|
||||
eventChan, err := engine.ExecuteStreamWithHistory(ctx, query, history)
|
||||
|
||||
// 4. 保存新消息后,添加到上下文管理器
|
||||
// s.AddMessageToContext(ctx, session, sessionID, newMessage)
|
||||
|
||||
return searchResults, responseChan, nil
|
||||
}
|
||||
```
|
||||
|
||||
## 配置参数说明
|
||||
|
||||
### ContextConfig 字段
|
||||
|
||||
| 字段 | 类型 | 说明 | 默认值 |
|
||||
|------|------|------|--------|
|
||||
| `enabled` | bool | 是否启用上下文管理 | true |
|
||||
| `max_tokens` | int | 最大 Token 数 | 8192 |
|
||||
| `compression_strategy` | string | 压缩策略: "sliding_window" 或 "smart" | "sliding_window" |
|
||||
| `recent_message_count` | int | 保留的最近消息数 | 20 (sliding_window) <br> 10 (smart) |
|
||||
|
||||
### 推荐配置
|
||||
|
||||
#### 短期对话(客服、问答)
|
||||
```json
|
||||
{
|
||||
"enabled": true,
|
||||
"max_tokens": 4096,
|
||||
"compression_strategy": "sliding_window",
|
||||
"recent_message_count": 15
|
||||
}
|
||||
```
|
||||
|
||||
#### 长期对话(咨询、助手)
|
||||
```json
|
||||
{
|
||||
"enabled": true,
|
||||
"max_tokens": 8192,
|
||||
"compression_strategy": "smart",
|
||||
"recent_message_count": 10
|
||||
}
|
||||
```
|
||||
|
||||
#### 高端模型(GPT-4 Turbo, Claude)
|
||||
```json
|
||||
{
|
||||
"enabled": true,
|
||||
"max_tokens": 16384,
|
||||
"compression_strategy": "smart",
|
||||
"recent_message_count": 20
|
||||
}
|
||||
```
|
||||
|
||||
## 监控和调试
|
||||
|
||||
### 查看上下文统计
|
||||
|
||||
```go
|
||||
// 获取上下文统计信息
|
||||
stats, err := contextManager.GetContextStats(ctx, sessionID)
|
||||
if err == nil {
|
||||
log.Printf("Session %s context stats:", sessionID)
|
||||
log.Printf(" Messages: %d", stats.MessageCount)
|
||||
log.Printf(" Tokens: ~%d", stats.TokenCount)
|
||||
log.Printf(" Compressed: %v", stats.IsCompressed)
|
||||
log.Printf(" Original messages: %d", stats.OriginalMessageCount)
|
||||
}
|
||||
```
|
||||
|
||||
### 日志示例
|
||||
|
||||
```
|
||||
INFO Using custom context config for session abc123: strategy=smart, max_tokens=8192, recent_count=10
|
||||
INFO Context exceeds max tokens (9500 > 8192), applying compression
|
||||
INFO Summarizing 15 old messages
|
||||
INFO Successfully summarized 15 messages
|
||||
INFO Smart compression: 25 -> 11 messages (system: 1, compressed: 1, recent: 10)
|
||||
INFO LLM context stats for session abc123: messages=11, tokens=~7800, compressed=true
|
||||
```
|
||||
|
||||
## 与消息存储的区别
|
||||
|
||||
| 特性 | 消息存储 (Message Repo) | 上下文管理器 (Context Manager) |
|
||||
|------|------------------------|------------------------------|
|
||||
| 目的 | 完整保存对话历史 | 管理 LLM 输入上下文 |
|
||||
| 存储 | 数据库(持久化) | 内存(会话级别) |
|
||||
| 内容 | 所有消息(完整) | 压缩后的消息 |
|
||||
| 大小限制 | 无限制 | 受 Token 限制 |
|
||||
| 使用场景 | 展示历史、审计 | LLM 推理输入 |
|
||||
| 生命周期 | 永久保存 | 会话期间 |
|
||||
|
||||
## 最佳实践
|
||||
|
||||
1. **选择合适的策略**:
|
||||
- 短对话 → 滑动窗口(性能更好)
|
||||
- 长对话 → 智能压缩(保留更多上下文)
|
||||
|
||||
2. **配置 Token 限制**:
|
||||
- 设置为模型上下文窗口的 70-80%
|
||||
- 为响应留出足够空间
|
||||
|
||||
3. **调整保留消息数**:
|
||||
- 滑动窗口: 15-30 条消息
|
||||
- 智能压缩: 8-15 条最近消息
|
||||
|
||||
4. **监控压缩效果**:
|
||||
- 定期检查 Token 使用情况
|
||||
- 观察压缩是否影响对话质量
|
||||
|
||||
5. **性能考虑**:
|
||||
- 智能压缩会额外调用 LLM(有成本)
|
||||
- 滑动窗口无额外开销
|
||||
|
||||
## 数据库迁移
|
||||
|
||||
运行以下迁移脚本添加 `context_config` 字段:
|
||||
|
||||
### MySQL
|
||||
```bash
|
||||
mysql -u root -p your_database < migrations/mysql/06-add-context-config-to-sessions.sql
|
||||
```
|
||||
|
||||
### ParadeDB/PostgreSQL
|
||||
```bash
|
||||
psql -U postgres -d your_database -f migrations/paradedb/06-add-context-config-to-sessions.sql
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q1: 上下文管理器的数据会持久化吗?
|
||||
**A**: 不会。上下文管理器是内存级别的,按 Session 维护。重启后会清空,需要从消息历史重新构建。
|
||||
|
||||
### Q2: 如何清空某个会话的上下文?
|
||||
**A**:
|
||||
```go
|
||||
err := contextManager.ClearContext(ctx, sessionID)
|
||||
```
|
||||
|
||||
### Q3: 压缩后的消息会影响数据库中的消息吗?
|
||||
**A**: 不会。压缩只影响发送给 LLM 的上下文,数据库中的消息完整保留。
|
||||
|
||||
### Q4: 智能压缩的总结质量如何保证?
|
||||
**A**:
|
||||
- 使用会话配置的 `summary_model_id` 模型
|
||||
- 可以使用更强的模型(如 GPT-4)进行总结
|
||||
- 总结时使用低 temperature (0.3) 确保一致性
|
||||
|
||||
### Q5: 如何为现有会话启用上下文管理?
|
||||
**A**:
|
||||
```bash
|
||||
# 更新会话配置
|
||||
curl -X PUT http://localhost:8080/api/v1/sessions/{session_id} \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-Tenant-ID: 1" \
|
||||
-d '{
|
||||
"context_config": {
|
||||
"enabled": true,
|
||||
"max_tokens": 8192,
|
||||
"compression_strategy": "sliding_window",
|
||||
"recent_message_count": 20
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
## 未来改进
|
||||
|
||||
- [ ] 支持更多压缩策略(如 MapReduce 总结)
|
||||
- [ ] 支持自定义 Token 计算器
|
||||
- [ ] 持久化压缩后的上下文摘要
|
||||
- [ ] 支持跨会话的上下文共享
|
||||
- [ ] 添加更详细的压缩指标和监控
|
||||
- [ ] 支持上下文恢复机制
|
||||
|
||||
## 参考
|
||||
|
||||
- [Agent 文档](./AGENT.md)
|
||||
- [API 文档](./API.md)
|
||||
- [消息管理](../internal/types/message.go)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
## MCP 功能使用说明
|
||||
|
||||
### 功能概述
|
||||
- MCP(Model Context Protocol)让 WeKnora 可以安全地连接外部工具或数据源,扩展 Agent 在推理时可调用的能力。
|
||||
- 在前端 `设置 > MCP 服务`(`frontend/src/views/settings/McpSettings.vue`)中集中管理所有服务,无需手动改配置文件。
|
||||
- 每个服务都包含名称、传输方式(SSE / HTTP Streamable / Stdio)、连接地址或命令、认证信息以及高级超时与重试策略。
|
||||
|
||||
### 入口与界面
|
||||
- 打开控制台左侧菜单 `设置 -> MCP 服务`,即可看到当前租户下的所有 MCP 服务列表。
|
||||
- 列表中可快速启停服务、查看描述,并通过右侧菜单执行“测试 / 编辑 / 删除”。
|
||||
- “添加服务”按钮会弹出 `McpServiceDialog`,用于创建或修改服务。
|
||||
|
||||
### 常用操作流程
|
||||
1. **新建服务**
|
||||
- 点击“添加服务”,填写名称与描述,选择传输方式。
|
||||
- SSE / HTTP Streamable 需提供可访问的服务 URL;Stdio 需配置 `uvx`/`npx` 命令与参数,可附加环境变量。
|
||||
- 根据需要填写 API Key、Bearer Token、超时与重试策略,保存后服务会出现在列表中。
|
||||
2. **启停服务**
|
||||
- 在列表开关中切换启用状态,系统会即时调用后端 `updateMCPService`,失败时会自动回滚状态并弹出提示。
|
||||
3. **连接测试**
|
||||
- 通过更多菜单选择“测试”,前端会调用 `/api/v1/mcp-services/{id}/test` 并弹出 `McpTestResult`。
|
||||
- 成功时会展示服务可用的工具清单(含输入 schema)和资源列表;失败时会显示错误信息,方便排查网络或鉴权问题。
|
||||
4. **编辑 / 删除**
|
||||
- “编辑”会带出原有配置,修改后保存即可。
|
||||
- “删除”需要在弹窗中确认,完成后列表自动刷新。
|
||||
|
||||
### 使用建议
|
||||
- **传输方式选择**:优先使用 SSE 获取流式体验;需要标准 HTTP Streamable 兼容时再切换;本地调试或离线环境适合使用 Stdio 并在同机启动 MCP Server。
|
||||
- **鉴权管理**:将 API Key / Token 保存在“认证配置”中,生产环境建议单独创建最小权限 Key,并定期轮换。
|
||||
- **重试策略**:对公网或第三方服务适当提高 `retry_count` 与 `retry_delay`,避免间歇性超时导致 Agent 中断
|
||||
+2
-151
@@ -1,74 +1,7 @@
|
||||
# 快速开发模式说明
|
||||
|
||||
## 🎯 问题背景
|
||||
解决开发流程中,每次修改 `app`(后端)或 `frontend`(前端)代码后,都需要打包Docker镜像的问题,实现这两个模块的热更新
|
||||
|
||||
之前的开发流程中,每次修改 `app`(后端)或 `frontend`(前端)代码后,都需要:
|
||||
|
||||
```bash
|
||||
# 重新构建 Docker 镜像(耗时 2-5 分钟)
|
||||
sh scripts/build_images.sh -p # 构建后端
|
||||
sh scripts/build_images.sh -f # 构建前端
|
||||
|
||||
# 重启容器
|
||||
sh scripts/start_all.sh --no-pull
|
||||
```
|
||||
|
||||
这个流程非常耗时,严重影响开发效率。
|
||||
|
||||
## ✨ 解决方案
|
||||
|
||||
现在提供了**快速开发模式**,可以直接在本地运行应用和前端,只在 Docker 中启动基础设施服务(数据库、缓存等),实现:
|
||||
|
||||
- ✅ **前端热重载**:修改代码自动刷新,无需重启
|
||||
- ✅ **后端快速重启**:修改代码后 5-10 秒即可重启
|
||||
- ✅ **无需构建镜像**:跳过耗时的镜像构建过程
|
||||
- ✅ **支持调试**:可以使用 IDE 断点调试
|
||||
|
||||
## 📦 新增文件
|
||||
|
||||
### 1. 核心配置文件
|
||||
|
||||
- **`docker-compose.dev.yml`** - 开发环境 Docker Compose 配置
|
||||
- 只启动基础设施服务(postgres, redis, minio, neo4j, docreader, jaeger)
|
||||
- 不启动 app 和 frontend 容器
|
||||
|
||||
### 2. 开发脚本
|
||||
|
||||
- **`scripts/dev.sh`** - 开发环境管理脚本
|
||||
- 支持启动/停止基础设施
|
||||
- 支持本地运行 app 和 frontend
|
||||
- 自动检测并使用 Air(Go 热重载工具)
|
||||
|
||||
- **`scripts/quick-dev.sh`** - 一键启动开发环境脚本
|
||||
- 交互式启动所有服务
|
||||
- 自动创建日志目录
|
||||
|
||||
### 3. 配置文件
|
||||
|
||||
- **`.air.toml`** - Air 热重载配置
|
||||
- 监控 Go 文件变化
|
||||
- 自动重新编译和重启
|
||||
|
||||
- **`frontend/vite.config.ts`** - 更新的 Vite 配置
|
||||
- 添加 API 代理配置
|
||||
- 避免 CORS 问题
|
||||
|
||||
### 4. 文档
|
||||
|
||||
- **`DEVELOPMENT.md`** - 开发环境快速入门指南
|
||||
- **`docs/开发指南.md`** - 完整开发指南
|
||||
- **`docs/快速开发模式说明.md`** - 本文档
|
||||
|
||||
### 5. Makefile 更新
|
||||
|
||||
新增的 Make 命令:
|
||||
- `make dev-start` - 启动开发环境基础设施
|
||||
- `make dev-stop` - 停止开发环境
|
||||
- `make dev-restart` - 重启开发环境
|
||||
- `make dev-logs` - 查看服务日志
|
||||
- `make dev-status` - 查看服务状态
|
||||
- `make dev-app` - 启动后端应用(本地)
|
||||
- `make dev-frontend` - 启动前端(本地)
|
||||
|
||||
## 🚀 使用方法
|
||||
|
||||
@@ -104,28 +37,7 @@ make dev-frontend
|
||||
./scripts/quick-dev.sh
|
||||
```
|
||||
|
||||
## 📊 效率对比
|
||||
|
||||
### 旧方式(慢)
|
||||
|
||||
| 操作 | 耗时 |
|
||||
|------|------|
|
||||
| 修改代码 | - |
|
||||
| 重新构建镜像 | 2-5 分钟 |
|
||||
| 重启容器 | 30-60 秒 |
|
||||
| **总计** | **2.5-6 分钟** |
|
||||
|
||||
### 新方式(快)
|
||||
|
||||
| 操作 | 耗时 |
|
||||
|------|------|
|
||||
| 首次启动基础设施 | 1-2 分钟(仅一次) |
|
||||
| **后续修改后端** | **5-10 秒** |
|
||||
| **后续修改前端** | **实时热重载** |
|
||||
|
||||
**效率提升:20-60 倍!**
|
||||
|
||||
## 🎓 高级功能
|
||||
|
||||
### 使用 Air 实现后端热重载
|
||||
|
||||
@@ -142,32 +54,6 @@ export PATH=$PATH:$(go env GOPATH)/bin
|
||||
make dev-app
|
||||
```
|
||||
|
||||
### VS Code 调试配置
|
||||
|
||||
创建 `.vscode/launch.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Launch WeKnora Server",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}/cmd/server",
|
||||
"env": {
|
||||
"DB_HOST": "localhost",
|
||||
"DOCREADER_ADDR": "localhost:50051",
|
||||
"MINIO_ENDPOINT": "localhost:9000",
|
||||
"REDIS_ADDR": "localhost:6379",
|
||||
"OTEL_EXPORTER_OTLP_ENDPOINT": "localhost:4317",
|
||||
"NEO4J_URI": "bolt://localhost:7687"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## 🔄 架构说明
|
||||
|
||||
@@ -217,39 +103,4 @@ make dev-app
|
||||
│ └─────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 🎯 使用场景
|
||||
|
||||
### 日常开发
|
||||
|
||||
使用**开发模式**(`make dev-*`),享受快速迭代。
|
||||
|
||||
### 集成测试
|
||||
|
||||
使用**生产模式**(`make start-all`),测试完整环境。
|
||||
|
||||
### 生产部署
|
||||
|
||||
```bash
|
||||
# 构建镜像
|
||||
make build-images
|
||||
|
||||
# 启动服务
|
||||
make start-all
|
||||
```
|
||||
|
||||
## 🔧 故障排除
|
||||
|
||||
详见 [DEVELOPMENT.md](../DEVELOPMENT.md) 的故障排除部分。
|
||||
|
||||
## 📚 相关文档
|
||||
|
||||
- [开发环境快速入门](../DEVELOPMENT.md)
|
||||
- [完整开发指南](./开发指南.md)
|
||||
- [API 文档](./API.md)
|
||||
|
||||
## 💬 反馈与建议
|
||||
|
||||
如有问题或建议,请提交 [Issue](https://github.com/Tencent/WeKnora/issues)。
|
||||
|
||||
```
|
||||
Reference in New Issue
Block a user