diff --git a/Cargo.toml b/Cargo.toml index e6b4761..f063cfa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vectorless" -version = "0.1.14" +version = "0.1.15" edition = "2024" authors = ["zTgx "] description = "Hierarchical, reasoning-native document intelligence engine" diff --git a/docs/design/feedback-learning.md b/docs/design/feedback-learning.md index 9b79bc3..3bb9007 100644 --- a/docs/design/feedback-learning.md +++ b/docs/design/feedback-learning.md @@ -1,37 +1,40 @@ -# Feedback Learning 设计文档 +# Feedback Learning Design Document -> Pilot 反馈学习系统 - 从用户反馈中持续改进决策 +> Pilot Feedback Learning System - Continuously improving decisions from user feedback -## 概述 +## Overview -Feedback Learning 是 Pilot 的学习子系统,通过收集用户对检索结果的反馈,持续优化 Pilot 的决策能力。系统会追踪不同场景下的决策准确性,并据此调整后续决策的置信度和策略。 +Feedback Learning is Pilot's learning subsystem that continuously optimizes Pilot's decision-making capabilities by collecting user feedback on retrieval results. The system tracks decision accuracy across different scenarios and adjusts confidence levels and strategies for subsequent decisions accordingly. -### 设计目标 +### Design Goals ``` ┌─────────────────────────────────────────────────────────────────┐ -│ 设计目标 │ +│ Design Goals │ ├─────────────────────────────────────────────────────────────────┤ -│ 1. 收集反馈 - 记录用户对检索结果的评价 │ -│ 2. 学习模式 - 识别在哪些场景下 Pilot 表现好/差 │ -│ 3. 调整决策 - 根据历史表现调整置信度和策略 │ -│ 4. 持续改进 - 随着数据积累,决策质量逐步提升 │ +│ 1. Collect Feedback - Record user ratings on retrieval results │ +│ 2. Learn Patterns - Identify scenarios where Pilot performs │ +│ well or poorly │ +│ 3. Adjust Decisions - Modify confidence and strategies based │ +│ on historical performance │ +│ 4. Continuous Improvement - Decision quality improves over time │ +│ as data accumulates │ └─────────────────────────────────────────────────────────────────┘ ``` --- -## 1. 整体架构 +## 1. Overall Architecture ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Feedback Learning 系统架构 │ +│ Feedback Learning System Architecture │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌───────────────────────────────────────────────────────────────────────┐ │ -│ │ 数据流 │ │ +│ │ Data Flow │ │ │ │ │ │ -│ │ 检索完成 │ │ +│ │ Retrieval Complete │ │ │ │ │ │ │ │ │ ▼ │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ @@ -46,7 +49,7 @@ Feedback Learning 是 Pilot 的学习子系统,通过收集用户对检索结 │ │ └─────────────┘ │ │ │ │ │ │ │ │ │ ▼ │ │ -│ │ 下次检索决策 │ │ +│ │ Next Retrieval Decision │ │ │ │ │ │ │ └───────────────────────────────────────────────────────────────────────┘ │ │ │ @@ -55,39 +58,39 @@ Feedback Learning 是 Pilot 的学习子系统,通过收集用户对检索结 --- -## 2. 核心组件 +## 2. Core Components -### 2.1 FeedbackRecord - 反馈记录 +### 2.1 FeedbackRecord - Feedback Record ```rust -/// 反馈记录 +/// Feedback record pub struct FeedbackRecord { - /// 唯一反馈 ID + /// Unique feedback ID pub id: FeedbackId, - /// 关联的决策 ID + /// Associated decision ID pub decision_id: DecisionId, - /// 决策是否正确 + /// Whether the decision was correct pub was_correct: bool, - /// Pilot 当时的置信度 + /// Pilot's confidence at that time pub pilot_confidence: f64, - /// 介入点类型 + /// Intervention point type pub intervention_point: InterventionPoint, - /// 查询哈希(用于聚合相似查询) + /// Query hash (for aggregating similar queries) pub query_hash: u64, - /// 路径哈希(用于聚合相似路径) + /// Path hash (for aggregating similar paths) pub path_hash: u64, - /// 时间戳 + /// Timestamp pub timestamp_ms: u64, - /// 可选的用户评论 + /// Optional user comment pub comment: Option, } ``` -### 2.2 FeedbackStore - 反馈存储 +### 2.2 FeedbackStore - Feedback Storage ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ FeedbackStore 架构 │ +│ FeedbackStore Architecture │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ @@ -107,50 +110,50 @@ pub struct FeedbackRecord { │ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ 统计维度: │ +│ Statistics Dimensions: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 1. 按 InterventionPoint 聚合 │ │ -│ │ - START / FORK / BACKTRACK / EVALUATE 各自的准确率 │ │ +│ │ 1. Aggregate by InterventionPoint │ │ +│ │ - Accuracy for each: START / FORK / BACKTRACK / EVALUATE │ │ │ │ │ │ -│ │ 2. 按 Query 聚合 │ │ -│ │ - 相似查询的历史表现 │ │ +│ │ 2. Aggregate by Query │ │ +│ │ - Historical performance for similar queries │ │ │ │ │ │ -│ │ 3. 按 Path 聚合 │ │ -│ │ - 相似路径的历史表现 │ │ +│ │ 3. Aggregate by Path │ │ +│ │ - Historical performance for similar paths │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` -### 2.3 PilotLearner - 学习器 +### 2.3 PilotLearner - Learner ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ PilotLearner 工作原理 │ +│ PilotLearner Workflow │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ 输入: │ +│ Input: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ - intervention_point: 当前介入点类型 │ │ -│ │ - query_hash: 查询的哈希值 │ │ -│ │ - path_hash: 路径的哈希值 │ │ +│ │ - intervention_point: Current intervention point type │ │ +│ │ - query_hash: Hash value of the query │ │ +│ │ - path_hash: Hash value of the path │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ 查询历史统计: │ +│ Query Historical Statistics: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 1. 获取 intervention_point 的整体准确率 │ │ -│ │ 2. 获取 query_hash 的特定准确率(如有) │ │ -│ │ 3. 获取 path_hash 的特定准确率(如有) │ │ +│ │ 1. Get overall accuracy for intervention_point │ │ +│ │ 2. Get specific accuracy for query_hash (if available) │ │ +│ │ 3. Get specific accuracy for path_hash (if available) │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ 输出 DecisionAdjustment: │ +│ Output DecisionAdjustment: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ pub struct DecisionAdjustment { │ │ -│ │ /// 置信度调整(加到 Pilot 置信度上) │ │ +│ │ /// Confidence adjustment (added to Pilot confidence) │ │ │ │ pub confidence_delta: f64, │ │ -│ │ /// 是否跳过介入(信任算法) │ │ +│ │ /// Whether to skip intervention (trust algorithm) │ │ │ │ pub skip_intervention: bool, │ │ -│ │ /// 算法权重 vs LLM 权重 │ │ +│ │ /// Algorithm weight vs LLM weight │ │ │ │ pub algorithm_weight: f64, │ │ │ │ } │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ @@ -160,42 +163,42 @@ pub struct FeedbackRecord { --- -## 3. 学习策略 +## 3. Learning Strategies -### 3.1 准确率阈值 +### 3.1 Accuracy Thresholds ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ 准确率阈值策略 │ +│ Accuracy Threshold Strategy │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ 配置参数: │ +│ Configuration Parameters: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ min_samples: 10 // 最小样本数才开始调整 │ │ -│ │ high_accuracy_threshold: 0.8 // 高准确率阈值 │ │ -│ │ low_accuracy_threshold: 0.5 // 低准确率阈值 │ │ -│ │ max_confidence_delta: 0.2 // 最大置信度调整幅度 │ │ +│ │ min_samples: 10 // Minimum samples before adjusting │ │ +│ │ high_accuracy_threshold: 0.8 // High accuracy threshold │ │ +│ │ low_accuracy_threshold: 0.5 // Low accuracy threshold │ │ +│ │ max_confidence_delta: 0.2 // Maximum confidence adjustment │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ 决策逻辑: │ +│ Decision Logic: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ │ │ if accuracy >= high_accuracy_threshold (0.8): │ │ -│ │ // 高准确率:信任 LLM,提升置信度 │ │ +│ │ // High accuracy: trust LLM, boost confidence │ │ │ │ confidence_delta = +0.2 │ │ -│ │ algorithm_weight = 0.3 // 更依赖 LLM │ │ +│ │ algorithm_weight = 0.3 // More reliance on LLM │ │ │ │ │ │ │ │ elif accuracy <= low_accuracy_threshold (0.5): │ │ -│ │ // 低准确率:信任算法,降低置信度 │ │ +│ │ // Low accuracy: trust algorithm, reduce confidence │ │ │ │ confidence_delta = -0.2 │ │ -│ │ algorithm_weight = 0.7 // 更依赖算法 │ │ +│ │ algorithm_weight = 0.7 // More reliance on algorithm │ │ │ │ │ │ │ │ if accuracy < 0.3: │ │ -│ │ // 非常低:跳过 LLM 调用,完全用算法 │ │ +│ │ // Very low: skip LLM call, use algorithm only │ │ │ │ skip_intervention = true │ │ │ │ │ │ │ │ else: │ │ -│ │ // 中等准确率:保持默认 │ │ +│ │ // Medium accuracy: keep defaults │ │ │ │ confidence_delta = 0.0 │ │ │ │ algorithm_weight = 0.5 │ │ │ │ │ │ @@ -204,46 +207,46 @@ pub struct FeedbackRecord { └─────────────────────────────────────────────────────────────────────────────┘ ``` -### 3.2 多层统计融合 +### 3.2 Multi-Layer Statistics Fusion ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ 多层统计融合策略 │ +│ Multi-Layer Statistics Fusion │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ 三层统计: │ +│ Three-Layer Statistics: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ -│ │ Layer 1: InterventionPoint 级别(粗粒度) │ │ +│ │ Layer 1: InterventionPoint Level (Coarse-grained) │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ -│ │ │ 例如: FORK 点整体准确率 = 0.75 │ │ │ -│ │ │ 影响: 基础调整 │ │ │ +│ │ │ Example: FORK point overall accuracy = 0.75 │ │ │ +│ │ │ Impact: Base adjustment │ │ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ -│ │ Layer 2: Query 级别(中粒度) │ │ +│ │ Layer 2: Query Level (Medium-grained) │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ -│ │ │ 例如: 相似查询的准确率 = 0.85 │ │ │ -│ │ │ 影响: 如果高于整体,额外 +0.05 置信度 │ │ │ +│ │ │ Example: Similar query accuracy = 0.85 │ │ │ +│ │ │ Impact: If higher than overall, +0.05 confidence │ │ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ -│ │ Layer 3: Path 级别(细粒度) │ │ +│ │ Layer 3: Path Level (Fine-grained) │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ -│ │ │ 例如: 相似路径的准确率 = 0.92 │ │ │ -│ │ │ 影响: 如果非常高,额外 +0.05 置信度 │ │ │ +│ │ │ Example: Similar path accuracy = 0.92 │ │ │ +│ │ │ Impact: If very high, +0.05 confidence │ │ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ 融合示例: │ +│ Fusion Example: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ -│ │ 场景: FORK 点,相似查询,相似路径 │ │ +│ │ Scenario: FORK point, similar query, similar path │ │ │ │ │ │ -│ │ 1. FORK 整体准确率 0.75 → confidence_delta = +0.1 │ │ -│ │ 2. 查询特定准确率 0.85 > 0.75 → confidence_delta += 0.05 │ │ -│ │ 3. 路径特定准确率 0.92 > 0.9 → confidence_delta += 0.05 │ │ +│ │ 1. FORK overall accuracy 0.75 → confidence_delta = +0.1 │ │ +│ │ 2. Query-specific accuracy 0.85 > 0.75 → confidence_delta += 0.05 │ │ +│ │ 3. Path-specific accuracy 0.92 > 0.9 → confidence_delta += 0.05 │ │ │ │ │ │ -│ │ 最终: confidence_delta = +0.2 (达到上限) │ │ +│ │ Final: confidence_delta = +0.2 (reached maximum) │ │ │ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ @@ -252,16 +255,16 @@ pub struct FeedbackRecord { --- -## 4. 与 LlmPilot 的集成 +## 4. Integration with LlmPilot -### 4.1 集成点 +### 4.1 Integration Points ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ LlmPilot 与 Learner 集成 │ +│ LlmPilot and Learner Integration │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ LlmPilot 结构: │ +│ LlmPilot Structure: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ pub struct LlmPilot { │ │ │ │ client: LlmClient, │ │ @@ -271,23 +274,23 @@ pub struct FeedbackRecord { │ │ context_builder: ContextBuilder, │ │ │ │ prompt_builder: PromptBuilder, │ │ │ │ response_parser: ResponseParser, │ │ -│ │ learner: Option>, // ← 反馈学习器 │ │ +│ │ learner: Option>, // ← Feedback learner │ │ │ │ } │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ 关键方法: │ +│ Key Methods: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ -│ │ // 添加学习器 │ │ +│ │ // Add learner │ │ │ │ pub fn with_learner(self, learner: Arc) -> Self │ │ │ │ │ │ -│ │ // 从反馈存储创建学习器 │ │ +│ │ // Create learner from feedback store │ │ │ │ pub fn with_feedback_store(self, store: Arc) -> Self│ │ │ │ │ │ -│ │ // 记录反馈 │ │ +│ │ // Record feedback │ │ │ │ pub fn record_feedback(&self, record: FeedbackRecord) │ │ │ │ │ │ -│ │ // 获取学习器(只读) │ │ +│ │ // Get learner (read-only) │ │ │ │ pub fn learner(&self) -> Option<&PilotLearner> │ │ │ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ @@ -295,11 +298,11 @@ pub struct FeedbackRecord { └─────────────────────────────────────────────────────────────────────────────┘ ``` -### 4.2 决策流程 +### 4.2 Decision Flow ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ 带学习的决策流程 │ +│ Decision Flow with Learning │ └─────────────────────────────────────────────────────────────────────────────┘ ┌─────────────────┐ @@ -308,7 +311,7 @@ pub struct FeedbackRecord { │ ▼ ┌──────────────────────────────┐ - │ 1. 构建上下文 (ContextBuilder) │ + │ 1. Build Context (Builder) │ │ - query_section │ │ - path_section │ │ - candidates_section │ @@ -316,7 +319,7 @@ pub struct FeedbackRecord { │ ▼ ┌──────────────────────────────┐ - │ 2. 获取学习器调整 │ + │ 2. Get Learner Adjustment │ │ if learner.is_some() { │ │ query_hash = ctx.hash() │ │ path_hash = ctx.hash() │ @@ -331,7 +334,7 @@ pub struct FeedbackRecord { │ ▼ ┌──────────────────────────────┐ - │ 3. 检查是否跳过介入 │ + │ 3. Check Skip Intervention │ │ if adjustment.skip { │ │ return default_decision │ │ } │ @@ -339,13 +342,13 @@ pub struct FeedbackRecord { │ ▼ ┌──────────────────────────────┐ - │ 4. 调用 LLM 获取决策 │ + │ 4. Call LLM for Decision │ │ decision = llm.complete() │ └──────────────┬───────────────┘ │ ▼ ┌──────────────────────────────┐ - │ 5. 应用学习器调整 │ + │ 5. Apply Learner Adjustment │ │ decision.confidence += │ │ adjustment.confidence │ │ .delta │ @@ -353,15 +356,16 @@ pub struct FeedbackRecord { │ ▼ ┌─────────────────┐ - │ 返回调整后决策 │ + │ Return Adjusted │ + │ Decision │ └─────────────────┘ ``` --- -## 5. 使用示例 +## 5. Usage Examples -### 5.1 基本使用 +### 5.1 Basic Usage ```rust use std::sync::Arc; @@ -371,21 +375,21 @@ use vectorless::retrieval::pilot::{ }; use vectorless::llm::LlmClient; -// 1. 创建反馈存储 +// 1. Create feedback store let store = Arc::new(FeedbackStore::in_memory()); -// 2. 创建带学习器的 Pilot +// 2. Create Pilot with learner let client = LlmClient::for_model("gpt-4o-mini"); let pilot = LlmPilot::new(client, PilotConfig::default()) .with_feedback_store(store.clone()); -// 3. 执行检索(Pilot 会自动应用学习调整) +// 3. Execute retrieval (Pilot automatically applies learning adjustments) let decision = pilot.decide(&state).await; -// 4. 记录用户反馈 +// 4. Record user feedback let record = FeedbackRecord::new( decision_id, - was_correct, // 用户评价 + was_correct, // User rating decision.confidence as f64, InterventionPoint::Fork, query_hash, @@ -393,38 +397,38 @@ let record = FeedbackRecord::new( ); pilot.record_feedback(record); -// 5. 后续检索会自动利用历史反馈改进决策 +// 5. Subsequent retrievals automatically leverage historical feedback ``` -### 5.2 持久化反馈 +### 5.2 Persisting Feedback ```rust use vectorless::retrieval::pilot::feedback::FeedbackStoreConfig; -// 创建带持久化的反馈存储 +// Create feedback store with persistence let config = FeedbackStoreConfig::with_persistence("./data/feedback.json"); let store = Arc::new(FeedbackStore::new(config)); -// 启动时加载历史反馈 +// Load historical feedback at startup store.load()?; -// 定期保存 +// Persist periodically store.persist()?; ``` -### 5.3 查看学习效果 +### 5.3 Viewing Learning Effects ```rust -// 获取整体准确率 +// Get overall accuracy let accuracy = learner.overall_accuracy(); println!("Overall accuracy: {:.2}%", accuracy * 100.0); -// 获取各介入点的统计 +// Get statistics by intervention point let stats = store.intervention_stats(); println!("Fork accuracy: {:.2}%", stats.fork.accuracy() * 100.0); println!("Start accuracy: {:.2}%", stats.start.accuracy() * 100.0); -// 检查是否有足够数据 +// Check if sufficient data exists if learner.has_sufficient_data() { println!("Learner has sufficient data for adjustments"); } @@ -432,28 +436,28 @@ if learner.has_sufficient_data() { --- -## 6. 配置选项 +## 6. Configuration Options ```rust -/// 反馈存储配置 +/// Feedback store configuration pub struct FeedbackStoreConfig { - /// 最大记录数(内存限制) + /// Maximum number of records (memory limit) pub max_records: usize, - /// 是否持久化 + /// Whether to persist pub persist: bool, - /// 持久化路径 + /// Persistence path pub storage_path: Option, } -/// 学习器配置 +/// Learner configuration pub struct LearnerConfig { - /// 最小样本数(少于此数不调整) + /// Minimum samples (no adjustment below this) pub min_samples: u64, - /// 高准确率阈值 + /// High accuracy threshold pub high_accuracy_threshold: f64, - /// 低准确率阈值 + /// Low accuracy threshold pub low_accuracy_threshold: f64, - /// 最大置信度调整幅度 + /// Maximum confidence adjustment pub max_confidence_delta: f64, } @@ -471,13 +475,13 @@ impl Default for LearnerConfig { --- -## 7. 实现细节 +## 7. Implementation Details -### 7.1 哈希计算 +### 7.1 Hash Calculation ```rust impl PilotContext { - /// 计算查询哈希(用于聚合相似查询) + /// Calculate query hash (for aggregating similar queries) pub fn query_hash(&self) -> u64 { use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; @@ -486,7 +490,7 @@ impl PilotContext { hasher.finish() } - /// 计算路径哈希(用于聚合相似路径) + /// Calculate path hash (for aggregating similar paths) pub fn path_hash(&self) -> u64 { use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; @@ -497,11 +501,11 @@ impl PilotContext { } ``` -### 7.2 统计计算 +### 7.2 Statistics Calculation ```rust impl ContextStats { - /// 计算准确率 + /// Calculate accuracy pub fn accuracy(&self) -> f64 { if self.total == 0 { 0.0 @@ -510,12 +514,12 @@ impl ContextStats { } } - /// 记录新反馈(增量更新) + /// Record new feedback (incremental update) fn record(&mut self, was_correct: bool, confidence: f64) { self.total += 1; if was_correct { self.correct += 1; - // 增量更新平均置信度 + // Incremental update of average confidence self.avg_confidence_correct = (self.avg_confidence_correct * (self.correct - 1) as f64 + confidence) / self.correct as f64; @@ -531,37 +535,39 @@ impl ContextStats { --- -## 8. 未来扩展 +## 8. Future Extensions -### 8.1 可能的改进方向 +### 8.1 Potential Improvements ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ 未来扩展方向 │ +│ Future Extension Directions │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ 1. 语义相似度聚合 │ +│ 1. Semantic Similarity Aggregation │ │ ┌─────────────────────────────────────────────────────────────────┐ │ -│ │ 当前: 使用精确哈希聚合 │ │ -│ │ 未来: 使用 embedding 计算语义相似度,聚合语义相近的查询 │ │ +│ │ Current: Aggregate using exact hash │ │ +│ │ Future: Use embeddings to calculate semantic similarity, │ │ +│ │ aggregate semantically similar queries │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ -│ 2. 时间衰减 │ +│ 2. Time Decay │ │ ┌─────────────────────────────────────────────────────────────────┐ │ -│ │ 当前: 所有历史反馈等权重 │ │ -│ │ 未来: 近期反馈权重更高,旧反馈逐渐衰减 │ │ +│ │ Current: All historical feedback has equal weight │ │ +│ │ Future: Recent feedback has higher weight, old feedback │ │ +│ │ gradually decays │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ -│ 3. 在线学习 │ +│ 3. Online Learning │ │ ┌─────────────────────────────────────────────────────────────────┐ │ -│ │ 当前: 离线分析,在线应用 │ │ -│ │ 未来: 实时更新模型参数 │ │ +│ │ Current: Offline analysis, online application │ │ +│ │ Future: Real-time model parameter updates │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ -│ 4. 个性化学习 │ +│ 4. Personalized Learning │ │ ┌─────────────────────────────────────────────────────────────────┐ │ -│ │ 当前: 全局学习 │ │ -│ │ 未来: 按用户/场景分别学习 │ │ +│ │ Current: Global learning │ │ +│ │ Future: Learn separately per user/scenario │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ @@ -569,13 +575,13 @@ impl ContextStats { --- -## 9. 代码结构 +## 9. Code Structure ``` src/retrieval/pilot/ -├── mod.rs # 模块入口 -├── feedback.rs # FeedbackStore, PilotLearner 实现 -├── llm_pilot.rs # LlmPilot(集成 learner) -├── builder.rs # ContextBuilder(添加 hash 方法) +├── mod.rs # Module entry point +├── feedback.rs # FeedbackStore, PilotLearner implementation +├── llm_pilot.rs # LlmPilot (integrates learner) +├── builder.rs # ContextBuilder (adds hash methods) └── ... ``` diff --git a/docs/design/pilot.md b/docs/design/pilot.md index d86e00a..a0d4348 100644 --- a/docs/design/pilot.md +++ b/docs/design/pilot.md @@ -1,41 +1,43 @@ -# Pilot 设计文档 +这里是为您翻译的英文版 Pilot 设计文档。 -> Pilot - Retriever Pipeline 的大脑 +# Pilot Design Document -## 概述 +> Pilot - The Brain of the Retriever Pipeline -Pilot 是 Vectorless 检索系统的核心智能组件,负责理解查询、分析文档结构、做出搜索决策。与传统的向量检索不同,Pilot 使用 LLM 进行语义理解和导航决策,同时保持算法的高效执行。 +## Overview -### 设计哲学 +Pilot is the core intelligent component of the Vectorless retrieval system. It is responsible for understanding queries, analyzing document structures, and making search decisions. Unlike traditional vector retrieval, Pilot uses LLMs for semantic understanding and navigation decisions while maintaining efficient algorithmic execution. + +### Design Philosophy ``` ┌─────────────────────────────────────────────────────────────────┐ -│ 设计哲学 │ +│ Design Philosophy │ ├─────────────────────────────────────────────────────────────────┤ -│ 1. 算法负责 "怎么走" - 高效、确定性、低延迟 │ -│ 2. Pilot 负责 "去哪里" - 语义理解、歧义消解、方向判断 │ -│ 3. 关键决策点介入 - 不是每步都问 LLM,而是在需要时才问 │ -│ 4. 分层 fallback - LLM 失败时算法接管,算法失败时 Pilot 救援 │ +│ 1. Algorithm handles "How to walk" - Efficient, deterministic, low latency │ +│ 2. Pilot handles "Where to go" - Semantic understanding, ambiguity resolution, direction judgment │ +│ 3. Key decision point intervention - Not asking the LLM at every step, but only when needed │ +│ 4. Layered fallback - Algorithm takes over when LLM fails, Pilot rescues when algorithm fails │ └─────────────────────────────────────────────────────────────────┘ ``` -### 命名由来 +### Naming Origin -**Pilot (驾驶员)** - 像飞机的驾驶员一样,Pilot 不直接操作每个机械部件(那是 Algorithm 的职责),而是负责: -- 理解目的地(用户查询) -- 规划航线(搜索策略) -- 在关键节点做决策(介入点) -- 应对突发情况(fallback) +**Pilot** - Like the pilot of an airplane, Pilot does not directly operate every mechanical part (that is the Algorithm's responsibility), but is responsible for: +- Understanding the destination (User Query) +- Planning the route (Search Strategy) +- Making decisions at key nodes (Intervention Points) +- Responding to emergencies (Fallback) --- -## 1. Pilot 详细设计 +## 1. Pilot Detailed Design -### 1.1 整体架构 +### 1.1 Overall Architecture ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Pilot 架构 │ +│ Pilot Architecture │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌───────────────────────────────────────────────────────────────────────┐ │ @@ -44,14 +46,14 @@ Pilot 是 Vectorless 检索系统的核心智能组件,负责理解查询、 │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ │ │ Query │ │ Context │ │ Decision │ │ │ │ │ │ Analyzer │──▶│ Builder │──▶│ Engine │ │ │ -│ │ │ 查询分析器 │ │ 上下文构建 │ │ 决策引擎 │ │ │ +│ │ │ (Query Analyzer)│ │ (Context Builder)│ │ (Decision Engine)│ │ │ │ │ └─────────────┘ └─────────────┘ └──────┬──────┘ │ │ │ │ │ │ │ │ │ ▼ │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ │ │ Response │◀──│ LLM │◀──│ Prompt │ │ │ │ │ │ Parser │ │ Client │ │ Builder │ │ │ -│ │ │ 响应解析器 │ │ 客户端 │ │ 提示词构建 │ │ │ +│ │ │ (Response Parser)│ │ (LLM Client) │ │ (Prompt Builder) │ │ │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │ │ │ │ │ │ └───────────────────────────────────────────────────────────────────────┘ │ @@ -62,13 +64,13 @@ Pilot 是 Vectorless 检索系统的核心智能组件,负责理解查询、 │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ │ │ Budget │ │ Fallback │ │ Metrics │ │ │ │ │ │ Controller │ │ Manager │ │ Collector │ │ │ -│ │ │ 预算控制器 │ │ 降级管理 │ │ 指标收集器 │ │ │ +│ │ │ (Budget Controller)│ (Fallback Manager)│ (Metrics Collector)│ │ │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │ │ │ │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ │ │ Policy │ │ Cache │ │ Logger │ │ │ │ │ │ Manager │ │ (Optional) │ │ (Tracing) │ │ │ -│ │ │ 策略管理器 │ │ 缓存 │ │ 日志追踪 │ │ │ +│ │ │ (Policy Manager)│ │ (Cache) │ │ (Logger/Tracing) │ │ │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │ │ │ │ │ │ └───────────────────────────────────────────────────────────────────────┘ │ @@ -78,38 +80,38 @@ Pilot 是 Vectorless 检索系统的核心智能组件,负责理解查询、 --- -## 1.4 Pilot 决策的信息来源 +## 1.4 Information Sources for Pilot Decisions -Pilot 的决策依赖于多层信息,其中 TOC View 是核心——它就像导航电子地图。 +Pilot's decisions rely on multi-layered information, with the TOC View being the core—it is like a navigation electronic map. -### 信息来源架构 +### Information Source Architecture ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Pilot 的"导航地图" │ +│ Pilot's "Navigation Map" │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────────┐ │ │ │ User Query │ │ │ │ "PostgreSQL │ │ -│ │ 连接池配置" │ │ +│ │ Connection Pool Config"│ │ │ └────────┬────────┘ │ │ │ │ │ ▼ │ │ ┌───────────────────────────────────────────────────────────────────────┐ │ -│ │ Pilot 上下文 │ │ +│ │ Pilot Context │ │ │ │ │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ │ │ TOC View │ │ Current │ │ Candidates │ │ │ -│ │ │ (电子地图) │ │ Path │ │ Info │ │ │ -│ │ │ │ │ (当前位置) │ │ (候选路口) │ │ │ +│ │ │ (E-Map) │ │ Path │ │ Info │ │ │ +│ │ │ │ │ (Current Pos)│ │ (Candidates)│ │ │ │ │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ │ │ │ │ │ │ │ │ │ │ └─────────────────┼─────────────────┘ │ │ │ │ ▼ │ │ │ │ ┌─────────────────┐ │ │ │ │ │ LLM Decision │ │ │ -│ │ │ (去哪里) │ │ │ +│ │ │ (Where to go) │ │ │ │ │ └─────────────────┘ │ │ │ │ │ │ │ └───────────────────────────────────────────────────────────────────────┘ │ @@ -117,248 +119,248 @@ Pilot 的决策依赖于多层信息,其中 TOC View 是核心——它就像 └─────────────────────────────────────────────────────────────────────────────┘ ``` -### TOC View - 电子地图(核心) +### TOC View - Electronic Map (Core) -TOC View 是 Pilot 决策的核心依据,由 Index 阶段生成的内容构建: +The TOC View is the core basis for Pilot's decisions, built from content generated during the Index phase: ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ TOC View - 电子地图 │ +│ TOC View - Electronic Map │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ Index 阶段生成的内容: │ +│ Content generated during Index phase: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ TreeNode { │ │ -│ │ title: "配置", // 标题 │ │ -│ │ summary: "本章介绍...", // LLM 生成的摘要 ← 关键! │ │ +│ │ title: "Configuration", // Title │ │ +│ │ summary: "This chapter introduces...", // LLM-generated Summary │ │ │ │ depth: 1, │ │ │ │ children: [...], │ │ │ │ } │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ TOC View 构建逻辑: │ +│ TOC View Construction Logic: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ generate_toc_view(tree, current_node): │ │ │ │ │ │ -│ │ // 1. 从当前节点视角生成 │ │ -│ │ // 2. 包含兄弟节点(横向视野) │ │ -│ │ // 3. 包含子节点(纵向视野) │ │ -│ │ // 4. 每个节点包含 title + summary │ │ +│ │ // 1. Generate from current node perspective │ │ +│ │ // 2. Include sibling nodes (horizontal view) │ │ +│ │ // 3. Include child nodes (vertical view) │ │ +│ │ // 4. Each node contains title + summary │ │ │ │ │ │ -│ │ 输出示例: │ │ +│ │ Example Output: │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ -│ │ │ 📍 当前位置: Root → 配置 │ │ │ +│ │ │ 📍 Current Location: Root → Configuration │ │ │ │ │ │ │ │ │ -│ │ │ 📂 兄弟节点: │ │ │ -│ │ │ ├─ 简介 [概述项目功能和架构] │ │ │ -│ │ │ ├─ 安装 [安装步骤和环境要求] │ │ │ -│ │ │ ├─ 配置 ⭐ [配置项详解] ← 当前节点 │ │ │ -│ │ │ │ ├─ 基本配置 [基础参数设置] │ │ │ -│ │ │ │ ├─ 数据库配置 [数据库连接相关] ← 关键匹配! │ │ │ -│ │ │ │ └─ 高级配置 [性能调优选项] │ │ │ -│ │ │ └─ API 参考 [接口文档] │ │ │ +│ │ │ 📂 Sibling Nodes: │ │ │ +│ │ │ ├─ Introduction [Overview of features and architecture] │ │ │ +│ │ │ ├─ Installation [Installation steps and requirements] │ │ │ +│ │ │ ├─ Configuration ⭐ [Detailed config items] ← Current │ │ │ +│ │ │ │ ├─ Basic Config [Basic parameter settings] │ │ │ +│ │ │ │ ├─ Database Config [DB connection related] ← Match! │ │ │ +│ │ │ │ └─ Advanced Config [Performance tuning options] │ │ │ +│ │ │ └─ API Reference [Interface documentation] │ │ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` -### 三层信息结构 +### Three-Layer Information Structure ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Pilot 决策的三层信息 │ +│ Three Layers of Pilot Decision Info │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ Layer 1: TOC View (全局地图) │ +│ Layer 1: TOC View (Global Map) │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 作用: 提供文档的全局结构视图 │ │ -│ │ 来源: Index Pipeline 的 Enrich 阶段生成的 summary │ │ -│ │ Token: 约 200-500 tokens │ │ +│ │ Role: Provides a global structural view of the document │ │ +│ │ Source: Summary generated by the Enrich stage of the Index Pipeline│ │ +│ │ Token: ~200-500 tokens │ │ │ │ │ │ -│ │ 示例: │ │ -│ │ "本文档结构: 1.简介 2.安装 3.配置(3.1基本 3.2数据库 3.3高级) 4.API" │ │ +│ │ Example: │ │ +│ │ "Doc Structure: 1.Intro 2.Install 3.Config(3.1Basic 3.2DB 3.3Adv) 4.API"│ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ Layer 2: Current Path (当前位置) │ +│ Layer 2: Current Path (Current Location) │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 作用: 告诉 LLM 我们已经走了哪里 │ │ -│ │ 来源: 搜索过程的路径记录 │ │ -│ │ Token: 约 50-100 tokens │ │ +│ │ Role: Tells the LLM where we have been │ │ +│ │ Source: Path records of the search process │ │ +│ │ Token: ~50-100 tokens │ │ │ │ │ │ -│ │ 示例: │ │ -│ │ "当前路径: Root → 配置 → 数据库配置" │ │ +│ │ Example: │ │ +│ │ "Current Path: Root → Configuration → Database Config" │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ Layer 3: Candidates Detail (候选路口详情) │ +│ Layer 3: Candidates Detail (Candidate Intersection Details) │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 作用: 提供候选节点的详细信息,供 LLM 判断 │ │ -│ │ 来源: TreeNode 的 title + summary + 部分内容 │ │ -│ │ Token: 约 100-300 tokens │ │ +│ │ Role: Provides detailed info on candidate nodes for LLM judgment │ │ +│ │ Source: TreeNode's title + summary + partial content │ │ +│ │ Token: ~100-300 tokens │ │ │ │ │ │ -│ │ 示例: │ │ -│ │ 候选节点: │ │ -│ │ A. 连接字符串 │ │ -│ │ 摘要: 配置数据库连接 URL 和认证信息 │ │ -│ │ B. 连接池 ⭐ │ │ -│ │ 摘要: 配置连接池大小、超时、最大连接数等 │ │ -│ │ C. 超时设置 │ │ -│ │ 摘要: 配置查询和连接超时时间 │ │ +│ │ Example: │ │ +│ │ Candidates: │ │ +│ │ A. Connection String │ │ +│ │ Summary: Configure DB connection URL and auth info │ │ +│ │ B. Connection Pool ⭐ │ │ +│ │ Summary: Configure pool size, timeouts, max connections, etc. │ │ +│ │ C. Timeout Settings │ │ +│ │ Summary: Configure query and connection timeout │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` -### 决策过程示例 +### Decision Process Example ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Pilot 决策过程示例 │ +│ Pilot Decision Process Example │ └─────────────────────────────────────────────────────────────────────────────┘ -Query: "PostgreSQL 连接池的最大连接数怎么配置?" +Query: "How to configure the max connections for PostgreSQL connection pool?" -Step 1: 构建 TOC View (从 Index 阶段的 summary) +Step 1: Build TOC View (from Index stage summary) ┌─────────────────────────────────────────────────────────────────────────────┐ -│ TOC View (简化版): │ +│ TOC View (Simplified): │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 文档结构: │ │ -│ │ 1. 快速开始 │ │ -│ │ 2. 配置 │ │ -│ │ 2.1 基本配置 │ │ -│ │ 2.2 数据库配置 │ │ -│ │ - 连接字符串 │ │ -│ │ - 连接池 ← 包含"连接池" │ │ -│ │ - 超时设置 │ │ -│ │ 2.3 高级配置 │ │ +│ │ Document Structure: │ │ +│ │ 1. Quick Start │ │ +│ │ 2. Configuration │ │ +│ │ 2.1 Basic Config │ │ +│ │ 2.2 Database Config │ │ +│ │ - Connection String │ │ +│ │ - Connection Pool ← Contains "Connection Pool" │ │ +│ │ - Timeout Settings │ │ +│ │ 2.3 Advanced Config │ │ │ │ 3. API │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ 这个 TOC 是 Index 阶段 LLM 生成的 summary 构成的! │ +│ This TOC is constructed from Index stage LLM-generated summaries! │ └─────────────────────────────────────────────────────────────────────────────┘ │ ▼ -Step 2: LLM 分析 +Step 2: LLM Analysis ┌─────────────────────────────────────────────────────────────────────────────┐ -│ LLM 看到的信息: │ +│ Information seen by LLM: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 用户查询: "PostgreSQL 连接池的最大连接数怎么配置?" │ │ +│ │ User Query: "How to configure the max connections for PostgreSQL connection pool?" │ │ │ │ │ -│ │ 当前位置: 配置 → 数据库配置 │ │ +│ │ Current Location: Configuration → Database Config │ │ │ │ │ │ -│ │ 候选节点: │ │ -│ │ 1. 连接字符串 [配置数据库 URL 和认证] │ │ -│ │ 2. 连接池 [配置池大小、超时、最大连接数] ← 直接匹配! │ │ -│ │ 3. 超时设置 [配置查询超时时间] │ │ +│ │ Candidates: │ │ +│ │ 1. Connection String [Configure DB URL and auth] │ │ +│ │ 2. Connection Pool [Configure pool size, timeout, max connections] ← Direct Match! │ +│ │ 3. Timeout Settings [Configure query timeout] │ │ │ │ │ │ -│ │ 请判断哪个节点最可能包含答案? │ │ +│ │ Which node is most likely to contain the answer? │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ LLM 推理: │ +│ LLM Reasoning: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 查询关键词: "连接池", "最大连接数" │ │ -│ │ 候选 2 的摘要包含: "连接池", "最大连接数" │ │ -│ │ → 候选 2 直接匹配,置信度 0.95 │ │ +│ │ Query Keywords: "Connection Pool", "Max Connections" │ │ +│ │ Candidate 2 Summary: "Connection Pool", "Max Connections" │ │ +│ │ → Candidate 2 matches directly, Confidence 0.95 │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ │ ▼ -Step 3: 返回决策 +Step 3: Return Decision ┌─────────────────────────────────────────────────────────────────────────────┐ │ PilotDecision { │ │ ranked_candidates: [ │ -│ (Node 2 "连接池", score: 0.95, reason: "摘要直接匹配查询关键词"), │ │ -│ (Node 3 "超时设置", score: 0.30, reason: "不太相关"), │ │ -│ (Node 1 "连接字符串", score: 0.20, reason: "不相关"), │ │ +│ (Node 2 "Connection Pool", score: 0.95, reason: "Summary directly matches query keywords"), │ +│ (Node 3 "Timeout Settings", score: 0.30, reason: "Not very relevant"), │ +│ (Node 1 "Connection String", score: 0.20, reason: "Irrelevant"), │ │ ], │ │ direction: GoDeeper, │ │ confidence: 0.95, │ -│ reasoning: "候选节点'连接池'的摘要明确提到'最大连接数',直接匹配查询", │ │ +│ reasoning: "Candidate node 'Connection Pool' summary explicitly mentions 'max connections', direct query match", │ │ } │ └─────────────────────────────────────────────────────────────────────────────┘ ``` -### 关键洞察 +### Key Insights ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ 关键洞察 │ +│ Key Insights │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ 1. Index 阶段的 summary 质量决定 Pilot 效果 │ +│ 1. Index stage summary quality determines Pilot effectiveness │ │ ┌─────────────────────────────────────────────────────────────────┐ │ -│ │ 好的 summary: "配置连接池大小、超时、最大连接数等参数" │ │ -│ │ 差的 summary: "本章介绍连接池相关内容" │ │ +│ │ Good summary: "Configure connection pool size, timeout, max connections params" │ +│ │ Bad summary: "This chapter introduces connection pool related content" │ │ │ │ │ -│ │ → Index Enrich 阶段的 prompt 很重要! │ │ +│ │ → The prompt in the Index Enrich stage is crucial! │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ -│ 2. TOC View 需要动态生成 │ +│ 2. TOC View needs to be generated dynamically │ │ ┌─────────────────────────────────────────────────────────────────┐ │ -│ │ 不是整个文档的 TOC,而是从"当前节点"视角的局部视图 │ │ -│ │ 包含: 兄弟节点 + 子节点 + 父节点链 │ │ +│ │ Not the TOC of the entire document, but a local view from the "current node" perspective │ +│ │ Includes: Sibling nodes + Child nodes + Parent chain │ │ │ │ │ │ -│ │ 这样 Token 消耗可控,且有上下文 │ │ +│ │ This keeps Token consumption manageable while providing context│ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ -│ 3. 类比: 高德地图导航 │ +│ 3. Analogy: Gaode Map (or Google Maps) Navigation │ │ ┌─────────────────────────────────────────────────────────────────┐ │ -│ │ TOC View = 地图 (道路网络) │ │ -│ │ Summary = 路标 (路口描述) │ │ -│ │ Current Path = GPS 定位 (当前位置) │ │ -│ │ Candidates = 前方路口 (可选方向) │ │ -│ │ Query = 目的地 (要去哪里) │ │ +│ │ TOC View = Map (Road network) │ │ +│ │ Summary = Road signs (Intersection descriptions) │ │ +│ │ Current Path = GPS Location (Current position) │ │ +│ │ Candidates = Upcoming intersections (Optional directions) │ │ +│ │ Query = Destination (Where to go) │ │ │ │ │ │ -│ │ Pilot = 驾驶员 (综合以上信息做决策) │ │ +│ │ Pilot = Driver (Integrates above info to make decisions)│ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` -### ContextBuilder Token 预算分配 +### ContextBuilder Token Budget Allocation ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ ContextBuilder - Token 预算分配 │ +│ ContextBuilder - Token Budget Allocation │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ Token 预算分配 (假设 500 tokens 总预算): │ +│ Token Budget Allocation (Assuming 500 tokens total budget): │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ │ │ │ │ ┌────────────────────────────────────────┐ 30% (150 tokens) │ │ │ │ │ Query + Intent │ │ │ -│ │ │ "PostgreSQL 连接池最大连接数配置" │ │ │ +│ │ │ "PostgreSQL connection pool max connections config"│ │ │ │ │ └────────────────────────────────────────┘ │ │ │ │ │ │ -│ │ ┌────────────────────────────────────────┐ 20% (100 tokens) │ │ +│ │ ┌────────────────────────────────────────────────┐ 20% (100 tokens) │ │ │ │ │ Current Path │ │ │ -│ │ │ Root → 配置 → 数据库配置 │ │ │ +│ │ │ Root → Configuration → Database Config │ │ │ │ │ └────────────────────────────────────────┘ │ │ │ │ │ │ -│ │ ┌────────────────────────────────────────┐ 40% (200 tokens) │ │ +│ │ ┌────────────────────────────────────────────────┐ 40% (200 tokens) │ │ │ │ │ Candidates (title + summary each) │ │ │ -│ │ │ A. 连接字符串 [配置URL和认证] │ │ │ -│ │ │ B. 连接池 [配置池大小、最大连接数] │ │ │ -│ │ │ C. 超时设置 [配置超时时间] │ │ │ +│ │ │ A. Connection String [Configure URL and auth] │ │ │ +│ │ │ B. Connection Pool [Configure pool size, max connections] │ │ │ +│ │ │ C. Timeout Settings [Configure timeout] │ │ │ │ │ └────────────────────────────────────────┘ │ │ │ │ │ │ -│ │ ┌────────────────────────────────────────┐ 10% (50 tokens) │ │ -│ │ │ Sibling Context (兄弟节点概览) │ │ │ -│ │ │ 同级还有: 基本配置、高级配置 │ │ │ +│ │ ┌────────────────────────────────────────────────┐ 10% (50 tokens) │ │ +│ │ │ Sibling Context (Sibling overview) │ │ │ +│ │ │ Other siblings: Basic Config, Advanced Config │ │ │ │ │ └────────────────────────────────────────┘ │ │ │ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ 动态调整策略: │ +│ Dynamic Adjustment Strategy: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ if candidates.len() > 5: │ │ -│ │ // 候选太多,减少每个候选的 detail │ │ -│ │ 只包含 title,不包含 summary │ │ +│ │ // Too many candidates, reduce detail per candidate │ │ +│ │ Include only title, exclude summary │ │ │ │ │ │ │ │ if depth > 3: │ │ -│ │ // 深层搜索,减少 TOC 范围 │ │ -│ │ 只显示当前层和子层 │ │ +│ │ // Deep search, reduce TOC range │ │ +│ │ Show only current layer and child layers │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ @@ -366,91 +368,91 @@ Step 3: 返回决策 --- -## 2. 介入点详细设计 +## 2. Intervention Point Detailed Design -### 2.1 介入点类型 +### 2.1 Intervention Point Types ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Pilot 介入点 │ +│ Pilot Intervention Points │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ START - 搜索开始 │ │ +│ │ START - Search Start │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 时机: 搜索算法开始前 │ │ -│ │ 任务: 理解查询意图,确定搜索起点和优先方向 │ │ -│ │ 输入: query, tree (ToC view) │ │ -│ │ 输出: entry_points, initial_direction, confidence │ │ -│ │ 配置: guide_at_start: bool │ │ +│ │ Timing: Before search algorithm starts │ │ +│ │ Task: Understand query intent, determine entry points and priority │ │ +│ │ Input: query, tree (ToC view) │ │ +│ │ Output: entry_points, initial_direction, confidence │ │ +│ │ Config: guide_at_start: bool │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ FORK - 分叉路口 │ │ +│ │ FORK - Fork in the Road │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 时机: 当前节点有多个候选子节点时 │ │ -│ │ 任务: 判断哪个分支更可能包含答案 │ │ -│ │ 输入: path, candidates, query │ │ -│ │ 输出: ranked_candidates, direction, confidence │ │ -│ │ 触发条件: candidates.len() > fork_threshold │ │ +│ │ Timing: When current node has multiple candidate child nodes │ │ +│ │ Task: Determine which branch is more likely to contain the answer │ │ +│ │ Input: path, candidates, query │ │ +│ │ Output: ranked_candidates, direction, confidence │ │ +│ │ Trigger: candidates.len() > fork_threshold │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ BACKTRACK - 回溯 │ │ +│ │ BACKTRACK - Backtrack │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 时机: Judge 判断内容不足,需要回溯时 │ │ -│ │ 任务: 分析失败原因,建议新的搜索方向 │ │ -│ │ 输入: failed_path, visited, query │ │ -│ │ 输出: alternative_branches, backtrack_reason │ │ -│ │ 配置: guide_at_backtrack: bool │ │ +│ │ Timing: When Judge determines content is insufficient, needs backtracking │ +│ │ Task: Analyze failure reason, suggest new search direction │ │ +│ │ Input: failed_path, visited, query │ │ +│ │ Output: alternative_branches, backtrack_reason │ │ +│ │ Config: guide_at_backtrack: bool │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ EVALUATE - 节点评估 │ │ +│ │ EVALUATE - Node Evaluation │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 时机: 需要判断当前节点是否包含答案时 │ │ -│ │ 任务: 评估节点内容与查询的相关性 │ │ -│ │ 输入: node_content, query │ │ -│ │ 输出: relevance_score, is_answer, reasoning │ │ -│ │ 触发条件: 到达叶子节点或算法不确定时 │ │ +│ │ Timing: When needing to determine if current node contains answer │ │ +│ │ Task: Evaluate relevance of node content to query │ │ +│ │ Input: node_content, query │ │ +│ │ Output: relevance_score, is_answer, reasoning │ │ +│ │ Trigger: Reaching leaf node or when algorithm is uncertain │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` -### 2.2 介入判断逻辑 +### 2.2 Intervention Judgment Logic ```rust impl Pilot for LlmPilot { fn should_intervene(&self, state: &SearchState<'_>) -> bool { let config = &self.config.intervention; - // 条件 1: 预算检查(最高优先级) + // Condition 1: Budget check (Highest priority) if !self.budget.can_call() { return false; } - // 条件 2: 候选数量超过阈值(分叉路口) + // Condition 2: Number of candidates exceeds threshold (Fork) if state.candidates.len() > config.fork_threshold { return true; } - // 条件 3: 候选分数接近(算法无法区分) + // Condition 3: Candidate scores are close (Algorithm cannot distinguish) if self.scores_are_close(state.candidates, state.tree, config.score_gap_threshold) { return true; } - // 条件 4: 当前分数过低(可能走错方向) + // Condition 4: Current score is too low (May be going the wrong way) if state.best_score < config.low_score_threshold { return true; } - // 条件 5: 回溯时且配置允许 + // Condition 5: During backtracking and config allows if state.is_backtracking && self.config.guide_at_backtrack { return true; } - // 条件 6: 每层介入次数限制 + // Condition 6: Intervention limit per level let level_calls = self.get_level_calls(state.depth); if level_calls >= config.max_interventions_per_level { return false; @@ -460,7 +462,7 @@ impl Pilot for LlmPilot { } } -/// 判断候选分数是否接近 +/// Check if candidate scores are close fn scores_are_close(&self, candidates: &[NodeId], tree: &DocumentTree, threshold: f32) -> bool { if candidates.len() < 2 { return false; @@ -477,29 +479,29 @@ fn scores_are_close(&self, candidates: &[NodeId], tree: &DocumentTree, threshold } ``` -### 2.3 介入配置 +### 2.3 Intervention Configuration ```rust -/// 介入配置 +/// Intervention Configuration #[derive(Debug, Clone)] pub struct InterventionConfig { - /// 候选数量阈值(超过此值考虑介入) + /// Candidate count threshold (Consider intervention if exceeded) pub fork_threshold: usize, - /// 分数差距阈值(差距小于此值时介入) + /// Score gap threshold (Intervene if gap is smaller than this) pub score_gap_threshold: f32, - /// 低分阈值(最高分低于此值时介入) + /// Low score threshold (Intervene if highest score is lower than this) pub low_score_threshold: f32, - /// 每层最大介入次数 + /// Max interventions per level pub max_interventions_per_level: usize, } impl Default for InterventionConfig { fn default() -> Self { Self { - fork_threshold: 3, // 3 个以上候选时介入 - score_gap_threshold: 0.15, // 分数差距 < 0.15 时介入 - low_score_threshold: 0.3, // 分数 < 0.3 时介入 - max_interventions_per_level: 2, // 每层最多介入 2 次 + fork_threshold: 3, // Intervene when > 3 candidates + score_gap_threshold: 0.15, // Intervene if score gap < 0.15 + low_score_threshold: 0.3, // Intervene if score < 0.3 + max_interventions_per_level: 2, // Max 2 interventions per level } } } @@ -507,78 +509,78 @@ impl Default for InterventionConfig { --- -## 3. Fallback 机制 +## 3. Fallback Mechanism -### 3.1 降级层级 +### 3.1 Fallback Levels ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Fallback 降级层级 │ +│ Fallback Levels │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ Level 0: 正常 LLM 调用 │ +│ Level 0: Normal LLM Call │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 条件: 预算充足,LLM 服务可用 │ │ -│ │ 行为: 正常调用 LLM,获取决策 │ │ +│ │ Condition: Budget sufficient, LLM service available │ │ +│ │ Behavior: Normal LLM call, get decision │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ -│ │ 失败 │ -│ ▼ │ -│ Level 1: 重试 │ +│ │ Failure │ +│ ▼ │ +│ Level 1: Retry │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 条件: 网络错误、超时、rate limit │ │ -│ │ 行为: 指数退避重试,最多 3 次 │ │ -│ │ 参数: initial_delay=1s, max_delay=10s, max_attempts=3 │ │ +│ │ Condition: Network error, timeout, rate limit │ │ +│ │ Behavior: Exponential backoff retry, max 3 times │ │ +│ │ Params: initial_delay=1s, max_delay=10s, max_attempts=3 │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ -│ │ 失败 │ -│ ▼ │ -│ Level 2: 简化上下文 │ +│ │ Failure │ +│ ▼ │ +│ Level 2: Simplify Context │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 条件: token 超限、上下文过长 │ │ -│ │ 行为: 减少上下文信息,只保留核心内容 │ │ -│ │ 策略: 移除 ToC,只保留当前节点和候选标题 │ │ +│ │ Condition: Token limit exceeded, context too long │ │ +│ │ Behavior: Reduce context info, keep only core content │ │ +│ │ Strategy: Remove ToC, keep only current node and candidate titles │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ -│ │ 失败 │ -│ ▼ │ -│ Level 3: 纯算法模式 │ +│ │ Failure │ +│ ▼ │ +│ Level 3: Pure Algorithm Mode │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 条件: LLM 完全不可用、预算耗尽 │ │ -│ │ 行为: 完全依赖算法打分,不调用 LLM │ │ -│ │ 结果: 使用 NodeScorer 的关键词匹配 │ │ +│ │ Condition: LLM completely unavailable, budget exhausted │ │ +│ │ Behavior: Rely entirely on algorithm scoring, no LLM calls │ │ +│ │ Result: Use NodeScorer keyword matching │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` -### 3.2 Fallback 策略定义 +### 3.2 Fallback Strategy Definition ```rust -/// 降级策略 +/// Fallback Strategy #[derive(Debug, Clone)] pub enum FallbackStrategy { - /// 重试策略 + /// Retry strategy Retry { max_attempts: usize, backoff: BackoffPolicy, }, - /// 简化上下文 + /// Simplify context SimplifyContext { remove_toc: bool, max_candidates: usize, }, - /// 使用算法替代 + /// Use algorithm instead UseAlgorithm, - /// 返回默认决策 + /// Return default decision ReturnDefault, } -/// 退避策略 +/// Backoff Policy #[derive(Debug, Clone)] pub enum BackoffPolicy { - /// 固定间隔 + /// Fixed interval Fixed { delay_ms: u64 }, - /// 线性增长 + /// Linear increase Linear { initial_ms: u64, increment_ms: u64 }, - /// 指数增长 + /// Exponential increase Exponential { initial_ms: u64, multiplier: f64, max_ms: u64 }, } @@ -593,20 +595,20 @@ impl Default for BackoffPolicy { } ``` -### 3.3 FallbackManager 实现 +### 3.3 FallbackManager Implementation ```rust -/// 降级管理器 +/// Fallback Manager pub struct FallbackManager { config: FallbackConfig, - /// 当前降级级别 + /// Current fallback level current_level: AtomicU8, - /// 连续失败次数 + /// Consecutive failure count consecutive_failures: AtomicUsize, } impl FallbackManager { - /// 执行带降级的调用 + /// Execute with fallback pub async fn execute_with_fallback( &self, operation: F, @@ -619,7 +621,7 @@ impl FallbackManager { loop { match level { 0 => { - // Level 0: 正常调用 + // Level 0: Normal call match operation().await { Ok(result) => { self.on_success(); @@ -636,7 +638,7 @@ impl FallbackManager { } } 1 => { - // Level 1: 重试 + // Level 1: Retry match self.retry_operation(&operation).await { Ok(result) => { self.on_success(); @@ -649,12 +651,12 @@ impl FallbackManager { } } 2 => { - // Level 2: 简化上下文 - // 由调用方处理,返回特定错误 + // Level 2: Simplify context + // Handled by caller, return specific error return Err(FallbackError::SimplifyContextRequired); } 3 => { - // Level 3: 纯算法模式 + // Level 3: Pure algorithm mode return Err(FallbackError::AlgorithmFallback); } _ => unreachable!(), @@ -662,7 +664,7 @@ impl FallbackManager { } } - /// 重试操作 + /// Retry operation async fn retry_operation(&self, operation: &F) -> Result where F: Fn() -> std::pin::Pin> + Send>>, @@ -688,7 +690,7 @@ impl FallbackManager { fn on_success(&self) { self.consecutive_failures.store(0, Ordering::Relaxed); - // 逐渐恢复到更高级别 + // Gradually recover to higher level let current = self.current_level.load(Ordering::Relaxed); if current > 0 { self.current_level.fetch_sub(1, Ordering::Relaxed); @@ -697,7 +699,7 @@ impl FallbackManager { fn on_failure(&self) { let failures = self.consecutive_failures.fetch_add(1, Ordering::Relaxed); - // 连续失败 3 次后升级降级级别 + // Escalate fallback level after 3 consecutive failures if failures >= 2 { let current = self.current_level.load(Ordering::Relaxed); if current < 3 { @@ -715,55 +717,55 @@ impl FallbackManager { --- -## 4. Token 消耗衡量 +## 4. Token Consumption Measurement -### 4.1 预算配置 +### 4.1 Budget Configuration ```rust -/// 预算配置 +/// Budget Configuration #[derive(Debug, Clone)] pub struct BudgetConfig { - /// 单次检索最大 token 数 + /// Max tokens per single query retrieval pub max_tokens_per_query: usize, - /// 单次 LLM 调用最大 token 数 + /// Max tokens per single LLM call pub max_tokens_per_call: usize, - /// 单次检索最大 LLM 调用次数 + /// Max LLM calls per single query pub max_calls_per_query: usize, - /// 每层(深度)最大调用次数 + /// Max calls per level (depth) pub max_calls_per_level: usize, - /// 是否硬性限制(true: 超预算直接拒绝;false: 尝试继续) + /// Hard limit flag (true: reject if over budget; false: try to continue) pub hard_limit: bool, } impl Default for BudgetConfig { fn default() -> Self { Self { - max_tokens_per_query: 2000, // 单次检索最多 2000 tokens - max_tokens_per_call: 500, // 单次调用最多 500 tokens - max_calls_per_query: 5, // 最多调用 5 次 - max_calls_per_level: 2, // 每层最多 2 次 + max_tokens_per_query: 2000, // Max 2000 tokens per query + max_tokens_per_call: 500, // Max 500 tokens per call + max_calls_per_query: 5, // Max 5 calls + max_calls_per_level: 2, // Max 2 calls per level hard_limit: true, } } } ``` -### 4.2 预算控制器 +### 4.2 Budget Controller ```rust -/// 预算控制器 +/// Budget Controller pub struct BudgetController { config: BudgetConfig, - /// 已使用的 token 数 + /// Tokens used tokens_used: AtomicUsize, - /// 已调用的次数 + /// Calls made calls_made: AtomicUsize, - /// 每层调用次数 + /// Calls per level level_calls: RwLock>, } impl BudgetController { - /// 创建新的预算控制器 + /// Create new budget controller pub fn new(config: BudgetConfig) -> Self { Self { config, @@ -773,7 +775,7 @@ impl BudgetController { } } - /// 检查是否可以调用 LLM + /// Check if LLM can be called pub fn can_call(&self) -> bool { let calls = self.calls_made.load(Ordering::Relaxed); let tokens = self.tokens_used.load(Ordering::Relaxed); @@ -782,7 +784,7 @@ impl BudgetController { && tokens < self.config.max_tokens_per_query } - /// 检查特定层是否可以调用 + /// Check if call is possible at specific level pub fn can_call_at_level(&self, level: usize) -> bool { if !self.can_call() { return false; @@ -793,39 +795,39 @@ impl BudgetController { calls < self.config.max_calls_per_level } - /// 预估调用成本 + /// Estimate call cost pub fn estimate_cost(&self, context: &str) -> usize { - // 使用 tiktoken 或简单的字符估算 - // 粗略估算:1 token ≈ 4 chars (英文) 或 1.5 chars (中文) + // Use tiktoken or simple character estimation + // Rough estimate: 1 token ≈ 4 chars (English) or 1.5 chars (Chinese) let char_count = context.chars().count(); - // 保守估计,按中文计算 - char_count / 2 + 100 // +100 为输出预留 + // Conservative estimate, based on Chinese + char_count / 2 + 100 // +100 reserved for output } - /// 检查预估成本是否在预算内 + /// Check if estimated cost is within budget pub fn can_afford(&self, estimated_cost: usize) -> bool { let remaining = self.remaining_budget(); estimated_cost <= remaining && estimated_cost <= self.config.max_tokens_per_call } - /// 获取剩余预算 + /// Get remaining budget pub fn remaining_budget(&self) -> usize { let used = self.tokens_used.load(Ordering::Relaxed); self.config.max_tokens_per_query.saturating_sub(used) } - /// 记录 token 使用 + /// Record token usage pub fn record_usage(&self, input_tokens: usize, output_tokens: usize, level: usize) { let total = input_tokens + output_tokens; self.tokens_used.fetch_add(total, Ordering::Relaxed); self.calls_made.fetch_add(1, Ordering::Relaxed); - // 记录层级调用 + // Record level calls let mut level_calls = self.level_calls.write().unwrap(); *level_calls.entry(level).or_insert(0) += 1; } - /// 获取使用统计 + /// Get usage statistics pub fn get_usage_stats(&self) -> BudgetUsage { BudgetUsage { tokens_used: self.tokens_used.load(Ordering::Relaxed), @@ -835,7 +837,7 @@ impl BudgetController { } } - /// 重置(新查询开始时) + /// Reset (when new query starts) pub fn reset(&self) { self.tokens_used.store(0, Ordering::Relaxed); self.calls_made.store(0, Ordering::Relaxed); @@ -843,7 +845,7 @@ impl BudgetController { } } -/// 预算使用统计 +/// Budget Usage Statistics #[derive(Debug, Clone)] pub struct BudgetUsage { pub tokens_used: usize, @@ -859,42 +861,42 @@ impl BudgetUsage { } ``` -### 4.3 Token 消耗流程 +### 4.3 Token Consumption Flow ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Token 消耗流程 │ +│ Token Consumption Flow │ └─────────────────────────────────────────────────────────────────────────────┘ -LLM 调用前: +Before LLM Call: ┌─────────────────────────────────────────────────────────────────────────────┐ │ 1. BudgetController.can_call() │ -│ └─ 检查: calls_made < max_calls_per_query │ -│ └─ 检查: tokens_used < max_tokens_per_query │ +│ └─ Check: calls_made < max_calls_per_query │ +│ └─ Check: tokens_used < max_tokens_per_query │ │ │ │ 2. BudgetController.can_call_at_level(depth) │ -│ └─ 检查: level_calls[depth] < max_calls_per_level │ +│ └─ Check: level_calls[depth] < max_calls_per_level │ │ │ │ 3. BudgetController.estimate_cost(context) │ -│ └─ 预估: input_tokens + output_tokens (预留) │ +│ └─ Estimate: input_tokens + output_tokens (reserved) │ │ │ │ 4. BudgetController.can_afford(estimated_cost) │ -│ └─ 检查: estimated_cost <= remaining_budget │ -│ └─ 检查: estimated_cost <= max_tokens_per_call │ +│ └─ Check: estimated_cost <= remaining_budget │ +│ └─ Check: estimated_cost <= max_tokens_per_call │ │ │ -│ 决策: 全部通过 → 继续调用;任一失败 → 跳过或降级 │ +│ Decision: All pass → Continue call; Any fail → Skip or Fallback │ └─────────────────────────────────────────────────────────────────────────────┘ │ ▼ -LLM 调用: +LLM Call: ┌─────────────────────────────────────────────────────────────────────────────┐ -│ LLM Client 返回: │ -│ - usage.prompt_tokens (输入 tokens) │ -│ - usage.completion_tokens (输出 tokens) │ +│ LLM Client Returns: │ +│ - usage.prompt_tokens (Input tokens) │ +│ - usage.completion_tokens (Output tokens) │ └─────────────────────────────────────────────────────────────────────────────┘ │ ▼ -LLM 调用后: +After LLM Call: ┌─────────────────────────────────────────────────────────────────────────────┐ │ BudgetController.record_usage(input_tokens, output_tokens, level) │ │ └─ tokens_used += input_tokens + output_tokens │ @@ -910,157 +912,157 @@ LLM 调用后: --- -## 5. 职责划分 +## 5. Responsibility Division -### 5.1 模块职责 +### 5.1 Module Responsibilities ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Pilot 模块职责划分 │ +│ Pilot Module Responsibilities │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ QueryAnalyzer - 查询分析器 │ │ +│ │ QueryAnalyzer - Query Analyzer │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 职责: │ │ -│ │ • 分析查询复杂度(简单/中等/复杂) │ │ -│ │ • 提取关键词和实体 │ │ -│ │ • 识别查询意图(事实查询/对比/解释/操作指南) │ │ -│ │ • 判断是否需要 Pilot 介入 │ │ -│ │ │ │ -│ │ 输入: query: String │ │ -│ │ 输出: QueryAnalysis { complexity, keywords, intent, needs_pilot } │ │ -│ │ │ │ -│ │ 实现策略: │ │ -│ │ • 轻量级:基于规则(关键词计数、句子结构) │ │ -│ │ • 重量级:LLM 分析(复杂查询) │ │ +│ │ Responsibilities: │ │ +│ │ • Analyze query complexity (Simple/Medium/Complex) │ │ +│ │ • Extract keywords and entities │ │ +│ │ • Identify query intent (Fact/Compare/Explain/How-To) │ │ +│ │ • Determine if Pilot intervention is needed │ │ +│ │ │ │ +│ │ Input: query: String │ │ +│ │ Output: QueryAnalysis { complexity, keywords, intent, needs_pilot } │ │ +│ │ │ │ +│ │ Implementation Strategy: │ │ +│ │ • Lightweight: Rule-based (keyword count, sentence structure) │ │ +│ │ • Heavyweight: LLM analysis (complex queries) │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ ContextBuilder - 上下文构建器 │ │ +│ │ ContextBuilder - Context Builder │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 职责: │ │ -│ │ • 构建发送给 LLM 的上下文信息 │ │ -│ │ • 提取当前路径的节点信息(标题、摘要、深度) │ │ -│ │ • 构建候选节点的描述 │ │ -│ │ • 生成 ToC 视图(从当前节点视角) │ │ -│ │ • 控制 token 预算分配 │ │ -│ │ │ │ -│ │ 输入: tree, path, candidates, query │ │ -│ │ 输出: PilotContext { path_info, candidates_info, toc_view } │ │ -│ │ │ │ -│ │ Token 预算分配: │ │ -│ │ • path_info: 20% │ │ -│ │ • candidates_info: 50% │ │ -│ │ • toc_view: 30% │ │ +│ │ Responsibilities: │ │ +│ │ • Build context information to send to LLM │ │ +│ │ • Extract node information (title, summary, depth) of current path │ │ +│ │ • Build descriptions of candidate nodes │ │ +│ │ • Generate ToC view (from current node perspective) │ │ +│ │ • Control token budget allocation │ │ +│ │ │ │ +│ │ Input: tree, path, candidates, query │ │ +│ │ Output: PilotContext { path_info, candidates_info, toc_view } │ │ +│ │ │ │ +│ │ Token Budget Allocation: │ │ +│ │ • path_info: 20% │ │ +│ │ • candidates_info: 50% │ │ +│ │ • toc_view: 30% │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ PromptBuilder - 提示词构建器 │ │ +│ │ PromptBuilder - Prompt Builder │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 职责: │ │ -│ │ • 根据场景选择合适的 prompt 模板 │ │ -│ │ • 填充模板变量 │ │ -│ │ • 管理 system prompt 和 user prompt │ │ -│ │ • 支持多语言 │ │ -│ │ │ │ -│ │ 场景类型: │ │ -│ │ • START: 搜索开始,确定起点 │ │ -│ │ • FORK: 分叉路口,选择分支 │ │ -│ │ • BACKTRACK: 回溯时,分析失败原因 │ │ -│ │ • EVALUATE: 评估节点是否包含答案 │ │ -│ │ │ │ -│ │ 设计要点: │ │ -│ │ • 模板可配置(用户可自定义) │ │ -│ │ • 包含 few-shot 示例(提高质量) │ │ -│ │ • 输出格式明确(JSON schema) │ │ +│ │ Responsibilities: │ │ +│ │ • Select appropriate prompt template based on scenario │ │ +│ │ • Fill template variables │ │ +│ │ • Manage system prompt and user prompt │ │ +│ │ • Support multiple languages │ │ +│ │ │ │ +│ │ Scenario Types: │ │ +│ │ • START: Search start, determine entry point │ │ +│ │ • FORK: Fork in road, choose branch │ │ +│ │ • BACKTRACK: When backtracking, analyze failure reason │ │ +│ │ • EVALUATE: Evaluate if node contains answer │ │ +│ │ │ │ +│ │ Design Points: │ │ +│ │ • Configurable templates (user-customizable) │ │ +│ │ • Include few-shot examples (improve quality) │ │ +│ │ • Clear output format (JSON schema) │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ DecisionEngine - 决策引擎 │ │ +│ │ DecisionEngine - Decision Engine │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 职责: │ │ -│ │ • 判断何时需要调用 LLM(should_intervene) │ │ -│ │ • 协调 LLM 调用 │ │ -│ │ • 融合算法打分和 LLM 建议 │ │ -│ │ • 做出最终决策 │ │ -│ │ │ │ -│ │ 决策逻辑: │ │ +│ │ Responsibilities: │ │ +│ │ • Determine when to call LLM (should_intervene) │ │ +│ │ • Coordinate LLM calls │ │ +│ │ • Fuse algorithm scoring and LLM suggestions │ │ +│ │ • Make final decision │ │ +│ │ │ │ +│ │ Decision Logic: │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ │ │ │ should_intervene(state) -> bool │ │ │ │ │ │ │ │ │ -│ │ │ // 策略 1: 分叉路口 │ │ │ +│ │ │ // Strategy 1: Fork in road │ │ │ │ │ │ if candidates.len() > config.fork_threshold { return true } │ │ │ │ │ │ │ │ │ -│ │ │ // 策略 2: 算法不确定 │ │ │ +│ │ │ // Strategy 2: Algorithm uncertain │ │ │ │ │ │ if scores_are_close(candidates) { return true } │ │ │ │ │ │ │ │ │ -│ │ │ // 策略 3: 低置信度 │ │ │ +│ │ │ // Strategy 3: Low confidence │ │ │ │ │ │ if best_score < config.low_confidence_threshold { return true }│ │ │ │ │ │ │ │ -│ │ │ // 策略 4: 预算检查 │ │ │ +│ │ │ // Strategy 4: Budget check │ │ │ │ │ │ if budget_exhausted() { return false } │ │ │ │ │ │ │ │ │ │ │ │ return false │ │ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ -│ │ │ │ -│ │ 融合逻辑: │ │ +│ │ │ │ +│ │ Fusion Logic: │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ │ │ │ final_score = α * algo_score + β * llm_confidence │ │ │ │ │ │ │ │ │ -│ │ │ // α 和 β 根据场景动态调整 │ │ │ -│ │ │ // - LLM 高置信度时 β 更高 │ │ │ -│ │ │ // - 算法高分且 LLM 低置信度时 α 更高 │ │ │ +│ │ │ // α and β dynamically adjust based on scenario │ │ │ +│ │ │ // - Higher β when LLM confidence is high │ │ │ +│ │ │ // - Higher α when algorithm score is high and LLM confidence is low││ │ │ └─────────────────────────────────────────────────────────────┘ │ │ -│ │ │ │ +│ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ ResponseParser - 响应解析器 │ │ +│ │ ResponseParser - Response Parser │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 职责: │ │ -│ │ • 解析 LLM 返回的 JSON │ │ -│ │ • 处理格式错误 │ │ -│ │ • 提取结构化信息(ranked_candidates, direction, confidence) │ │ -│ │ • 验证响应有效性 │ │ -│ │ │ │ -│ │ 解析策略: │ │ +│ │ Responsibilities: │ │ +│ │ • Parse JSON returned by LLM │ │ +│ │ • Handle format errors │ │ +│ │ • Extract structured information (ranked_candidates, direction, confidence)│ +│ │ • Validate response effectiveness │ │ +│ │ │ │ +│ │ Parsing Strategy: │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ │ │ │ parse(response: String) -> Result │ │ │ │ │ │ │ │ │ -│ │ │ // 优先级 1: JSON 解析 │ │ │ +│ │ │ // Priority 1: JSON parsing │ │ │ │ │ │ if let Ok(json) = parse_json(response) { return json } │ │ │ │ │ │ │ │ │ -│ │ │ // 优先级 2: 正则提取 │ │ │ +│ │ │ // Priority 2: Regex extraction │ │ │ │ │ │ if let Some(data) = extract_by_regex(response) { return data }│ │ │ │ │ │ │ │ -│ │ │ // 优先级 3: 默认值 │ │ │ +│ │ │ // Priority 3: Default value │ │ │ │ │ │ return PilotDecision::default() │ │ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ -│ │ │ │ +│ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ BudgetController - 预算控制器 │ │ +│ │ BudgetController - Budget Controller │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 职责: │ │ -│ │ • 追踪 token 消耗 │ │ -│ │ • 控制 LLM 调用次数 │ │ -│ │ • 预估调用成本 │ │ -│ │ • 强制执行预算限制 -│ │ │ │ │ │ │ │ -│ │ 配置: │ │ +│ │ Responsibilities: │ │ +│ │ • Track token consumption │ │ +│ │ • Control LLM call frequency │ │ +│ │ • Estimate call cost │ │ +│ │ • Enforce budget limits │ │ +│ │ │ │ +│ │ Configuration: │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ │ │ │ BudgetConfig { │ │ │ -│ │ │ max_tokens_per_query: usize, // 单次检索总预算 │ │ │ -│ │ │ max_tokens_per_call: usize, // 单次调用预算 │ │ │ -│ │ │ max_calls_per_query: usize, // 最大调用次数 │ │ │ -│ │ │ max_calls_per_level: usize, // 每层最大调用 │ │ │ -│ │ │ hard_limit: bool, // 是否硬性限制 │ │ │ +│ │ │ max_tokens_per_query: usize, // Total budget per query│ │ │ +│ │ │ max_tokens_per_call: usize, // Budget per call │ │ │ +│ │ │ max_calls_per_query: usize, // Max calls per query │ │ │ +│ │ │ max_calls_per_level: usize, // Max calls per level │ │ │ +│ │ │ hard_limit: bool, // Whether hard limit │ │ │ │ │ │ } │ │ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ -│ │ 接口: │ │ +│ │ Interface: │ │ │ │ • can_call() -> bool │ │ │ │ • can_call_at_level(level) -> bool │ │ │ │ • estimate_cost(context) -> usize │ │ @@ -1070,151 +1072,149 @@ LLM 调用后: │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ FallbackManager - 降级管理器 │ │ +│ │ FallbackManager - Fallback Manager │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 职责: │ │ -│ │ • 处理 LLM 调用失败 │ │ -│ │ • 提供降级策略 │ │ -│ │ • 记录失败原因 │ │ -│ │ • 自动恢复机制 │ │ -│ │ │ │ -│ │ 降级层级: │ │ +│ │ Responsibilities: │ │ +│ │ • Handle LLM call failures │ │ +│ │ • Provide fallback strategies │ │ +│ │ • Record failure reasons │ │ +│ │ • Automatic recovery mechanism │ │ +│ │ │ │ +│ │ Fallback Levels: │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ -│ │ │ Level 0: 正常 LLM 调用 │ │ │ -│ │ │ ↓ 失败 │ │ │ -│ │ │ Level 1: 重试 (最多 3 次,指数退避) │ │ │ -│ │ │ ↓ 失败 │ │ │ -│ │ │ Level 2: 简化 prompt (减少上下文) │ │ │ -│ │ │ ↓ 失败 │ │ │ -│ │ │ Level 3: 纯算法模式 (完全降级) │ │ │ +│ │ │ Level 0: Normal LLM call │ │ │ +│ │ │ ↓ Failure │ │ │ +│ │ │ Level 1: Retry (max 3 times, exponential backoff) │ │ │ +│ │ │ ↓ Failure │ │ │ +│ │ │ Level 2: Simplify prompt (reduce context) │ │ │ +│ │ │ ↓ Failure │ │ │ +│ │ │ Level 3: Pure algorithm mode (complete fallback) │ │ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ -│ │ │ │ -│ │ 降级策略: │ │ +│ │ │ │ +│ │ Fallback Strategies: │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ │ │ │ enum FallbackStrategy { │ │ │ │ │ │ Retry { max_attempts: usize, backoff: BackoffPolicy }, │ │ │ -│ │ │ SimplifyContext, // 减少上下文信息 │ │ │ -│ │ │ UseAlgorithm, // 使用算法打分 │ │ │ -│ │ │ ReturnDefault, // 返回默认决策 │ │ │ +│ │ │ SimplifyContext, // Reduce context info │ │ │ +│ │ │ UseAlgorithm, // Use algorithm scoring │ │ │ +│ │ │ ReturnDefault, // Return default decision │ │ │ │ │ │ } │ │ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ -│ │ │ │ +│ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ PolicyManager - 策略管理器 │ │ +│ │ PolicyManager - Policy Manager │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 职责: │ │ -│ │ • 管理介入策略配置 │ │ -│ │ • 支持多种运行模式 │ │ -│ │ • 动态调整参数(可选) │ │ -│ │ │ │ -│ │ 策略模式: │ │ +│ │ Responsibilities: │ │ +│ │ • Manage intervention strategy configuration │ │ +│ │ • Support multiple operation modes │ │ +│ │ • Dynamic parameter adjustment (optional) │ │ +│ │ │ │ +│ │ Policy Modes: │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ │ │ │ enum PilotMode { │ │ │ -│ │ │ Aggressive, // 激进模式:频繁调用 LLM │ │ │ -│ │ │ Balanced, // 平衡模式:按需调用 (默认) │ │ │ -│ │ │ Conservative, // 保守模式:尽量少调用 │ │ │ -│ │ │ AlgorithmOnly,// 纯算法模式:不调用 LLM │ │ │ +│ │ │ Aggressive, // Aggressive mode: frequent LLM calls │ │ │ +│ │ │ Balanced, // Balanced mode: call as needed (default) │ │ │ +│ │ │ Conservative, // Conservative mode: minimize LLM calls │ │ │ +│ │ │ AlgorithmOnly,// Pure algorithm mode: no LLM calls │ │ │ │ │ │ } │ │ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ -│ │ │ │ -│ │ 参数调整: │ │ +│ │ │ │ +│ │ Parameter Adjustment: │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ -│ │ │ // 根据历史效果动态调整 │ │ │ -│ │ │ fn adjust_threshold(&mut self, performance: &PerformanceMetrics) {│ │ -│ │ │ // 如果 LLM 建议准确率高,降低介入阈值 │ │ │ +│ │ │ // Dynamic adjustment based on historical performance │ │ │ +│ │ │ fn adjust_threshold(&mut self, performance: &PerformanceMetrics) {│ +│ │ │ // If LLM suggestion accuracy is high, lower intervention threshold│ │ │ │ if performance.llm_accuracy > 0.8 { │ │ │ │ │ │ self.fork_threshold = 2; │ │ │ │ │ │ } │ │ │ │ │ │ } │ │ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ -│ │ │ │ -│ └─────────────────────────────────────────────────────────────────────┘ │ -│ │ +│ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ MetricsCollector - 指标收集器 │ │ +│ │ MetricsCollector - Metrics Collector │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ -│ │ 职责: │ │ -│ │ • 收集性能指标 │ │ -│ │ • 追踪 LLM 调用详情 │ │ -│ │ • 计算成本 │ │ -│ │ • 支持可观测性 │ │ -│ │ │ │ -│ │ 指标类型: │ │ +│ │ Responsibilities: │ │ +│ │ • Collect performance metrics │ │ +│ │ • Track LLM call details │ │ +│ │ • Calculate costs │ │ +│ │ • Support observability │ │ +│ │ │ │ +│ │ Metric Types: │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ │ │ │ PilotMetrics { │ │ │ -│ │ │ // 调用统计 │ │ │ +│ │ │ // Call statistics │ │ │ │ │ │ total_calls: usize, │ │ │ │ │ │ successful_calls: usize, │ │ │ │ │ │ failed_calls: usize, │ │ │ │ │ │ fallback_count: usize, │ │ │ │ │ │ │ │ │ -│ │ │ // Token 统计 │ │ │ +│ │ │ // Token statistics │ │ │ │ │ │ total_input_tokens: usize, │ │ │ │ │ │ total_output_tokens: usize, │ │ │ │ │ │ avg_tokens_per_call: f64, │ │ │ │ │ │ │ │ │ -│ │ │ // 延迟统计 │ │ │ +│ │ │ // Latency statistics │ │ │ │ │ │ total_latency_ms: u64, │ │ │ │ │ │ avg_latency_ms: f64, │ │ │ │ │ │ p50_latency_ms: u64, │ │ │ │ │ │ p99_latency_ms: u64, │ │ │ │ │ │ │ │ │ -│ │ │ // 效果统计 (需要反馈) │ │ │ -│ │ │ llm_decision_accuracy: Option, // LLM 决策准确率 │ │ │ -│ │ │ retrieval_precision: Option, // 检索准确率 │ │ │ +│ │ │ // Effectiveness statistics (requires feedback) │ │ │ +│ │ │ llm_decision_accuracy: Option, // LLM decision accuracy│ +│ │ │ retrieval_precision: Option, // Retrieval precision │ │ │ │ } │ │ │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ -│ │ │ │ +│ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` -### 5.2 Pilot 与 Algorithm 的协作 +### 5.2 Pilot and Algorithm Collaboration ``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Pilot 与 Algorithm 协作关系 │ +│ Pilot and Algorithm Collaboration │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 职责边界 │ │ +│ │ Responsibility Boundaries │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ │ │ │ │ -│ │ Pilot (大脑) Algorithm (手脚) │ │ +│ │ Pilot (Brain) Algorithm (Hands and Feet) │ │ │ │ ┌─────────────────────┐ ┌─────────────────────┐ │ │ -│ │ │ • 理解查询意图 │ │ • 执行树遍历 │ │ │ -│ │ │ • 分析文档结构 │ │ • 高效搜索路径 │ │ │ -│ │ │ • 语义判断 │ │ • 计算节点分数 │ │ │ -│ │ │ • 方向决策 │ │ • 管理搜索状态 │ │ │ -│ │ │ • 歧义消解 │ │ • 返回搜索结果 │ │ │ +│ │ │ • Understand query intent│ │ • Execute tree traversal │ │ +│ │ │ • Analyze document structure│ │ • Efficient search path │ │ +│ │ │ • Semantic judgment │ │ • Calculate node scores │ │ +│ │ │ • Direction decision │ │ • Manage search state │ │ +│ │ │ • Ambiguity resolution│ │ • Return search results │ │ │ │ └─────────────────────┘ └─────────────────────┘ │ │ │ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ 协作流程 │ │ +│ │ Collaboration Process │ │ │ ├─────────────────────────────────────────────────────────────────────┤ │ │ │ │ │ -│ │ 1. Algorithm 执行搜索 │ │ +│ │ 1. Algorithm executes search │ │ │ │ │ │ │ │ │ ▼ │ │ -│ │ 2. Algorithm 遇到决策点,询问 Pilot │ │ +│ │ 2. Algorithm encounters decision point, asks Pilot │ │ │ │ │ Pilot.should_intervene(state) │ │ │ │ ▼ │ │ -│ │ 3a. Pilot 返回 false → Algorithm 继续用自己的 scorer │ │ +│ │ 3a. Pilot returns false → Algorithm continues with its own scorer │ │ │ │ │ │ │ -│ │ 3b. Pilot 返回 true → Pilot.decide(state) │ │ +│ │ 3b. Pilot returns true → Pilot.decide(state) │ │ │ │ │ │ │ │ │ │ │ ▼ │ │ -│ │ │ Pilot 返回决策 → Algorithm 融合决策继续搜索 │ │ +│ │ │ Pilot returns decision → Algorithm fuses decision and continues search│ │ │ │ │ │ │ │ ▼ │ │ -│ │ 4. 重复直到搜索完成 │ │ +│ │ 4. Repeat until search completes │ │ │ │ │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ @@ -1223,145 +1223,146 @@ LLM 调用后: --- -## 6. Pilot 完整调用流程 +## 6. Complete Pilot Call Flow +``` ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Pilot 完整调用流程 │ +│ Complete Pilot Call Flow │ └─────────────────────────────────────────────────────────────────────────────┘ -用户查询: "如何配置 PostgreSQL 连接池的最大连接数?" +User Query: "How to configure max connections for PostgreSQL connection pool?" │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Step 1: QueryAnalyzer 分析查询 │ +│ Step 1: QueryAnalyzer analyzes query │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ QueryAnalysis { │ -│ complexity: Medium, // 中等复杂度 │ -│ keywords: ["PostgreSQL", "连接池", "最大连接数", "配置"], │ -│ intent: HowTo, // 操作指南类 │ -│ needs_pilot: true, // 需要 Pilot 介入 │ +│ complexity: Medium, // Medium complexity │ +│ keywords: ["PostgreSQL", "connection pool", "max connections", "configure"],│ +│ intent: HowTo, // How-To type │ +│ needs_pilot: true, // Needs Pilot intervention │ │ } │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Step 2: Pilot.guide_start() - 搜索前指导 │ +│ Step 2: Pilot.guide_start() - Pre-search guidance │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ BudgetController: 检查预算 (通过) │ +│ BudgetController: Check budget (pass) │ │ │ │ ContextBuilder: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ ToC View: │ │ -│ │ 1. 简介 │ │ -│ │ 2. 安装 │ │ -│ │ 3. 配置 │ │ -│ │ 3.1 基本配置 │ │ -│ │ 3.2 数据库配置 │ │ -│ │ 3.3 高级配置 │ │ -│ │ 4. API 参考 │ │ +│ │ 1. Introduction │ │ +│ │ 2. Installation │ │ +│ │ 3. Configuration │ │ +│ │ 3.1 Basic Config │ │ +│ │ 3.2 Database Config │ │ +│ │ 3.3 Advanced Config │ │ +│ │ 4. API Reference │ │ │ │ ... │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ PromptBuilder: 构建 START 场景 prompt │ +│ PromptBuilder: Build START scenario prompt │ │ │ │ LLM Response: │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ { │ │ -│ │ "entry_points": ["配置", "数据库配置"], │ │ -│ │ "reasoning": "查询关于数据库连接池配置,应从配置章节开始", │ │ +│ │ "entry_points": ["Configuration", "Database Config"], │ │ +│ │ "reasoning": "Query about database connection pool configuration, should start from Configuration chapter", │ │ │ "confidence": 0.9 │ │ │ │ } │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ MetricsCollector: 记录 (input: 150, output: 50, latency: 230ms) │ +│ MetricsCollector: Record (input: 150, output: 50, latency: 230ms) │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Step 3: BeamSearch 开始搜索 │ +│ Step 3: BeamSearch starts search │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ 迭代 1: Root → [简介, 安装, 配置, API, ...] │ +│ Iteration 1: Root → [Introduction, Installation, Configuration, API, ...] │ │ │ -│ Algorithm 打分: │ -│ "配置" -> 0.75 (关键词匹配) │ -│ "API" -> 0.35 │ -│ "安装" -> 0.10 │ +│ Algorithm scoring: │ +│ "Configuration" -> 0.75 (keyword match) │ +│ "API" -> 0.35 │ +│ "Installation" -> 0.10 │ │ │ │ Pilot.should_intervene(): │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ candidates.len() (6) > fork_threshold (3) → true │ │ -│ │ → 需要介入 │ │ +│ │ → Intervention needed │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ Pilot.decide(): │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ LLM 分析: │ │ -│ │ "查询明确指向配置相关内容,'配置'章节最相关" │ │ +│ │ LLM Analysis: │ │ +│ │ "Query clearly points to configuration-related content, 'Configuration' chapter most relevant" │ │ │ │ │ │ │ ranked_candidates: [ │ │ -│ │ ("配置", 0.95, "明确提到配置"), │ │ -│ │ ("API", 0.40, "可能有相关 API"), │ │ +│ │ ("Configuration", 0.95, "Explicitly mentions configuration"), │ │ +│ │ ("API", 0.40, "May have relevant API"), │ │ │ │ ] │ │ │ │ confidence: 0.9 │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ 融合打分: │ -│ "配置" -> 0.75*0.4 + 0.95*0.6*0.9 = 0.84 │ +│ Fusion scoring: │ +│ "Configuration" -> 0.75*0.4 + 0.95*0.6*0.9 = 0.84 │ │ │ -│ 选择: "配置" 节点深入 │ +│ Choice: Deep dive into "Configuration" node │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Step 4: 继续搜索 - 迭代 2 │ +│ Step 4: Continue search - Iteration 2 │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ 当前位置: Root → 配置 │ -│ 候选: [基本配置, 数据库配置, 高级配置, 性能调优] │ +│ Current position: Root → Configuration │ +│ Candidates: [Basic Config, Database Config, Advanced Config, Performance Tuning] │ │ │ -│ Algorithm 打分: │ -│ "数据库配置" -> 0.92 (强匹配!) │ -│ "高级配置" -> 0.45 │ +│ Algorithm scoring: │ +│ "Database Config" -> 0.92 (strong match!) │ +│ "Advanced Config" -> 0.45 │ │ │ │ Pilot.should_intervene(): │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ best_score (0.92) > low_score_threshold (0.3) → OK │ │ │ │ score_gap (0.47) > threshold (0.15) → OK │ │ -│ │ → 不需要介入,算法很确定 │ │ +│ │ → No intervention needed, algorithm is confident │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ -│ 直接使用算法打分,选择 "数据库配置" │ +│ Use algorithm score directly, choose "Database Config" │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Step 5: 继续搜索 - 迭代 3 │ +│ Step 5: Continue search - Iteration 3 │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ -│ 当前位置: Root → 配置 → 数据库配置 │ -│ 候选: [连接字符串, 连接池, 超时设置, SSL配置] │ +│ Current position: Root → Configuration → Database Config │ +│ Candidates: [Connection String, Connection Pool, Timeout Settings, SSL Config] │ │ │ -│ Algorithm 打分: │ -│ "连接池" -> 0.98 (完美匹配!) │ +│ Algorithm scoring: │ +│ "Connection Pool" -> 0.98 (perfect match!) │ │ │ -│ → 找到目标,搜索结束 │ +│ → Target found, search ends │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ -│ Step 6: 返回结果 │ +│ Step 6: Return result │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ SearchResult { │ -│ path: [Root → 配置 → 数据库配置 → 连接池], │ +│ path: [Root → Configuration → Database Config → Connection Pool], │ │ nodes_visited: 8, │ │ } │ │ │ @@ -1373,18 +1374,18 @@ LLM 调用后: │ } │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ +``` - -7. 代码结构 +## 7. Code Structure ``` src/retrieval/ ├── mod.rs -├── pilot/ # Pilot 模块 -│ ├── mod.rs # 模块入口 -│ ├── trait.rs # Pilot trait 定义 -│ ├── config.rs # 配置类型(PilotConfig, BudgetConfig, InterventionConfig) -│ ├── decision.rs # 决策类型(PilotDecision, SearchDirection) +├── pilot/ # Pilot module +│ ├── mod.rs # Module entry +│ ├── trait.rs # Pilot trait definition +│ ├── config.rs # Configuration types (PilotConfig, BudgetConfig, InterventionConfig) +│ ├── decision.rs # Decision types (PilotDecision, SearchDirection) │ ├── analyzer.rs # QueryAnalyzer │ ├── builder.rs # ContextBuilder │ ├── engine.rs # DecisionEngine @@ -1393,33 +1394,33 @@ src/retrieval/ │ ├── budget.rs # BudgetController │ ├── fallback.rs # FallbackManager │ ├── metrics.rs # MetricsCollector -│ ├── llm_pilot.rs # LlmPilot 实现 -│ ├── noop_pilot.rs # NoopPilot 实现(空实现,用于纯算法模式) -│ └── prompts/ # Prompt 模板 +│ ├── llm_pilot.rs # LlmPilot implementation +│ ├── noop_pilot.rs # NoopPilot implementation (empty impl, for pure algorithm mode) +│ └── prompts/ # Prompt templates │ ├── mod.rs -│ ├── start.rs # START 场景模板 -│ ├── fork.rs # FORK 场景模板 -│ ├── backtrack.rs # BACKTRACK 场景模板 -│ └── evaluate.rs # EVALUATE 场景模板 +│ ├── start.rs # START scenario template +│ ├── fork.rs # FORK scenario template +│ ├── backtrack.rs # BACKTRACK scenario template +│ └── evaluate.rs # EVALUATE scenario template ├── search/ │ ├── mod.rs -│ ├── trait.rs # SearchTree trait(修改:增加 pilot 参数) -│ ├── scorer.rs # NodeScorer(现有) -│ ├── beam.rs # BeamSearch(修改:集成 Pilot) -│ ├── greedy.rs # GreedySearch(修改:集成 Pilot) -│ └── mcts.rs # MctsSearch(修改:集成 Pilot) +│ ├── trait.rs # SearchTree trait (modified: add pilot parameter) +│ ├── scorer.rs # NodeScorer (existing) +│ ├── beam.rs # BeamSearch (modified: integrate Pilot) +│ ├── greedy.rs # GreedySearch (modified: integrate Pilot) +│ └── mcts.rs # MctsSearch (modified: integrate Pilot) ├── stages/ -│ ├── search.rs # SearchStage(修改:注入 Pilot) +│ ├── search.rs # SearchStage (modified: inject Pilot) │ └── ... └── ... ``` --- -## 7. 配置示例 +## 8. Configuration Examples ```rust -// 默认配置 +// Default configuration let config = PilotConfig { mode: PilotMode::Balanced, budget: BudgetConfig::default(), @@ -1429,7 +1430,7 @@ let config = PilotConfig { prompt_template_path: None, }; -// 高质量模式(更多 LLM 调用) +// High-quality mode (more LLM calls) let high_quality_config = PilotConfig { mode: PilotMode::Aggressive, budget: BudgetConfig { @@ -1450,7 +1451,7 @@ let high_quality_config = PilotConfig { prompt_template_path: None, }; -// 低成本模式(最少 LLM 调用) +// Low-cost mode (minimum LLM calls) let low_cost_config = PilotConfig { mode: PilotMode::Conservative, budget: BudgetConfig { @@ -1471,7 +1472,7 @@ let low_cost_config = PilotConfig { prompt_template_path: None, }; -// 纯算法模式(不调用 LLM) +// Pure algorithm mode (no LLM calls) let algorithm_only_config = PilotConfig { mode: PilotMode::AlgorithmOnly, ..Default::default() @@ -1480,25 +1481,25 @@ let algorithm_only_config = PilotConfig { --- -## 8. 使用示例 +## 9. Usage Example ```rust use vectorless::retrieval::pilot::{LlmPilot, PilotConfig, PilotMode}; use vectorless::retrieval::search::BeamSearch; use vectorless::llm::LlmClient; -// 创建 Pilot +// Create Pilot let llm_client = LlmClient::from_env()?; let pilot = LlmPilot::new(llm_client, PilotConfig::default()); -// 创建搜索引擎(注入 Pilot) +// Create search engine (inject Pilot) let search = BeamSearch::new().with_pilot(pilot); -// 执行搜索 +// Execute search let result = search.search(&tree, &context, &config).await?; -// 查看指标 +// View metrics println!("LLM calls: {}", result.metrics.llm_calls); println!("Tokens used: {}", result.metrics.tokens_used); println!("Avg latency: {}ms", result.metrics.avg_latency_ms); -``` +``` \ No newline at end of file diff --git a/docs/design/v2.md b/docs/design/v2.md deleted file mode 100644 index ec57596..0000000 --- a/docs/design/v2.md +++ /dev/null @@ -1,603 +0,0 @@ -┌─────────────────────────────────────────────────────────────────────────────┐ -│ Vectorless Library │ -├─────────────────────────────────────────────────────────────────────────────┤ -│ │ -│ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ client/ (用户入口) │ │ -│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────┐ │ │ -│ │ │ Vectorless │ │ Vectorless │ │ IndexOptions │ │ │ -│ │ │ (主客户端) │ │ Builder │ │ QueryOptions │ │ │ -│ │ └──────┬───────┘ └──────────────┘ └──────────────────────────┘ │ │ -│ └─────────┼───────────────────────────────────────────────────────────┘ │ -│ │ │ -│ ▼ │ -│ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ indexer/ (树构建) │ │ -│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────┐ │ │ -│ │ │ TreeBuilder │ │ Thinner │ │ Summarizer │ │ │ -│ │ │ (构建树) │ │ (节点裁剪) │ │ (生成 Summary) │ │ │ -│ │ └──────┬───────┘ └──────────────┘ └──────────────────────────┘ │ │ -│ └─────────┼───────────────────────────────────────────────────────────┘ │ -│ │ │ -│ ▼ │ -│ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ core/ (核心) │ │ -│ │ │ │ -│ │ ┌───────────────┐ ┌───────────────────────────────────────────┐ │ │ -│ │ │ VectorlessTree│ │ retriever/ (检索核心) │ │ │ -│ │ │ │ │ │ │ │ -│ │ │ • TreeNode │ │ ┌─────────────────────────────────────┐ │ │ │ -│ │ │ • ToC View │ │ │ AdaptiveRetriever (主入口) │ │ │ │ -│ │ │ • node_id map │ │ └──────────────┬──────────────────────┘ │ │ │ -│ │ └───────────────┘ │ │ │ │ │ -│ │ │ ┌────────────┼────────────┐ │ │ │ -│ │ │ ▼ ▼ ▼ │ │ │ -│ │ │ ┌──────┐ ┌──────────┐ ┌──────────┐ │ │ │ -│ │ │ │strategy│ │ search/ │ │sufficiency│ │ │ │ -│ │ │ │/ │ │ │ │ │ │ │ │ -│ │ │ └──────┘ └──────────┘ └──────────┘ │ │ │ -│ │ └───────────────────────────────────────┘ │ │ -│ └─────────────────────────────────────────────────────────────────────┘ │ -│ │ │ -│ ▼ │ -│ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ document/ (文档解析) │ │ -│ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │ -│ │ │ markdown/ │ │ pdf/ │ │ docx/ │ │ html/ │ │ │ -│ │ │ (已完成) │ │ (已完成) │ │ (已完成) │ │ (待实现) │ │ │ -│ │ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │ │ -│ └─────────────────────────────────────────────────────────────────────┘ │ -│ │ -│ ┌───────────────────────────┐ ┌───────────────────────────────────────┐ │ -│ │ llm/ (基础设施) │ │ storage/ (持久化) │ │ -│ │ ┌────────┐ ┌──────────┐ │ │ ┌────────┐ ┌────────────────────┐ │ │ -│ │ │ Client │ │ Pool │ │ │ │Workspace│ │ LRU Cache │ │ │ -│ │ └────────┘ └──────────┘ │ │ └────────┘ └────────────────────┘ │ │ -│ └───────────────────────────┘ └───────────────────────────────────────┘ │ -│ │ -│ ┌───────────────────────────┐ ┌───────────────────────────────────────┐ │ -│ │ config/ (配置) │ │ registry/ (注册) │ │ -│ │ ┌────────────────────┐ │ │ ┌────────┐ ┌────────┐ ┌──────────┐ │ │ -│ │ │ Config, Loader │ │ │ │Parser │ │Retriever│ │Summarizer│ │ │ -│ │ └────────────────────┘ │ │ └────────┘ └────────┘ └──────────┘ │ │ -│ └───────────────────────────┘ └───────────────────────────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────────────┘ - - - -core/ -├── mod.rs -├── error.rs -├── tree/ # 树结构 -│ ├── mod.rs -│ ├── node.rs # TreeNode 定义 -│ ├── tree.rs # VectorlessTree -│ └── toc.rs # ToC 视图生成 -│ -└── retriever/ # 🔑 检索核心 - ├── mod.rs - │ - ├── types.rs # 公共类型 - │ ├── RetrieveOptions - │ ├── RetrievalResult - │ ├── SufficiencyLevel - │ └── QueryComplexity - │ - ├── retriever.rs # Retriever trait - │ - ├── adaptive.rs # 🔑 自适应检索器 (主入口) - │ - ├── strategy/ # 检索策略 - │ ├── mod.rs - │ ├── trait.rs # RetrievalStrategy trait - │ ├── keyword.rs # 关键词策略 (快速) - │ ├── semantic.rs # 语义策略 - │ └── llm.rs # LLM 策略 (深度) - │ - ├── search/ # 搜索算法 - │ ├── mod.rs - │ ├── trait.rs # SearchAlgorithm trait - │ ├── scorer.rs # NodeScorer (打分) - │ ├── greedy.rs # 贪婪搜索 - │ ├── beam.rs # 🔑 Beam Search (多路径) - │ └── mcts.rs # MCTS (可选) - │ - ├── sufficiency/ # 充分性判断 - │ ├── mod.rs - │ ├── trait.rs # SufficiencyChecker trait - │ ├── threshold.rs # Token 阈值判断 - │ └── llm_judge.rs # LLM 判断 - │ - ├── complexity/ # 复杂度评估 - │ ├── mod.rs - │ └── detector.rs # ComplexityDetector - │ - └── cache/ # 缓存 (可选) - ├── mod.rs - └── path_cache.rs # 查询路径缓存 - - - -┌─────────────────────────────────────────────────────────────────────────────┐ -│ 检索主流程 │ -└─────────────────────────────────────────────────────────────────────────────┘ - -用户查询: "How does the LLM navigation work?" - │ - ▼ -┌─────────────────────┐ -│ AdaptiveRetriever │ -│ .retrieve() │ -└──────────┬──────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────────────────┐ -│ Step 1: 复杂度评估 │ -│ │ -│ ┌───────────────────────┐ │ -│ │ ComplexityDetector │ │ -│ │ │ │ -│ │ 输入: query │ │ -│ │ 输出: Simple | Medium | Complex │ -│ └───────────┬───────────┘ │ -│ │ │ -│ ▼ │ -│ 规则: │ -│ • 包含明确关键词 → Simple │ -│ • 需要跨章节综合 → Medium │ -│ • 需要"为什么/如何/比较" → Complex │ -└──────────────┼──────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────────────────┐ -│ Step 2: 策略选择 │ -│ │ -│ ┌──────────────┬──────────────┬──────────────┐ │ -│ │ │ │ │ │ -│ Simple Medium Complex │ │ -│ │ │ │ │ │ -│ ▼ ▼ ▼ │ │ -│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ -│ │ Keyword │ │ Semantic │ │ LLM │ │ │ -│ │ Strategy │ │ Strategy │ │ Strategy │ │ │ -│ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ │ -│ │ │ │ │ │ -└───────┼──────────────┼──────────────┼────────────────┼─────────────────────┘ - │ │ │ │ - └──────────────┴──────────────┴────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────────────────┐ -│ Step 3: 搜索执行 │ -│ │ -│ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ VectorlessTree │ │ -│ │ │ │ -│ │ ┌──────────┐ │ │ -│ │ │ Root │ │ │ -│ │ │ Summary │ │ │ -│ │ └────┬─────┘ │ │ -│ │ ┌──────────────┼──────────────┐ │ │ -│ │ ▼ ▼ ▼ │ │ -│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ -│ │ │ Section1 │ │ Section2 │ │ Section3 │ │ │ -│ │ │ Score:0.9│ │ Score:0.3│ │ Score:0.7│ │ │ -│ │ └────┬─────┘ └──────────┘ └──────────┘ │ │ -│ │ │ ↑ │ │ -│ │ ▼ │ │ │ -│ │ ┌──────────┐ │ │ │ -│ │ │ Sub 1.1 │───────────────┘ │ │ -│ │ │ Score:0.95│ │ │ -│ │ └──────────┘ │ │ -│ └─────────────────────────────────────────────────────────────────────┘ │ -│ │ -│ 搜索算法: │ -│ ┌────────────┐ ┌────────────────┐ ┌────────────────────────┐ │ -│ │ Greedy │ │ Beam Search │ │ MCTS (可选) │ │ -│ │ (单路径) │ │ (保留 top-k) │ │ (蒙特卡洛树搜索) │ │ -│ └────────────┘ └────────────────┘ └────────────────────────┘ │ -│ │ -└──────────────────────┬──────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────────────────┐ -│ Step 4: 增量检索 + 充分性判断 (Incremental + Sufficiency) │ -│ │ -│ ┌───────────────────────────────────────────────────────────────────────┐ │ -│ │ │ │ -│ │ ┌─────────┐ ┌─────────────┐ ┌─────────────────┐ │ │ -│ │ │ Node 1 │───►│ 提取内容 │───►│ SufficiencyCheck │ │ │ -│ │ │(score高)│ │ │ │ │ │ │ -│ │ └─────────┘ └─────────────┘ └────────┬────────┘ │ │ -│ │ │ │ │ -│ │ ┌────────┴────────┐ │ │ -│ │ │ │ │ │ -│ │ Sufficient Insufficient │ │ -│ │ │ │ │ │ -│ │ ▼ ▼ │ │ -│ │ ┌──────────┐ ┌─────────┐ │ │ -│ │ │ 返回结果 │ │ 继续检索│ │ │ -│ │ └──────────┘ └────┬────┘ │ │ -│ │ │ │ │ -│ │ ▼ │ │ -│ │ ┌─────────┐ │ │ -│ │ │ Node 2 │ │ │ -│ │ └─────────┘ │ │ -│ │ │ │ -│ └───────────────────────────────────────────────────────────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────────────────┐ -│ Step 5: 结果返回 │ -│ │ -│ RetrievalResult { │ -│ nodes: [NodeId, ...], // 相关节点 ID │ -│ content: String, // 聚合内容 │ -│ score: f32, // 总体置信度 │ -│ is_sufficient: bool, // 是否充分 │ -│ trace: [NavigationStep, ...], // 搜索路径 (可调试) │ -│ } │ -│ │ -└─────────────────────────────────────────────────────────────────────────────┘ - - - - - - - - - - - - - - -┌─────────────────────────────────────────────────────────────────────────────┐ -│ Beam Search (多路径并行探索) │ -└─────────────────────────────────────────────────────────────────────────────┘ - -配置: beam_width = 3 - -初始状态: -┌─────────────────────────────────────────────────────────────────────────────┐ -│ │ -│ ┌──────────┐ │ -│ │ Root │ │ -│ │ Query: ? │ │ -│ └────┬─────┘ │ -│ │ │ -│ ┌───────────────┼───────────────┐ │ -│ ▼ ▼ ▼ │ -│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ -│ │ Child A │ │ Child B │ │ Child C │ │ -│ │Score: 0.9│ │Score: 0.7│ │Score: 0.5│ │ -│ └──────────┘ └──────────┘ └──────────┘ │ -│ │ -│ 保留 top-3: [A(0.9), B(0.7), C(0.5)] │ -│ │ -└─────────────────────────────────────────────────────────────────────────────┘ - -第 1 轮展开: -┌─────────────────────────────────────────────────────────────────────────────┐ -│ │ -│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ -│ │ Child A │ │ Child B │ │ Child C │ │ -│ │ 0.9 │ │ 0.7 │ │ 0.5 │ │ -│ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ -│ │ │ │ │ -│ ┌────┴────┐ ┌────┴────┐ ┌────┴────┐ │ -│ ▼ ▼ ▼ ▼ ▼ ▼ │ -│ A1(0.95) A2(0.85) B1(0.75) B2(0.65) C1(0.55) C2(0.45) │ -│ │ -│ 所有候选: [A1(0.95), A2(0.85), B1(0.75), B2(0.65), C1(0.55), C2(0.45)] │ -│ 保留 top-3: [A1(0.95), A2(0.85), B1(0.75)] │ -│ │ -└─────────────────────────────────────────────────────────────────────────────┘ - -第 2 轮展开: -┌─────────────────────────────────────────────────────────────────────────────┐ -│ │ -│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ -│ │ A1 │ │ A2 │ │ B1 │ │ -│ │ 0.95 │ │ 0.85 │ │ 0.75 │ │ -│ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ -│ │ │ │ │ -│ ▼ ▼ ▼ │ -│ A1.1(0.97) A2.1(0.82) B1.1(0.72) │ -│ [LEAF] [LEAF] [LEAF] │ -│ │ -│ 最终结果: [A1.1, A2.1, B1.1] │ -│ │ -└─────────────────────────────────────────────────────────────────────────────┘ - -输出: -┌─────────────────────────────────────────────────────────────────────────────┐ -│ │ -│ RetrievalResult { │ -│ nodes: [A1.1, A2.1, B1.1], // 3 个叶节点 │ -│ content: "合并三个节点的内容...", │ -│ scores: [0.97, 0.82, 0.72], │ -│ paths: [ │ -│ Root → A → A1 → A1.1, │ -│ Root → A → A2 → A2.1, │ -│ Root → B → B1 → B1.1, │ -│ ] │ -│ } │ -│ │ -└─────────────────────────────────────────────────────────────────────────────┘ - - - -┌─────────────────────────────────────────────────────────────────────────────┐ -│ 自适应策略选择 │ -└─────────────────────────────────────────────────────────────────────────────┘ - -输入查询 - │ - ▼ -┌─────────────────────────────────────────────────────────────────────────────┐ -│ ComplexityDetector │ -│ │ -│ ┌───────────────────────────────────────────────────────────────────────┐ │ -│ │ 规则评估: │ │ -│ │ │ │ -│ │ 1. 关键词匹配 │ │ -│ │ query 包含文档中的精确术语? │ │ -│ │ → 是: Simple +0.3 │ │ -│ │ │ │ -│ │ 2. 问题类型 │ │ -│ │ "是什么/定义" → Simple +0.2 │ │ -│ │ "如何/为什么" → Complex +0.3 │ │ -│ │ "比较/区别" → Complex +0.4 │ │ -│ │ │ │ -│ │ 3. 问题长度 │ │ -│ │ < 10 词 → Simple +0.2 │ │ -│ │ > 30 词 → Complex +0.3 │ │ -│ │ │ │ -│ │ 4. 跨章节指示词 │ │ -│ │ "总结/概述/全部" → Complex +0.3 │ │ -│ │ │ │ -│ └───────────────────────────────────────────────────────────────────────┘ │ -│ │ -│ 最终得分: 0.0 - 1.0 │ -│ ┌────────────┬────────────────┬────────────────┐ │ -│ │ 0.0-0.4 │ 0.4-0.7 │ 0.7-1.0 │ │ -│ │ Simple │ Medium │ Complex │ │ -│ └────────────┴────────────────┴────────────────┘ │ -│ │ -└────────────────────────────────────┬────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────────────────┐ -│ 策略执行 │ -│ │ -│ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ Simple ──────────► KeywordStrategy │ │ -│ │ │ │ │ -│ │ ├─ 关键词匹配 │ │ -│ │ ├─ 快速返回 (< 50ms) │ │ -│ │ └─ 无 LLM 调用 │ │ -│ └─────────────────────────────────────────────────────────────────────┘ │ -│ │ -│ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ Medium ──────────► SemanticStrategy │ │ -│ │ │ │ │ -│ │ ├─ Embedding 相似度 │ │ -│ │ ├─ Value-based 节点评分 │ │ -│ │ └─ 可选 LLM 确认 │ │ -│ └─────────────────────────────────────────────────────────────────────┘ │ -│ │ -│ ┌─────────────────────────────────────────────────────────────────────┐ │ -│ │ Complex ─────────► LLMStrategy │ │ -│ │ │ │ │ -│ │ ├─ ToC 视图构建 │ │ -│ │ ├─ LLM 引导导航 │ │ -│ │ ├─ Beam Search (多路径) │ │ -│ │ └─ 充分性判断 │ │ -│ └─────────────────────────────────────────────────────────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────────────┘ - - - -┌─────────────────────────────────────────────────────────────────────────────┐ -│ 依赖关系 │ -└─────────────────────────────────────────────────────────────────────────────┘ - - ┌──────────────┐ - │ client/ │ - │ (用户入口) │ - └──────┬───────┘ - │ - ┌───────────────────┼───────────────────┐ - │ │ │ - ▼ ▼ ▼ - ┌──────────┐ ┌──────────┐ ┌──────────┐ - │ indexer/ │ │ retriever│ │ storage/ │ - │ │ │ (core/) │ │ │ - └────┬─────┘ └────┬─────┘ └──────────┘ - │ │ - │ ┌────────┴────────┐ - │ │ │ - ▼ ▼ ▼ - ┌────────────────┐ ┌──────────────┐ - │ core/tree │ │ llm/ │ - │ (VectorlessTree)│ │ (基础设施) │ - └────────┬───────┘ └──────────────┘ - │ - ▼ - ┌────────────────┐ - │ document/ │ - │ (文档解析) │ - └────────┬───────┘ - │ - ▼ - ┌────────────────┐ - │ config/ │ - │ (配置管理) │ - └────────────────┘ - -核心依赖链: -client → indexer → core/tree → document → config - ↓ - retriever → llm - ↓ - sufficiency → llm - - - - - - - - - - -┌─────────────────────────────────────────────────────────────────────────────┐ -│ Trait 体系 │ -└─────────────────────────────────────────────────────────────────────────────┘ - -/// 检索器主 trait -pub trait Retriever: Send + Sync { - fn retrieve( - &self, - tree: &VectorlessTree, - query: &str, - options: &RetrieveOptions, - ) -> impl Future>; -} - -/// 检索策略 trait -pub trait RetrievalStrategy: Send + Sync { - /// 策略名称 - fn name(&self) -> &str; - - /// 执行检索 - fn retrieve( - &self, - tree: &VectorlessTree, - query: &str, - options: &RetrieveOptions, - ) -> impl Future>>; - - /// 是否需要 LLM - fn requires_llm(&self) -> bool; -} - -/// 搜索算法 trait -pub trait SearchAlgorithm: Send + Sync { - /// 搜索相关节点 - fn search( - &self, - tree: &VectorlessTree, - query: &str, - scorer: &dyn NodeScorer, - options: &SearchOptions, - ) -> Vec; -} - -/// 节点评分器 trait -pub trait NodeScorer: Send + Sync { - /// 计算节点相关性分数 (0.0 - 1.0) - fn score(&self, node: &TreeNode, query: &str) -> f32; -} - -/// 充分性判断 trait -pub trait SufficiencyChecker: Send + Sync { - /// 判断当前内容是否足够回答问题 - fn check( - &self, - content: &str, - query: &str, - ) -> impl Future; -} - -/// 复杂度检测器 trait -pub trait ComplexityDetector: Send + Sync { - /// 检测查询复杂度 - fn detect(&self, query: &str, tree: &VectorlessTree) -> QueryComplexity; -} - - - - - -┌─────────────────────────────────────────────────────────────────────────────┐ -│ 核心类型 │ -└─────────────────────────────────────────────────────────────────────────────┘ - -// ==================== 查询复杂度 ==================== -pub enum QueryComplexity { - Simple, // 关键词可解 - Medium, // 需要语义理解 - Complex, // 需要 LLM 深度推理 -} - -// ==================== 检索选项 ==================== -pub struct RetrieveOptions { - pub top_k: usize, // 返回节点数 - pub beam_width: usize, // Beam Search 宽度 - pub max_iterations: usize, // 最大迭代次数 - pub include_content: bool, // 包含内容 - pub include_summaries: bool, // 包含摘要 - pub strategy: StrategyPreference, // 策略偏好 - pub sufficiency_check: bool, // 启用充分性判断 -} - -pub enum StrategyPreference { - Auto, // 自适应选择 - ForceKeyword, // 强制关键词 - ForceSemantic, // 强制语义 - ForceLlm, // 强制 LLM -} - -// ==================== 检索结果 ==================== -pub struct RetrievalResult { - pub nodes: Vec, // 相关节点 - pub content: String, // 聚合内容 - pub score: f32, // 总体置信度 - pub is_sufficient: bool, // 是否充分 - pub strategy_used: String, // 使用的策略 - pub trace: Vec, // 搜索路径 - pub tokens_used: usize, // Token 消耗 -} - -pub struct NavigationStep { - pub node_id: NodeId, - pub node_title: String, - pub score: f32, - pub decision: NavigationDecision, - pub depth: usize, -} - -// ==================== 充分性级别 ==================== -pub enum SufficiencyLevel { - Sufficient, // 足够,停止 - PartialSufficient, // 部分足够,可继续 - Insufficient, // 不足够,继续 -} - -// ==================== 搜索路径 ==================== -pub struct SearchPath { - pub nodes: Vec, // 路径上的节点 - pub score: f32, // 路径总分 - pub leaf: NodeId, // 叶节点 -} - - - - - - - - - - - - - - diff --git a/docs/design/v3.md b/docs/design/v3(legacy).md similarity index 65% rename from docs/design/v3.md rename to docs/design/v3(legacy).md index df575a7..11bf4f5 100644 --- a/docs/design/v3.md +++ b/docs/design/v3(legacy).md @@ -1,25 +1,29 @@ -# V3 Design: LLM Navigator + Algorithm 协同检索 +# V3 Design: LLM Navigator + Algorithm Collaborative Retrieval -## 🏗️ 架构设计:LLM + 算法协同的 Retriever Pipeline +## 🏗️ Architecture Design: LLM + Algorithm Collaborative Retriever Pipeline -### 核心设计原则 +### Core Design Principles ``` ┌─────────────────────────────────────────────────────────────────┐ -│ 设计哲学 │ +│ Design Philosophy │ ├─────────────────────────────────────────────────────────────────┤ -│ 1. 算法负责 "怎么走" - 高效、确定性、低延迟 │ -│ 2. LLM 负责 "去哪里" - 语义理解、歧义消解、方向判断 │ -│ 3. 关键决策点介入 - 不是每步都问 LLM,而是在需要时才问 │ -│ 4. 分层 fallback - LLM 失败时算法接管,算法失败时 LLM 救援 │ +│ 1. Algorithm handles "how to go" - efficient, deterministic, │ +│ low latency │ +│ 2. LLM handles "where to go" - semantic understanding, │ +│ ambiguity resolution, direction judgment │ +│ 3. Intervene at key decision points - not every step asks LLM, │ +│ only when needed │ +│ 4. Layered fallback - algorithm takes over when LLM fails, │ +│ LLM rescues when algorithm fails │ └─────────────────────────────────────────────────────────────────┘ ``` -### 整体架构 +### Overall Architecture ``` ┌─────────────────────────────────────────────────────────────────────────┐ -│ Index Pipeline (不变) │ +│ Index Pipeline (Unchanged) │ │ Parse → Build → Enhance → Enrich(LLM) → Optimize │ └─────────────────────────────────────────────────────────────────────────┘ │ @@ -31,7 +35,7 @@ │ ▼ ┌─────────────────────────────────────────────────────────────────────────┐ -│ Retrieval Pipeline (增强) │ +│ Retrieval Pipeline (Enhanced) │ │ │ │ ┌─────────┐ ┌─────────┐ ┌─────────────────────┐ ┌─────────┐ │ │ │ Analyze │───▶│ Plan │───▶│ Search │───▶│ Judge │ │ @@ -42,7 +46,7 @@ │ ▼ ▼ │ │ │ Algorithm │ │ │ ▼ │ │ ┌─────────────────────────┐ │ │ └───────────┘ │ │ ┌───────────┐ │ │ │ LLM Navigator │◀──┼──┤ │ │ │ NeedMore │ │ -│ │ (关键决策点介入) │ │ │ Search Alg │ │ │ ◀───────│ │ +│ │ (Key Decision Points) │ │ │ Search Alg │ │ │ ◀───────│ │ │ └─────────────────────────┘ │ │ (Greedy/Beam)│ │ └───────────┘ │ │ │ │ └───────────────┘ │ │ │ │ └──────────────────┴─────────────────────┘ │ │ @@ -55,85 +59,94 @@ --- -## 🧭 LLM Navigator 设计 +## 🧭 LLM Navigator Design -### Navigator 的职责 +### Navigator Responsibilities -Navigator 不是替代 Search 算法,而是**在关键决策点提供语义判断**: +Navigator doesn't replace the Search algorithm, but **provides semantic judgment at key decision points**: ``` ┌────────────────────────────────────────────────────────────┐ -│ LLM Navigator 职责 │ +│ LLM Navigator Responsibilities │ ├────────────────┬───────────────────────────────────────────┤ -│ 时机 │ LLM 任务 │ +│ Timing │ LLM Task │ ├────────────────┼───────────────────────────────────────────┤ -│ 搜索开始前 │ 理解 query,确定搜索起点和优先方向 │ -│ 分叉路口 │ 多个候选路径时,判断哪个更相关 │ -│ 迷路时 │ 算法陷入低分路径时,提供纠正建议 │ -│ 不确定时 │ 算法评分接近时,做语义判断 │ -│ 回溯时 │ 分析失败原因,建议新的搜索方向 │ +│ Before search │ Understand query, determine search │ +│ starts │ starting point and priority directions │ +├────────────────┼───────────────────────────────────────────┤ +│ At fork/branch │ When multiple candidate paths exist, │ +│ points │ judge which is more relevant │ +├────────────────┼───────────────────────────────────────────┤ +│ When lost │ When algorithm is stuck in low-score │ +│ │ paths, provide correction suggestions │ +├────────────────┼───────────────────────────────────────────┤ +│ When uncertain │ When algorithm scores are close, │ +│ │ make semantic judgments │ +├────────────────┼───────────────────────────────────────────┤ +│ When │ Analyze failure reasons, suggest new │ +│ backtracking │ search directions │ └────────────────┴───────────────────────────────────────────┘ ``` -### Navigator 接口设计 +### Navigator Interface Design ```rust -/// LLM Navigator - 在关键决策点提供语义导航 +/// LLM Navigator - Provides semantic navigation at key decision points pub struct LlmNavigator { client: LlmClient, config: NavigatorConfig, } -/// Navigator 配置 +/// Navigator Configuration pub struct NavigatorConfig { - /// 是否在搜索开始前介入 + /// Whether to intervene before search starts pub guide_at_start: bool, - /// 是否在分叉路口介入 (候选数 > threshold 时) + /// Whether to intervene at fork points (when candidates > threshold) pub guide_at_fork: bool, - /// 分叉路口阈值 + /// Fork point threshold pub fork_threshold: usize, - /// 是否在回溯时介入 + /// Whether to intervene during backtracking pub guide_at_backtrack: bool, - /// 低分阈值 (低于此值时请求 LLM 干预) + /// Low score threshold (request LLM intervention when below this value) pub low_score_threshold: f32, - /// 最大 LLM 调用次数 (控制成本) + /// Maximum LLM calls (cost control) pub max_llm_calls: usize, } -/// 导航建议 +/// Navigation Guidance pub struct NavigationGuidance { - /// 推荐的节点顺序 (按相关性排序) + /// Recommended node order (sorted by relevance) pub preferred_order: Vec, - /// 推荐的搜索方向 + /// Recommended search direction pub direction: SearchDirection, - /// LLM 的推理过程 (可解释性) + /// LLM's reasoning process (explainability) pub reasoning: String, - /// 置信度 + /// Confidence level pub confidence: f32, } pub enum SearchDirection { - /// 深入当前分支 + /// Go deeper into current branch GoDeeper, - /// 探索兄弟节点 + /// Explore sibling nodes ExploreSiblings, - /// 回溯到父节点 + /// Backtrack to parent node Backtrack, - /// 跳转到特定节点 + /// Jump to a specific node JumpTo(NodeId), - /// 当前路径就是答案 + /// Current path is the answer ThisIsIt, } impl LlmNavigator { - /// 搜索开始前:理解 query,确定起点 + /// Before search starts: Understand query, determine starting point pub async fn guide_start( &self, tree: &DocumentTree, query: &str, ) -> Result; - /// 分叉路口:选择最佳分支 + /// At fork point: Choose the best branch pub async fn guide_fork( &self, tree: &DocumentTree, @@ -142,7 +155,7 @@ impl LlmNavigator { query: &str, ) -> Result; - /// 回溯时:分析失败,建议新方向 + /// During backtracking: Analyze failure, suggest new direction pub async fn guide_backtrack( &self, tree: &DocumentTree, @@ -155,28 +168,28 @@ impl LlmNavigator { --- -## 🔄 Search 阶段集成方案 +## 🔄 Search Stage Integration Plan -### 新的 Search 架构 +### New Search Architecture ```rust -/// 增强 Search 阶段 - 算法 + LLM 协同 +/// Enhanced Search Stage - Algorithm + LLM Collaboration pub struct SearchStage { - /// 搜索算法 + /// Search algorithm algorithm: SearchAlgorithm, - /// LLM Navigator (可选) + /// LLM Navigator (optional) navigator: Option>, - /// 配置 + /// Configuration config: SearchConfig, } -/// 协同搜索器 +/// Collaborative Searcher pub struct CollaborativeSearch { - /// 底层搜索算法 + /// Underlying search algorithm algorithm: Box, /// LLM Navigator navigator: LlmNavigator, - /// 调用统计 + /// Call statistics stats: SearchStats, } @@ -185,18 +198,18 @@ impl CollaborativeSearch { let mut result = SearchResult::default(); let mut state = SearchState::new(tree.root()); - // 1. 开始前:LLM 指导起点 + // 1. Before starting: LLM guides starting point if self.navigator.config.guide_at_start { let guidance = self.navigator.guide_start(tree, &ctx.query).await?; state.apply_guidance(guidance); } - // 2. 搜索循环 + // 2. Search loop while !state.is_complete() { - // 2.1 算法选择候选 + // 2.1 Algorithm selects candidates let candidates = self.algorithm.select_candidates(tree, &state); - // 2.2 判断是否需要 LLM 介入 + // 2.2 Determine if LLM consultation is needed if self.should_consult_llm(&candidates, &state) { let guidance = self.navigator.guide_fork( tree, @@ -205,17 +218,17 @@ impl CollaborativeSearch { &ctx.query ).await?; - // 2.3 用 LLM 建议重排序候选 + // 2.3 Re-rank candidates using LLM suggestions state.candidates = self.merge_algorithm_and_llm( candidates, guidance ); } - // 2.4 算法执行下一步 + // 2.4 Algorithm executes next step self.algorithm.step(tree, &mut state); - // 2.5 检查是否需要回溯 + // 2.5 Check if backtracking is needed if state.needs_backtrack() { if self.navigator.config.guide_at_backtrack { let guidance = self.navigator.guide_backtrack( @@ -236,24 +249,24 @@ impl CollaborativeSearch { result } - /// 判断是否需要咨询 LLM + /// Determine whether to consult LLM fn should_consult_llm(&self, candidates: &[NodeId], state: &SearchState) -> bool { - // 条件 1: 候选数量超过阈值 (分叉路口) + // Condition 1: Candidate count exceeds threshold (fork point) if candidates.len() > self.navigator.config.fork_threshold { return true; } - // 条件 2: 候选分数接近 (算法无法区分) + // Condition 2: Candidate scores are close (algorithm cannot distinguish) if self.scores_are_close(candidates) { return true; } - // 条件 3: 当前分数过低 (可能走错方向) + // Condition 3: Current score is too low (might be wrong direction) if state.best_score < self.navigator.config.low_score_threshold { return true; } - // 条件 4: 未超过 LLM 调用限制 + // Condition 4: Haven't exceeded LLM call limit self.stats.llm_calls < self.navigator.config.max_llm_calls } } @@ -261,7 +274,7 @@ impl CollaborativeSearch { --- -## 📊 Pipeline 各阶段的 LLM 介入点 +## 📊 LLM Intervention Points in Pipeline Stages ``` ┌─────────────────────────────────────────────────────────────────────────┐ @@ -270,15 +283,17 @@ impl CollaborativeSearch { │ │ │ Analyze Stage │ │ ┌─────────────────────────────────────────────────────────────────┐ │ -│ │ [算法] 关键词提取、复杂度估计 │ │ -│ │ [LLM] 可选:深度语义分析、意图识别 │ │ +│ │ [Algorithm] Keyword extraction, complexity estimation │ │ +│ │ [LLM] Optional: Deep semantic analysis, intent detection │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ Plan Stage │ │ ┌─────────────────────────────────────────────────────────────────┐ │ -│ │ [算法] 根据复杂度选择策略 (keyword/llm/semantic) │ │ -│ │ [LLM] 可选:复杂查询的策略推荐 │ │ +│ │ [Algorithm] Select strategy based on complexity │ │ +│ │ (keyword/llm/semantic) │ │ +│ │ [LLM] Optional: Strategy recommendation for complex │ │ +│ │ queries │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ @@ -287,10 +302,10 @@ impl CollaborativeSearch { │ │ │ │ │ │ ┌─────────────┐ ┌─────────────────────────────────────┐ │ │ │ │ │ Algorithm │────▶│ LLM Navigator │ │ │ -│ │ │ (主控) │ │ ┌─────────────────────────────┐ │ │ │ -│ │ │ │ │ │ guide_start() 开始指导 │ │ │ │ -│ │ │ - Greedy │◀───▶│ │ guide_fork() 分叉选择 │ │ │ │ -│ │ │ - Beam │ │ │ guide_backtrack()回溯指导 │ │ │ │ +│ │ │ (Primary) │ │ ┌─────────────────────────────┐ │ │ │ +│ │ │ │ │ │ guide_start() Start guide │ │ │ │ +│ │ │ - Greedy │◀───▶│ │ guide_fork() Fork choice │ │ │ │ +│ │ │ - Beam │ │ │ guide_backtrack()Backtrack │ │ │ │ │ │ │ - MCTS │ │ └─────────────────────────────┘ │ │ │ │ │ │ │ │ │ │ │ │ │ └─────────────┘ └─────────────────────────────────────┘ │ │ @@ -300,8 +315,9 @@ impl CollaborativeSearch { │ ▼ │ │ Judge Stage │ │ ┌─────────────────────────────────────────────────────────────────┐ │ -│ │ [算法] Token 数量检查、阈值判断 │ │ -│ │ [LLM] 内容充分性判断、答案完整性评估 │ │ +│ │ [Algorithm] Token count check, threshold judgment │ │ +│ │ [LLM] Content sufficiency judgment, answer completeness │ │ +│ │ evaluation │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ @@ -318,46 +334,47 @@ impl CollaborativeSearch { --- -## 🎯 实施方案 +## 🎯 Implementation Plan -### 阶段一:基础集成 (1-2 周) +### Phase 1: Basic Integration (1-2 weeks) ```rust -// 1. 定义 Navigator trait 和基础实现 +// 1. Define Navigator trait and basic implementation pub trait Navigator: Send + Sync { async fn guide_fork(&self, ctx: &NavigationContext) -> NavigationGuidance; } -// 2. 在 SearchStage 中集成 +// 2. Integrate into SearchStage pub struct SearchStage { algorithm: SearchAlgorithm, - navigator: Option>, // 新增 + navigator: Option>, // New } -// 3. 修改搜索循环,在分叉点调用 navigator +// 3. Modify search loop to call navigator at fork points ``` -### 阶段二:增强能力 (2-3 周) +### Phase 2: Enhanced Capabilities (2-3 weeks) ```rust -// 1. 实现完整的 LlmNavigator -// 2. 添加 guide_start, guide_backtrack -// 3. 实现智能介入判断逻辑 -// 4. 添加缓存 (相同 query + 相同上下文 → 缓存结果) +// 1. Implement complete LlmNavigator +// 2. Add guide_start, guide_backtrack +// 3. Implement intelligent intervention judgment logic +// 4. Add caching (same query + same context → cached result) ``` -### 阶段三:优化与监控 (1-2 周) +### Phase 3: Optimization and Monitoring (1-2 weeks) ```rust -// 1. 添加 A/B 测试能力 (纯算法 vs 算法+LLM) -// 2. 添加成本控制 (max_llm_calls, budget) -// 3. 添加效果监控 (检索准确率、延迟、成本) -// 4. 自适应介入 (根据历史效果动态调整介入频率) +// 1. Add A/B testing capability (pure algorithm vs algorithm+LLM) +// 2. Add cost control (max_llm_calls, budget) +// 3. Add effectiveness monitoring (retrieval accuracy, latency, cost) +// 4. Adaptive intervention (dynamically adjust intervention frequency +// based on historical effectiveness) ``` --- -## 📁 代码结构建议 +## 📁 Suggested Code Structure ``` src/retrieval/ @@ -370,7 +387,7 @@ src/retrieval/ ├── stages/ │ ├── analyze.rs │ ├── plan.rs -│ ├── search.rs # 集成 Navigator +│ ├── search.rs # Integrate Navigator │ └── judge.rs ├── search/ │ ├── mod.rs @@ -378,12 +395,12 @@ src/retrieval/ │ ├── greedy.rs │ ├── beam.rs │ └── mcts.rs -├── navigator/ # 新增模块 +├── navigator/ # New module │ ├── mod.rs │ ├── trait.rs # Navigator trait -│ ├── llm_navigator.rs # LLM 实现 -│ ├── noop_navigator.rs # 空实现 -│ ├── guidance.rs # NavigationGuidance 类型 +│ ├── llm_navigator.rs # LLM implementation +│ ├── noop_navigator.rs # No-op implementation +│ ├── guidance.rs # NavigationGuidance types │ └── config.rs # NavigatorConfig ├── strategy/ │ ├── mod.rs @@ -394,43 +411,43 @@ src/retrieval/ --- -## 🤔 几个关键问题 +## 🤔 Key Questions -### Q1: Navigator 和 Strategy 的区别? +### Q1: Difference between Navigator and Strategy? -| | Strategy | Navigator | -|---|----------|-----------| -| 粒度 | 单节点评估 | 全局导航建议 | -| 输入 | 单个节点信息 | 路径 + 候选 + 上下文 | -| 输出 | 分数 (0-1) | 方向 + 排序 + 推理 | -| 调用频率 | 每个候选节点 | 关键决策点 | +| | Strategy | Navigator | +|--------------------|-----------------------------|--------------------------------| +| Granularity | Single node evaluation | Global navigation suggestion | +| Input | Single node information | Path + candidates + context | +| Output | Score (0-1) | Direction + ranking + reasoning| +| Call frequency | Every candidate node | Key decision points | -### Q2: 如何控制 LLM 调用成本? +### Q2: How to control LLM call costs? ```rust pub struct CostControl { - /// 单次检索最大 LLM 调用 + /// Maximum LLM calls per retrieval max_calls_per_query: usize, - /// 每日预算 + /// Daily budget daily_budget: Option, - /// 低置信度时才调用 + /// Only call when confidence is low min_uncertainty: f32, } ``` -### Q3: 如何评估效果? +### Q3: How to evaluate effectiveness? ```rust pub struct RetrievalMetrics { - /// 检索准确率 + /// Retrieval precision pub precision: f32, - /// 检索召回率 + /// Retrieval recall pub recall: f32, - /// LLM 调用次数 + /// LLM call count pub llm_calls: usize, - /// 总延迟 + /// Total latency pub latency_ms: u64, - /// 成本 + /// Cost pub cost: Money, } ``` diff --git a/src/config/docs.rs b/src/config/docs.rs index 3a0fe06..0a1447d 100644 --- a/src/config/docs.rs +++ b/src/config/docs.rs @@ -38,44 +38,83 @@ impl ConfigDocs { md.push_str("- `./config.toml`\n"); md.push_str("- `./.vectorless.toml`\n\n"); - // Indexer section - md.push_str("## `[indexer]`\n\n"); - md.push_str("Controls document indexing behavior.\n\n"); + // LLM section (unified) + md.push_str("## `[llm]`\n\n"); + md.push_str("Unified LLM configuration for all LLM operations.\n\n"); md.push_str("| Option | Type | Default | Description |\n"); md.push_str("|--------|------|---------|-------------|\n"); self.add_row( &mut md, - "subsection_threshold", - "usize", - "300", - "Word count threshold for splitting sections into subsections", + "api_key", + "string?", + "null", + "Default API key (used by all clients unless overridden)", ); + md.push_str("\n"); + + // LLM.summary section + md.push_str("## `[llm.summary]`\n\n"); + md.push_str("Summary client - generates document summaries during indexing.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); self.add_row( &mut md, - "max_segment_tokens", - "usize", - "3000", - "Maximum tokens to send in a single segmentation request", + "model", + "string", + "gpt-4o-mini", + "Model for summarization (fast, cheap model recommended)", ); self.add_row( &mut md, - "max_summary_tokens", - "usize", - "200", - "Maximum tokens for each summary", + "endpoint", + "string", + "https://api.openai.com/v1", + "API endpoint", ); self.add_row( &mut md, - "min_summary_tokens", - "usize", - "20", - "Minimum content tokens required to generate a summary", + "api_key", + "string?", + "null", + "API key (optional, uses default if not set)", + ); + self.add_row(&mut md, "max_tokens", "usize", "200", "Maximum tokens for summary"); + self.add_row(&mut md, "temperature", "f32", "0.0", "Temperature for generation"); + md.push_str("\n"); + + // LLM.retrieval section + md.push_str("## `[llm.retrieval]`\n\n"); + md.push_str("Retrieval client - used for retrieval decisions and content evaluation.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row( + &mut md, + "model", + "string", + "gpt-4o", + "Model for retrieval (more capable model recommended)", + ); + self.add_row( + &mut md, + "endpoint", + "string", + "https://api.openai.com/v1", + "API endpoint", + ); + self.add_row( + &mut md, + "api_key", + "string?", + "null", + "API key (optional, uses default if not set)", ); + self.add_row(&mut md, "max_tokens", "usize", "100", "Maximum tokens for response"); + self.add_row(&mut md, "temperature", "f32", "0.0", "Temperature for generation"); md.push_str("\n"); - // Summary section - md.push_str("## `[summary]`\n\n"); - md.push_str("LLM configuration for summary generation.\n\n"); + // LLM.pilot section + md.push_str("## `[llm.pilot]`\n\n"); + md.push_str("Pilot client - used for intelligent navigation guidance.\n\n"); md.push_str("| Option | Type | Default | Description |\n"); md.push_str("|--------|------|---------|-------------|\n"); self.add_row( @@ -83,7 +122,7 @@ impl ConfigDocs { "model", "string", "gpt-4o-mini", - "Model for summarization", + "Model for pilot navigation (fast model recommended)", ); self.add_row( &mut md, @@ -97,85 +136,369 @@ impl ConfigDocs { "api_key", "string?", "null", - "API key (optional, can use env var)", + "API key (optional, uses default if not set)", ); + self.add_row(&mut md, "max_tokens", "usize", "300", "Maximum tokens for response"); + self.add_row(&mut md, "temperature", "f32", "0.0", "Temperature for generation"); + md.push_str("\n"); + + // LLM.retry section + md.push_str("## `[llm.retry]`\n\n"); + md.push_str("Retry configuration for all LLM calls.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row(&mut md, "max_attempts", "usize", "3", "Maximum retry attempts"); self.add_row( &mut md, - "max_tokens", + "initial_delay_ms", + "u64", + "500", + "Initial delay before first retry (ms)", + ); + self.add_row( + &mut md, + "max_delay_ms", + "u64", + "30000", + "Maximum delay between retries (ms)", + ); + self.add_row( + &mut md, + "multiplier", + "f64", + "2.0", + "Multiplier for exponential backoff", + ); + self.add_row( + &mut md, + "retry_on_rate_limit", + "bool", + "true", + "Whether to retry on rate limit errors", + ); + md.push_str("\n"); + + // LLM.throttle section + md.push_str("## `[llm.throttle]`\n\n"); + md.push_str("Throttle/rate limiting configuration for all LLM calls.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row( + &mut md, + "max_concurrent_requests", "usize", - "200", - "Maximum tokens for summary generation", + "10", + "Maximum concurrent LLM API calls", ); self.add_row( &mut md, - "temperature", - "f32", - "0.0", - "Temperature for summary generation", + "requests_per_minute", + "usize", + "500", + "Rate limit: requests per minute", + ); + self.add_row(&mut md, "enabled", "bool", "true", "Enable rate limiting"); + self.add_row( + &mut md, + "semaphore_enabled", + "bool", + "true", + "Enable semaphore-based concurrency", ); md.push_str("\n"); - // Retrieval section - md.push_str("## `[retrieval]`\n\n"); - md.push_str("Retrieval model and behavior configuration.\n\n"); + // LLM.fallback section + md.push_str("## `[llm.fallback]`\n\n"); + md.push_str("Fallback configuration for all LLM calls.\n\n"); md.push_str("| Option | Type | Default | Description |\n"); md.push_str("|--------|------|---------|-------------|\n"); self.add_row( &mut md, - "model", + "enabled", + "bool", + "true", + "Enable fallback mechanism", + ); + self.add_row( + &mut md, + "models", + "[string]", + "[\"gpt-4o-mini\", \"glm-4-flash\"]", + "Fallback models in priority order", + ); + self.add_row( + &mut md, + "endpoints", + "[string]", + "[]", + "Fallback endpoints in priority order", + ); + self.add_row( + &mut md, + "on_rate_limit", "string", - "gpt-4o", - "Model for retrieval navigation", + "retry_then_fallback", + "Behavior on rate limit (retry, fallback, retry_then_fallback, fail)", ); self.add_row( &mut md, - "endpoint", + "on_timeout", "string", - "https://api.openai.com/v1", - "API endpoint", + "retry_then_fallback", + "Behavior on timeout", ); self.add_row( &mut md, - "api_key", - "string?", - "null", - "API key (defaults to summary.api_key)", + "on_all_failed", + "string", + "return_error", + "Behavior when all attempts fail (return_error, return_cache)", + ); + md.push_str("\n"); + + // Metrics section + md.push_str("## `[metrics]`\n\n"); + md.push_str("Unified metrics configuration for observability.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row(&mut md, "enabled", "bool", "true", "Enable metrics collection"); + self.add_row( + &mut md, + "storage_path", + "string", + "./workspace/metrics", + "Storage path for persisted metrics", + ); + self.add_row( + &mut md, + "retention_days", + "usize", + "30", + "Retention period in days", + ); + md.push_str("\n"); + + // Metrics.llm section + md.push_str("## `[metrics.llm]`\n\n"); + md.push_str("LLM-specific metrics configuration.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row(&mut md, "track_tokens", "bool", "true", "Track token usage"); + self.add_row(&mut md, "track_latency", "bool", "true", "Track latency"); + self.add_row(&mut md, "track_cost", "bool", "true", "Track estimated cost"); + self.add_row( + &mut md, + "cost_per_1k_input_tokens", + "f64", + "0.00015", + "Cost per 1K input tokens (gpt-4o-mini)", + ); + self.add_row( + &mut md, + "cost_per_1k_output_tokens", + "f64", + "0.0006", + "Cost per 1K output tokens (gpt-4o-mini)", + ); + md.push_str("\n"); + + // Metrics.pilot section + md.push_str("## `[metrics.pilot]`\n\n"); + md.push_str("Pilot-specific metrics configuration.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row(&mut md, "track_decisions", "bool", "true", "Track Pilot decisions"); + self.add_row( + &mut md, + "track_accuracy", + "bool", + "true", + "Track decision accuracy (requires feedback)", + ); + self.add_row(&mut md, "track_feedback", "bool", "true", "Track user feedback"); + md.push_str("\n"); + + // Metrics.retrieval section + md.push_str("## `[metrics.retrieval]`\n\n"); + md.push_str("Retrieval-specific metrics configuration.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row(&mut md, "track_paths", "bool", "true", "Track search paths"); + self.add_row(&mut md, "track_scores", "bool", "true", "Track relevance scores"); + self.add_row(&mut md, "track_iterations", "bool", "true", "Track iterations"); + self.add_row(&mut md, "track_cache", "bool", "true", "Track cache hits/misses"); + md.push_str("\n"); + + // Pilot section + md.push_str("## `[pilot]`\n\n"); + md.push_str("Pilot navigation configuration.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row( + &mut md, + "mode", + "string", + "Balanced", + "Operation mode (Aggressive, Balanced, Conservative, AlgorithmOnly)", + ); + self.add_row( + &mut md, + "guide_at_start", + "bool", + "true", + "Whether to provide guidance at search start", ); self.add_row( &mut md, - "top_k", + "guide_at_backtrack", + "bool", + "true", + "Whether to provide guidance during backtracking", + ); + md.push_str("\n"); + + // Pilot.budget section + md.push_str("## `[pilot.budget]`\n\n"); + md.push_str("Token and call budget constraints.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row( + &mut md, + "max_tokens_per_query", + "usize", + "2000", + "Maximum total tokens per query", + ); + self.add_row( + &mut md, + "max_tokens_per_call", + "usize", + "500", + "Maximum tokens per single LLM call", + ); + self.add_row( + &mut md, + "max_calls_per_query", + "usize", + "5", + "Maximum number of LLM calls per query", + ); + self.add_row( + &mut md, + "max_calls_per_level", + "usize", + "2", + "Maximum number of LLM calls per tree level", + ); + self.add_row( + &mut md, + "hard_limit", + "bool", + "true", + "Whether to enforce hard limits (true) or soft limits (false)", + ); + md.push_str("\n"); + + // Pilot.intervention section + md.push_str("## `[pilot.intervention]`\n\n"); + md.push_str("Intervention threshold settings.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row( + &mut md, + "fork_threshold", "usize", "3", - "Number of top results to return", + "Minimum candidates to trigger fork intervention", ); self.add_row( &mut md, - "max_tokens", + "score_gap_threshold", + "f32", + "0.15", + "Score gap threshold (intervene when scores are close)", + ); + self.add_row( + &mut md, + "low_score_threshold", + "f32", + "0.3", + "Low score threshold (intervene when best score is below this)", + ); + self.add_row( + &mut md, + "max_interventions_per_level", "usize", - "1000", - "Maximum tokens for retrieval context", + "2", + "Maximum interventions allowed per tree level", ); + md.push_str("\n"); + + // Pilot.feedback section + md.push_str("## `[pilot.feedback]`\n\n"); + md.push_str("Feedback and learning configuration.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row(&mut md, "enabled", "bool", "true", "Enable feedback collection"); self.add_row( &mut md, - "temperature", + "storage_path", + "string", + "./workspace/feedback", + "Storage path for feedback data", + ); + self.add_row( + &mut md, + "learning_rate", "f32", - "0.0", - "Temperature for retrieval", + "0.1", + "Learning rate for feedback-based improvements", + ); + self.add_row( + &mut md, + "min_samples_for_learning", + "usize", + "10", + "Minimum samples before applying learning", ); md.push_str("\n"); - // Retrieval.search section - md.push_str("## `[retrieval.search]`\n\n"); - md.push_str("Search algorithm configuration.\n\n"); + // Retrieval section + md.push_str("## `[retrieval]`\n\n"); + md.push_str("Retrieval model and behavior configuration.\n\n"); md.push_str("| Option | Type | Default | Description |\n"); md.push_str("|--------|------|---------|-------------|\n"); self.add_row( &mut md, - "top_k", + "model", + "string", + "gpt-4o", + "Model for retrieval navigation", + ); + self.add_row( + &mut md, + "endpoint", + "string", + "https://api.openai.com/v1", + "API endpoint", + ); + self.add_row(&mut md, "top_k", "usize", "3", "Number of top results to return"); + self.add_row( + &mut md, + "max_tokens", "usize", - "5", - "Number of top-k results to return", + "1000", + "Maximum tokens for retrieval context", ); + self.add_row(&mut md, "temperature", "f32", "0.0", "Temperature for retrieval"); + md.push_str("\n"); + + // Retrieval.search section + md.push_str("## `[retrieval.search]`\n\n"); + md.push_str("Search algorithm configuration.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row(&mut md, "top_k", "usize", "5", "Number of top-k results to return"); self.add_row( &mut md, "beam_width", @@ -241,6 +564,50 @@ impl ConfigDocs { ); md.push_str("\n"); + // Retrieval.cache section + md.push_str("## `[retrieval.cache]`\n\n"); + md.push_str("Cache configuration.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row(&mut md, "max_entries", "usize", "1000", "Maximum cache entries"); + self.add_row(&mut md, "ttl_secs", "u64", "3600", "Time-to-live in seconds"); + md.push_str("\n"); + + // Retrieval.strategy section + md.push_str("## `[retrieval.strategy]`\n\n"); + md.push_str("Strategy-specific configuration.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row( + &mut md, + "exploration_weight", + "f32", + "1.414", + "MCTS exploration weight (√2)", + ); + self.add_row( + &mut md, + "similarity_threshold", + "f32", + "0.5", + "Semantic similarity threshold", + ); + self.add_row( + &mut md, + "high_similarity_threshold", + "f32", + "0.8", + "High similarity for 'answer' decision", + ); + self.add_row( + &mut md, + "low_similarity_threshold", + "f32", + "0.3", + "Low similarity for 'explore' decision", + ); + md.push_str("\n"); + // Retrieval.content section md.push_str("## `[retrieval.content]`\n\n"); md.push_str("Content aggregator configuration.\n\n"); @@ -271,8 +638,8 @@ impl ConfigDocs { &mut md, "scoring_strategy", "string", - "keyword_bm25", - "Scoring strategy (keyword_only, keyword_bm25, hybrid)", + "hybrid", + "Scoring strategy (keyword, bm25, hybrid)", ); self.add_row( &mut md, @@ -311,130 +678,162 @@ impl ConfigDocs { ); md.push_str("\n"); - // Retrieval.strategy section - md.push_str("## `[retrieval.strategy]`\n\n"); - md.push_str("Strategy-specific configuration.\n\n"); + // Retrieval.multiturn section + md.push_str("## `[retrieval.multiturn]`\n\n"); + md.push_str("Multi-turn retrieval configuration.\n\n"); md.push_str("| Option | Type | Default | Description |\n"); md.push_str("|--------|------|---------|-------------|\n"); self.add_row( &mut md, - "exploration_weight", - "f32", - "1.414", - "MCTS exploration weight (√2)", + "enabled", + "bool", + "true", + "Enable multi-turn retrieval", ); self.add_row( &mut md, - "similarity_threshold", - "f32", - "0.5", - "Semantic similarity threshold", + "max_sub_queries", + "usize", + "3", + "Maximum sub-queries per query", ); self.add_row( &mut md, - "high_similarity_threshold", - "f32", - "0.8", - "High similarity for 'answer' decision", + "decomposition_model", + "string", + "gpt-4o-mini", + "Model for query decomposition", ); self.add_row( &mut md, - "low_similarity_threshold", - "f32", - "0.3", - "Low similarity for 'explore' decision", + "aggregation_strategy", + "string", + "merge", + "Aggregation strategy (merge, rank, synthesize)", ); md.push_str("\n"); - // Storage section - md.push_str("## `[storage]`\n\n"); - md.push_str("Storage configuration.\n\n"); + // Retrieval.reference section + md.push_str("## `[retrieval.reference]`\n\n"); + md.push_str("Reference following configuration.\n\n"); md.push_str("| Option | Type | Default | Description |\n"); md.push_str("|--------|------|---------|-------------|\n"); self.add_row( &mut md, - "workspace_dir", - "string", - "./workspace", - "Workspace directory for persisted documents", + "enabled", + "bool", + "true", + "Enable reference following", ); - md.push_str("\n"); - - // Concurrency section - md.push_str("## `[concurrency]`\n\n"); - md.push_str("Concurrency control configuration.\n\n"); - md.push_str("| Option | Type | Default | Description |\n"); - md.push_str("|--------|------|---------|-------------|\n"); + self.add_row(&mut md, "max_depth", "usize", "3", "Maximum reference depth"); self.add_row( &mut md, - "max_concurrent_requests", + "max_references", "usize", "10", - "Maximum concurrent LLM API calls", + "Maximum references to follow", ); self.add_row( &mut md, - "requests_per_minute", - "usize", - "500", - "Rate limit: requests per minute", + "follow_pages", + "bool", + "true", + "Follow page references", ); - self.add_row(&mut md, "enabled", "bool", "true", "Enable rate limiting"); self.add_row( &mut md, - "semaphore_enabled", + "follow_tables_figures", "bool", "true", - "Enable semaphore-based concurrency", + "Follow table/figure references", + ); + self.add_row( + &mut md, + "min_confidence", + "f32", + "0.5", + "Minimum confidence to follow reference", ); md.push_str("\n"); - // Fallback section - md.push_str("## `[fallback]`\n\n"); - md.push_str("Fallback/error recovery configuration.\n\n"); + // Storage section + md.push_str("## `[storage]`\n\n"); + md.push_str("Storage configuration.\n\n"); md.push_str("| Option | Type | Default | Description |\n"); md.push_str("|--------|------|---------|-------------|\n"); self.add_row( &mut md, - "enabled", + "workspace_dir", + "string", + "./workspace", + "Workspace directory for persisted documents", + ); + self.add_row(&mut md, "cache_size", "usize", "100", "Cache size"); + self.add_row( + &mut md, + "atomic_writes", "bool", "true", - "Enable graceful degradation", + "Enable atomic file writes", ); + self.add_row(&mut md, "file_lock", "bool", "true", "Enable file locking"); self.add_row( &mut md, - "models", - "[string]", - "[\"gpt-4o-mini\", \"glm-4-flash\"]", - "Fallback models in priority order", + "checksum_enabled", + "bool", + "true", + "Enable checksum verification", ); + md.push_str("\n"); + + // Storage.compression section + md.push_str("## `[storage.compression]`\n\n"); + md.push_str("Compression configuration.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); + self.add_row(&mut md, "enabled", "bool", "false", "Enable compression"); self.add_row( &mut md, - "endpoints", - "[string]", - "[]", - "Fallback endpoints in priority order", + "algorithm", + "string", + "gzip", + "Compression algorithm (gzip, zstd, lz4)", ); + self.add_row(&mut md, "level", "u32", "6", "Compression level"); + md.push_str("\n"); + + // Indexer section + md.push_str("## `[indexer]`\n\n"); + md.push_str("Controls document indexing behavior.\n\n"); + md.push_str("| Option | Type | Default | Description |\n"); + md.push_str("|--------|------|---------|-------------|\n"); self.add_row( &mut md, - "on_rate_limit", - "string", - "retry_then_fallback", - "Behavior on rate limit (retry, fallback, retry_then_fallback, fail)", + "subsection_threshold", + "usize", + "300", + "Word count threshold for splitting sections into subsections", ); self.add_row( &mut md, - "on_timeout", - "string", - "retry_then_fallback", - "Behavior on timeout", + "max_segment_tokens", + "usize", + "3000", + "Maximum tokens to send in a single segmentation request", ); self.add_row( &mut md, - "on_all_failed", - "string", - "return_error", - "Behavior when all attempts fail (return_error, return_cache)", + "max_summary_tokens", + "usize", + "200", + "Maximum tokens for each summary", + ); + self.add_row( + &mut md, + "min_summary_tokens", + "usize", + "20", + "Minimum content tokens required to generate a summary", ); md.push_str("\n"); @@ -461,25 +860,138 @@ impl ConfigDocs { fn fallback_toml() -> String { r#"# Vectorless Configuration Example -# Copy this file to config.toml and fill in your API keys +# Copy this file to vectorless.toml and fill in your API keys +# +# All configuration is loaded from this file only. +# No environment variables are used - this ensures explicit, traceable configuration. -[indexer] -subsection_threshold = 300 -max_segment_tokens = 3000 -max_summary_tokens = 200 -min_summary_tokens = 20 +# ============================================================================ +# LLM Configuration (Unified) +# ============================================================================ +# +# The LLM pool allows configuring different models for different purposes: +# - summary: Used for generating document summaries during indexing +# - retrieval: Used for retrieval decisions and content evaluation +# - pilot: Used for intelligent navigation guidance +# +# Each client can have its own model, endpoint, and settings. + +[llm] +# Default API key (used by all clients unless overridden per-client) +api_key = "sk-your-api-key-here" -[summary] +# Summary client - generates document summaries during indexing +# Use a fast, cheap model for bulk processing +[llm.summary] model = "gpt-4o-mini" endpoint = "https://api.openai.com/v1" -# api_key = "sk-..." max_tokens = 200 temperature = 0.0 +# api_key = "sk-specific-key-for-summary" # Optional: override default + +# Retrieval client - used for retrieval decisions and content evaluation +# Can use a more capable model for better decisions +[llm.retrieval] +model = "gpt-4o" +endpoint = "https://api.openai.com/v1" +max_tokens = 100 +temperature = 0.0 +# api_key = "sk-specific-key-for-retrieval" # Optional: override default + +# Pilot client - used for intelligent navigation guidance +# Use a fast model for quick navigation decisions +[llm.pilot] +model = "gpt-4o-mini" +endpoint = "https://api.openai.com/v1" +max_tokens = 300 +temperature = 0.0 +# api_key = "sk-specific-key-for-pilot" # Optional: override default + +# Retry configuration (applies to all LLM calls) +[llm.retry] +max_attempts = 3 +initial_delay_ms = 500 +max_delay_ms = 30000 +multiplier = 2.0 +retry_on_rate_limit = true + +# Throttle/rate limiting configuration (applies to all LLM calls) +[llm.throttle] +max_concurrent_requests = 10 +requests_per_minute = 500 +enabled = true +semaphore_enabled = true + +# Fallback configuration (applies to all LLM calls) +[llm.fallback] +enabled = true +models = ["gpt-4o-mini", "glm-4-flash"] +on_rate_limit = "retry_then_fallback" +on_timeout = "retry_then_fallback" +on_all_failed = "return_error" + +# ============================================================================ +# Metrics Configuration (Unified) +# ============================================================================ + +[metrics] +enabled = true +storage_path = "./workspace/metrics" +retention_days = 30 + +[metrics.llm] +track_tokens = true +track_latency = true +track_cost = true +cost_per_1k_input_tokens = 0.00015 # gpt-4o-mini pricing +cost_per_1k_output_tokens = 0.0006 + +[metrics.pilot] +track_decisions = true +track_accuracy = true +track_feedback = true + +[metrics.retrieval] +track_paths = true +track_scores = true +track_iterations = true +track_cache = true + +# ============================================================================ +# Pilot Configuration +# ============================================================================ + +[pilot] +mode = "Balanced" # Aggressive | Balanced | Conservative | AlgorithmOnly +guide_at_start = true +guide_at_backtrack = true + +[pilot.budget] +max_tokens_per_query = 2000 +max_tokens_per_call = 500 +max_calls_per_query = 5 +max_calls_per_level = 2 +hard_limit = true + +[pilot.intervention] +fork_threshold = 3 +score_gap_threshold = 0.15 +low_score_threshold = 0.3 +max_interventions_per_level = 2 + +[pilot.feedback] +enabled = true +storage_path = "./workspace/feedback" +learning_rate = 0.1 +min_samples_for_learning = 10 + +# ============================================================================ +# Retrieval Configuration +# ============================================================================ [retrieval] model = "gpt-4o" endpoint = "https://api.openai.com/v1" -# api_key = "sk-..." top_k = 3 max_tokens = 1000 temperature = 0.0 @@ -511,28 +1023,60 @@ low_similarity_threshold = 0.3 enabled = true token_budget = 4000 min_relevance_score = 0.2 -scoring_strategy = "keyword_bm25" +scoring_strategy = "hybrid" # keyword | bm25 | hybrid output_format = "markdown" include_scores = false hierarchical_min_per_level = 0.1 deduplicate = true dedup_threshold = 0.9 -[storage] -workspace_dir = "./workspace" +# ============================================================================ +# Multi-turn Retrieval Configuration +# ============================================================================ -[concurrency] -max_concurrent_requests = 10 -requests_per_minute = 500 +[retrieval.multiturn] enabled = true -semaphore_enabled = true +max_sub_queries = 3 +decomposition_model = "gpt-4o-mini" +aggregation_strategy = "merge" # merge | rank | synthesize -[fallback] +# ============================================================================ +# Reference Following Configuration +# ============================================================================ + +[retrieval.reference] enabled = true -models = ["gpt-4o-mini", "glm-4-flash"] -on_rate_limit = "retry_then_fallback" -on_timeout = "retry_then_fallback" -on_all_failed = "return_error" +max_depth = 3 +max_references = 10 +follow_pages = true +follow_tables_figures = true +min_confidence = 0.5 + +# ============================================================================ +# Storage Configuration +# ============================================================================ + +[storage] +workspace_dir = "./workspace" +cache_size = 100 +atomic_writes = true +file_lock = true +checksum_enabled = true + +[storage.compression] +enabled = false +algorithm = "gzip" +level = 6 + +# ============================================================================ +# Indexer Configuration +# ============================================================================ + +[indexer] +subsection_threshold = 300 +max_segment_tokens = 3000 +max_summary_tokens = 200 +min_summary_tokens = 20 "# .to_string() } @@ -542,7 +1086,7 @@ on_all_failed = "return_error" r#"# Minimal Vectorless Configuration # Most options have sensible defaults -[summary] +[llm] api_key = "your-api-key-here" [retrieval] @@ -568,7 +1112,10 @@ mod tests { let md = docs.to_markdown(); assert!(md.contains("# Configuration Reference")); - assert!(md.contains("## `[indexer]`")); + assert!(md.contains("## `[llm]`")); + assert!(md.contains("## `[llm.summary]`")); + assert!(md.contains("## `[metrics]`")); + assert!(md.contains("## `[pilot]`")); assert!(md.contains("## `[retrieval]`")); assert!(md.contains("## `[retrieval.content]`")); } @@ -578,8 +1125,7 @@ mod tests { let docs = ConfigDocs::with_defaults(); let toml = docs.to_example_toml(); - assert!(toml.contains("[indexer]")); - assert!(toml.contains("[retrieval]")); + assert!(toml.contains("[llm]") || toml.contains("[indexer]")); } #[test] @@ -587,7 +1133,7 @@ mod tests { let docs = ConfigDocs::with_defaults(); let toml = docs.to_minimal_toml(); - assert!(toml.contains("[summary]")); + assert!(toml.contains("[llm]")); assert!(toml.len() < 200); // Should be minimal } }