Просмотр исходного кода

feat(knowledge): P0 三大特性 — RAG Fusion、Contextual Chunking、Wiki 定时重编译

P0-1 RAG Fusion
- 新增 _call_llm_once() 同步 LLM 工具函数
- 新增 _rrf_fuse() Reciprocal Rank Fusion(score+=1/(k+rank),k=60)
- 新增 _fusion_search():LLM 扩写查询为 N=4 子问题 → 多路 BM25 → RRF 合并
- SearchRequest.mode 新增 fusion 选项
- search_kb / search_stream 均支持 fusion 模式
- 前端 QA 面板新增「RAG Fusion(多查询+RRF)」模式选项

P0-2 Contextual Chunking
- IndexBuildRequest 新增 chunk_strategy(token | contextual)
- 新增 _contextual_enrich_index():BM25 构建后批量 LLM 生成文档摘要,
  为每个 chunk 前置 [文档背景: {summary}] 并回写 rag_index.json
- _run_index_job 接受 chunk_strategy 参数并在 BM25 成功后触发增强
- 前端索引构建面板新增分块策略下拉(含耗时提示)

P0-3 Wiki 定时自动重编译
- 新增 WikiScheduleRequest pydantic 模型
- 新增 _load/save_wiki_schedule()、_compute_next_run() 持久化到 .wiki_schedule.json
- 新增 GET/PUT /{kb_id}/wiki/schedule 端点(在通配符路由之前注册)
- 新增 _wiki_schedule_loop() 守护线程(每 30 min 检查所有 KB)
- 新增 _start_schedule_checker() 在 app.py startup 中启动
- 前端 WikiBrowser 新增定时设置面板(启用/周期/下次运行时间)
- knowledge.ts 新增 WikiSchedule 接口 + wikiSchedule/updateWikiSchedule API

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
kenny67nju 5 месяцев назад
Родитель
Сommit
598447ce11
4 измененных файлов с 486 добавлено и 19 удалено
  1. 7 0
      agentpaas/api/app.py
  2. 386 13
      agentpaas/api/v1/knowledge.py
  3. 14 2
      webui/src/api/knowledge.ts
  4. 79 4
      webui/src/pages/KnowledgeDetail.tsx

+ 7 - 0
agentpaas/api/app.py

@@ -127,6 +127,13 @@ app.include_router(providers_api.router, prefix="/api/v1")
 app.include_router(templates_api.router, prefix="/api/v1")
 app.include_router(knowledge_router.router, prefix="/api/v1")
 
+
+@app.on_event("startup")
+async def _on_startup():
+    """Start background services on server startup."""
+    knowledge_router._start_schedule_checker()
+
+
 @app.get("/health")
 async def health():
     return {"status": "ok", "version": "0.1.0"}

+ 386 - 13
agentpaas/api/v1/knowledge.py

@@ -59,6 +59,7 @@ class AddFilesRequest(BaseModel):
 class IndexBuildRequest(BaseModel):
     index_type: str = Field(default="bm25", description="bm25 | vector | graph | all")
     mode: str = Field(default="full", description="full | incremental")
+    chunk_strategy: str = Field(default="token", description="token | contextual")
 
 
 class WikiBuildRequest(BaseModel):
@@ -68,7 +69,7 @@ class WikiBuildRequest(BaseModel):
 
 class SearchRequest(BaseModel):
     query: str = Field(..., max_length=4096)
-    mode: str = Field(default="lambda", description="lambda | bm25 | vector | wiki")
+    mode: str = Field(default="lambda", description="lambda | bm25 | vector | wiki | fusion")
     top_k: int = Field(default=5, ge=1, le=20)
     weights: Optional[Dict[str, float]] = None  # bm25/vector/graph/wiki overrides
 
@@ -77,6 +78,11 @@ class UpdateIgnoreDirsRequest(BaseModel):
     ignored_dirs: List[str] = Field(default_factory=list, description="List of relative dir paths to ignore")
 
 
+class WikiScheduleRequest(BaseModel):
+    enabled: bool = True
+    interval: str = Field(default="weekly", description="daily | weekly")
+
+
 # ─── Helper: walk root_dir ───
 
 def _walk_dir(
@@ -279,7 +285,7 @@ def _popen_stream(
     return proc.returncode
 
 
-def _run_index_job(db: Database, kb_id: str, job_id: str, kb_root: str, index_type: str, mode: str):
+def _run_index_job(db: Database, kb_id: str, job_id: str, kb_root: str, index_type: str, mode: str, chunk_strategy: str = "token"):
     """Background thread — extract text then build index, streaming log to DB."""
 
     def _flush(status: str, log_buf: List[str]):
@@ -333,6 +339,11 @@ def _run_index_job(db: Database, kb_id: str, job_id: str, kb_root: str, index_ty
                     rc = _popen_stream(bm25_script, env, kb_root, log_buf, db, job_id, flush_every=5)
                     if rc != 0:
                         errors.append(f"BM25 构建失败(returncode={rc})")
+                    elif chunk_strategy == "contextual":
+                        # ── Step 2b: Contextual chunking enrichment ──
+                        log_buf.append("[Contextual] 启动上下文增强分块...")
+                        _flush("running", log_buf)
+                        _contextual_enrich_index(kb_path, scripts_dir, log_buf, db, job_id, _flush)
                 else:
                     log_buf.append("[BM25] rebuild_index.py / build_index.py 均未找到 — 已跳过")
 
@@ -851,11 +862,11 @@ async def trigger_index(
 
     t = threading.Thread(
         target=_run_index_job,
-        args=(db, kb_id, job_id, kb["root_dir"], req.index_type, req.mode),
+        args=(db, kb_id, job_id, kb["root_dir"], req.index_type, req.mode, req.chunk_strategy),
         daemon=True,
     )
     t.start()
-    return {"job_id": job_id, "status": "pending"}
+    return {"job_id": job_id, "status": "pending", "chunk_strategy": req.chunk_strategy}
 
 
 # ─── Wiki Compile Jobs ───
@@ -940,6 +951,38 @@ async def wiki_tree(
     return result
 
 
+@router.get("/{kb_id}/wiki/schedule")
+async def get_wiki_schedule(
+    kb_id: str,
+    tenant: TenantContext = Depends(get_tenant),
+    db: Database = Depends(get_database),
+):
+    """Return the current auto-recompile schedule for this knowledge base."""
+    kb = db.fetchone("SELECT * FROM knowledge_bases WHERE id=? AND tenant_id=?", (kb_id, tenant.tenant_id))
+    if not kb:
+        raise HTTPException(status_code=404, detail="Knowledge base not found")
+    return _load_wiki_schedule(kb["root_dir"])
+
+
+@router.put("/{kb_id}/wiki/schedule")
+async def update_wiki_schedule(
+    kb_id: str,
+    req: WikiScheduleRequest,
+    tenant: TenantContext = Depends(get_tenant),
+    db: Database = Depends(get_database),
+):
+    """Enable / disable the auto-recompile schedule and set the interval."""
+    kb = db.fetchone("SELECT * FROM knowledge_bases WHERE id=? AND tenant_id=?", (kb_id, tenant.tenant_id))
+    if not kb:
+        raise HTTPException(status_code=404, detail="Knowledge base not found")
+    cfg = _load_wiki_schedule(kb["root_dir"])
+    cfg["enabled"] = req.enabled
+    cfg["interval"] = req.interval
+    cfg["next_run"] = _compute_next_run(req.interval) if req.enabled else cfg.get("next_run", "")
+    _save_wiki_schedule(kb["root_dir"], cfg)
+    return cfg
+
+
 @router.get("/{kb_id}/wiki/{page_path:path}")
 async def wiki_page(
     kb_id: str,
@@ -978,6 +1021,259 @@ async def delete_analysis(
     return None
 
 
+# ─── P0 helper: sync LLM call (non-streaming) ───
+
+def _call_llm_once(
+    chat_url: str,
+    headers: dict,
+    model: str,
+    messages: List[Dict],
+    is_anthropic: bool = False,
+    max_tokens: int = 256,
+    timeout: int = 30,
+) -> str:
+    """Make a single non-streaming LLM call and return the full response text."""
+    import urllib.request as _ur
+    if is_anthropic:
+        system_parts = [m["content"] for m in messages if m["role"] == "system"]
+        user_msgs = [m for m in messages if m["role"] != "system"]
+        body_dict: dict = {
+            "model": model,
+            "messages": user_msgs,
+            "max_tokens": max_tokens,
+            "stream": False,
+        }
+        if system_parts:
+            body_dict["system"] = "\n\n".join(system_parts)
+        body = json.dumps(body_dict, ensure_ascii=False).encode("utf-8")
+        req = _ur.Request(chat_url, data=body, headers=headers, method="POST")
+        with _ur.urlopen(req, timeout=timeout) as resp:
+            d = json.loads(resp.read())
+            return d.get("content", [{}])[0].get("text", "")
+    else:
+        body = json.dumps({
+            "model": model,
+            "messages": messages,
+            "max_tokens": max_tokens,
+            "stream": False,
+        }, ensure_ascii=False).encode("utf-8")
+        req = _ur.Request(chat_url, data=body, headers=headers, method="POST")
+        with _ur.urlopen(req, timeout=timeout) as resp:
+            d = json.loads(resp.read())
+            return d["choices"][0]["message"].get("content", "")
+
+
+# ─── P0 helper: Reciprocal Rank Fusion ───
+
+def _rrf_fuse(all_rankings: List[List[Dict]], k: int = 60) -> List[Dict]:
+    """Reciprocal Rank Fusion: score(d) += 1/(k + rank) across all rankings.
+
+    Returns a deduplicated list sorted by descending RRF score.
+    Deduplication key: (source, first 80 chars of text).
+    """
+    scores: Dict[str, float] = {}
+    best: Dict[str, Dict] = {}
+    for ranking in all_rankings:
+        for rank, chunk in enumerate(ranking, start=1):
+            key = f"{chunk.get('source', '')}::{(chunk.get('text') or '')[:80]}"
+            scores[key] = scores.get(key, 0.0) + 1.0 / (k + rank)
+            if key not in best:
+                best[key] = chunk
+    return sorted(best.values(), key=lambda c: -scores[
+        f"{c.get('source', '')}::{(c.get('text') or '')[:80]}"
+    ])
+
+
+# ─── P0 helper: Wiki schedule persistence ───
+
+def _load_wiki_schedule(kb_root: str) -> dict:
+    """Read {kb_root}/.wiki_schedule.json; return defaults if absent."""
+    p = Path(kb_root) / ".wiki_schedule.json"
+    defaults = {"enabled": False, "interval": "weekly", "next_run": "", "last_run": ""}
+    if not p.exists():
+        return defaults
+    try:
+        return {**defaults, **json.loads(p.read_text(encoding="utf-8"))}
+    except Exception:
+        return defaults
+
+
+def _save_wiki_schedule(kb_root: str, config: dict):
+    """Write {kb_root}/.wiki_schedule.json atomically."""
+    p = Path(kb_root) / ".wiki_schedule.json"
+    tmp = p.with_suffix(".json.tmp")
+    tmp.write_text(json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8")
+    tmp.replace(p)
+
+
+def _compute_next_run(interval: str) -> str:
+    """Return ISO-8601 UTC timestamp for the next run based on interval."""
+    import datetime
+    now = datetime.datetime.utcnow()
+    if interval == "daily":
+        delta = datetime.timedelta(days=1)
+    else:  # weekly
+        delta = datetime.timedelta(weeks=1)
+    return (now + delta).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+# ─── P0 helper: Contextual chunking enrichment ───
+
+def _contextual_enrich_index(
+    kb_path: Path,
+    scripts_dir: Path,
+    log_buf: List[str],
+    db: Database,
+    job_id: str,
+    flush_fn,
+    provider_id: str = "",
+    model_override: str = "",
+):
+    """After BM25 build: read rag_index.json, group chunks by source doc, generate one LLM
+    summary per doc, prepend '[文档背景: {summary}]\\n' to every chunk from that doc, and
+    write the enriched index back.
+
+    Falls back gracefully on any error so the main index job is never broken.
+    """
+    index_file = kb_path / "rag_index.json"
+    if not index_file.exists():
+        log_buf.append("[Contextual] rag_index.json 不存在,跳过上下文增强")
+        return
+
+    try:
+        from agentpaas.api.v1.providers_api import DEFAULT_PROVIDERS
+        chat_url, headers, model_name, _ = _resolve_llm(provider_id, model_override)
+        pdef = DEFAULT_PROVIDERS.get(provider_id, {})
+        is_anthropic = pdef.get("type") == "anthropic"
+    except Exception as e:
+        log_buf.append(f"[Contextual] LLM 解析失败({e}),跳过上下文增强")
+        flush_fn("running", log_buf)
+        return
+
+    try:
+        raw = json.loads(index_file.read_text(encoding="utf-8"))
+    except Exception as e:
+        log_buf.append(f"[Contextual] 读取 rag_index.json 失败({e})")
+        return
+
+    # raw can be list of chunks or dict; normalise
+    chunks: List[Dict] = raw if isinstance(raw, list) else raw.get("chunks", [])
+
+    # Group chunks by source document
+    from collections import defaultdict
+    doc_chunks: Dict[str, List[int]] = defaultdict(list)
+    for idx, chunk in enumerate(chunks):
+        src = chunk.get("source") or chunk.get("file") or ""
+        doc_chunks[src].append(idx)
+
+    log_buf.append(f"[Contextual] 共 {len(doc_chunks)} 篇文档,生成摘要中...")
+    flush_fn("running", log_buf)
+
+    summaries: Dict[str, str] = {}
+    for src, idxs in doc_chunks.items():
+        # Gather up to 1500 chars of text as doc sample
+        sample = "\n".join((chunks[i].get("text") or "")[:300] for i in idxs[:5])[:1500]
+        prompt = [
+            {"role": "system", "content": "你是文档摘要助手,请用1-3句话概括以下文档的主要内容。"},
+            {"role": "user", "content": f"文档: {src}\n\n内容摘录:\n{sample}\n\n一句话摘要:"},
+        ]
+        try:
+            summary = _call_llm_once(
+                chat_url, headers, model_name, prompt,
+                is_anthropic=is_anthropic, max_tokens=128, timeout=20,
+            ).strip()
+            summaries[src] = summary
+        except Exception as e:
+            summaries[src] = src  # fallback: just use filename
+
+    # Prepend background context to each chunk
+    enriched = 0
+    for chunk in chunks:
+        src = chunk.get("source") or chunk.get("file") or ""
+        summary = summaries.get(src, "")
+        if summary and not (chunk.get("text") or "").startswith("[文档背景:"):
+            chunk["text"] = f"[文档背景: {summary}]\n{chunk.get('text', '')}"
+            enriched += 1
+
+    # Write back
+    try:
+        if isinstance(raw, list):
+            out = chunks
+        else:
+            raw["chunks"] = chunks
+            out = raw
+        index_file.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
+        log_buf.append(f"[Contextual] ✅ 已为 {enriched} 个 chunk 添加文档背景({len(summaries)} 篇文档)")
+    except Exception as e:
+        log_buf.append(f"[Contextual] 写回索引失败({e})")
+    flush_fn("running", log_buf)
+
+
+# ─── P0 helper: Wiki auto-recompile background scheduler ───
+
+_SCHEDULE_CHECKER_STARTED = False
+_SCHEDULE_CHECKER_LOCK = threading.Lock()
+
+
+def _wiki_schedule_loop():
+    """Daemon thread: every 30 min, scan all KB roots and trigger wiki builds if due."""
+    import datetime
+    from agentpaas.db.session import get_db
+    while True:
+        time.sleep(1800)  # 30 minutes
+        try:
+            db: Database = get_db()
+            kbs = db.fetchall("SELECT id, root_dir FROM knowledge_bases WHERE root_dir IS NOT NULL")
+            now_str = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
+            for kb in kbs:
+                try:
+                    cfg = _load_wiki_schedule(kb["root_dir"])
+                    if not cfg.get("enabled"):
+                        continue
+                    next_run = cfg.get("next_run", "")
+                    if not next_run or now_str >= next_run:
+                        # Trigger wiki build
+                        job_id = gen_id("kbj_")
+                        tenant_row = db.fetchone(
+                            "SELECT tenant_id FROM knowledge_bases WHERE id=?", (kb["id"],)
+                        )
+                        tid = tenant_row["tenant_id"] if tenant_row else "system"
+                        db.execute(
+                            "INSERT INTO kb_jobs (id, kb_id, tenant_id, job_type, status, created_at) VALUES (?,?,?,?,?,?)",
+                            (job_id, kb["id"], tid, "wiki:scheduled", "pending", now_utc()),
+                        )
+                        db.commit()
+                        t = threading.Thread(
+                            target=_run_wiki_job,
+                            args=(db, kb["id"], job_id, kb["root_dir"], "incremental", 2),
+                            daemon=True,
+                        )
+                        t.start()
+                        # Update schedule
+                        cfg["last_run"] = now_str
+                        cfg["next_run"] = _compute_next_run(cfg.get("interval", "weekly"))
+                        _save_wiki_schedule(kb["root_dir"], cfg)
+                except Exception:
+                    pass
+        except Exception:
+            pass
+
+
+def _start_schedule_checker():
+    """Start the wiki-schedule background thread exactly once."""
+    global _SCHEDULE_CHECKER_STARTED
+    with _SCHEDULE_CHECKER_LOCK:
+        if _SCHEDULE_CHECKER_STARTED:
+            return
+        _SCHEDULE_CHECKER_STARTED = True
+        t = threading.Thread(
+            target=_wiki_schedule_loop,
+            daemon=True,
+            name="wiki-scheduler",
+        )
+        t.start()
+
+
 # ─── Search helpers ───
 
 def _search_subprocess(kb_root: str, scripts_dir: Path, mode: str, query: str, top_k: int) -> List[Dict]:
@@ -1028,6 +1324,67 @@ def _search_subprocess(kb_root: str, scripts_dir: Path, mode: str, query: str, t
             pass
 
 
+def _fusion_search(
+    kb_root: str,
+    scripts_dir: Path,
+    query: str,
+    top_k: int,
+    n_subqueries: int = 4,
+    provider_id: str = "",
+    model_override: str = "",
+) -> List[Dict]:
+    """RAG Fusion: expand query → N sub-queries → BM25 search each → RRF merge.
+
+    If LLM expansion fails, falls back to a single BM25 search on the original query.
+    """
+    # ── Step 1: query expansion ──
+    sub_queries: List[str] = [query]
+    try:
+        from agentpaas.api.v1.providers_api import DEFAULT_PROVIDERS
+        chat_url, headers, model_name, _ = _resolve_llm(provider_id, model_override)
+        pdef = DEFAULT_PROVIDERS.get(provider_id, {})
+        is_anthropic = pdef.get("type") == "anthropic"
+        expansion_prompt = [
+            {
+                "role": "system",
+                "content": (
+                    f"请将用户的问题改写为 {n_subqueries} 个语义相近但措辞不同的子问题,"
+                    "每行一个,只输出问题,不要编号或其他内容。"
+                ),
+            },
+            {"role": "user", "content": query},
+        ]
+        raw = _call_llm_once(
+            chat_url, headers, model_name, expansion_prompt,
+            is_anthropic=is_anthropic, max_tokens=256, timeout=20,
+        )
+        lines = [l.strip() for l in raw.splitlines() if l.strip()]
+        if lines:
+            sub_queries = [query] + lines[:n_subqueries]
+    except Exception:
+        pass  # fallback: single query
+
+    # ── Step 2: search each sub-query ──
+    all_rankings: List[List[Dict]] = []
+    for sq in sub_queries:
+        try:
+            results = _search_subprocess(kb_root, scripts_dir, "bm25", sq, top_k)
+            if results:
+                all_rankings.append(results)
+        except Exception:
+            pass
+
+    if not all_rankings:
+        # Last resort: direct BM25
+        try:
+            return _search_subprocess(kb_root, scripts_dir, "bm25", query, top_k)
+        except Exception:
+            return []
+
+    # ── Step 3: RRF fusion ──
+    return _rrf_fuse(all_rankings)[:top_k]
+
+
 # ─── Search ───
 
 @router.post("/{kb_id}/search")
@@ -1053,10 +1410,17 @@ async def search_kb(
         raise HTTPException(status_code=503, detail="BM25 索引不存在,请先在「索引构建」标签中触发构建。")
 
     try:
-        results = await asyncio.get_event_loop().run_in_executor(
-            None,
-            lambda: _search_subprocess(kb_root, scripts_dir, req.mode, req.query, req.top_k)
-        )
+        if req.mode == "fusion":
+            # RAG Fusion: expand query → multi-search → RRF
+            results = await asyncio.get_event_loop().run_in_executor(
+                None,
+                lambda: _fusion_search(kb_root, scripts_dir, req.query, req.top_k),
+            )
+        else:
+            results = await asyncio.get_event_loop().run_in_executor(
+                None,
+                lambda: _search_subprocess(kb_root, scripts_dir, req.mode, req.query, req.top_k)
+            )
         return {
             "query": req.query,
             "mode": req.mode,
@@ -1242,16 +1606,25 @@ async def search_stream(
 
     async def event_stream():
         # ── Step 1: retrieve ──
-        yield f"data: {json.dumps({'type': 'status', 'text': '正在检索相关文档...'})}\n\n"
+        if mode == "fusion":
+            yield f"data: {json.dumps({'type': 'status', 'text': '正在扩写查询并多路检索(RAG Fusion)...'})}\n\n"
+        else:
+            yield f"data: {json.dumps({'type': 'status', 'text': '正在检索相关文档...'})}\n\n"
         await asyncio.sleep(0)
 
         chunks: List[Dict] = []
         if scripts_dir and (Path(kb_root) / "rag_index.json").exists():
             try:
-                chunks = await asyncio.get_event_loop().run_in_executor(
-                    None,
-                    lambda: _search_subprocess(kb_root, scripts_dir, mode, q, top_k)
-                )
+                if mode == "fusion":
+                    chunks = await asyncio.get_event_loop().run_in_executor(
+                        None,
+                        lambda: _fusion_search(kb_root, scripts_dir, q, top_k, provider_id=provider_id, model_override=model)
+                    )
+                else:
+                    chunks = await asyncio.get_event_loop().run_in_executor(
+                        None,
+                        lambda: _search_subprocess(kb_root, scripts_dir, mode, q, top_k)
+                    )
             except Exception as e:
                 yield f"data: {json.dumps({'type': 'status', 'text': f'检索出错: {e}'})}\n\n"
         else:

+ 14 - 2
webui/src/api/knowledge.ts

@@ -79,6 +79,13 @@ export interface WikiTree {
   index_content: string
 }
 
+export interface WikiSchedule {
+  enabled: boolean
+  interval: 'daily' | 'weekly'
+  next_run: string
+  last_run: string
+}
+
 export const knowledgeApi = {
   list: () => api.get<{ items: KnowledgeBase[] }>('/knowledge'),
   get: (id: string) => api.get<KnowledgeBase>(`/knowledge/${id}`),
@@ -110,8 +117,8 @@ export const knowledgeApi = {
   removeFile: (kbId: string, fileId: string) =>
     api.delete(`/knowledge/${kbId}/files/${fileId}`),
 
-  buildIndex: (kbId: string, index_type = 'bm25', mode = 'full') =>
-    api.post<{ job_id: string }>(`/knowledge/${kbId}/index`, { index_type, mode }),
+  buildIndex: (kbId: string, index_type = 'bm25', mode = 'full', chunk_strategy = 'token') =>
+    api.post<{ job_id: string; chunk_strategy: string }>(`/knowledge/${kbId}/index`, { index_type, mode, chunk_strategy }),
   buildWiki: (kbId: string, mode = 'incremental', concurrency = 2) =>
     api.post<{ job_id: string }>(`/knowledge/${kbId}/wiki`, { mode, concurrency }),
   pauseWiki: (kbId: string) =>
@@ -124,6 +131,11 @@ export const knowledgeApi = {
   deleteAnalysis: (kbId: string, name: string) =>
     api.delete(`/knowledge/${kbId}/wiki/analyses/${name}`),
 
+  wikiSchedule: (kbId: string) =>
+    api.get<WikiSchedule>(`/knowledge/${kbId}/wiki/schedule`),
+  updateWikiSchedule: (kbId: string, data: Partial<WikiSchedule>) =>
+    api.put<WikiSchedule>(`/knowledge/${kbId}/wiki/schedule`, data),
+
   search: (kbId: string, query: string, mode = 'lambda', top_k = 5) =>
     api.post<{ query: string; mode: string; results: any[] }>(`/knowledge/${kbId}/search`, {
       query, mode, top_k,

+ 79 - 4
webui/src/pages/KnowledgeDetail.tsx

@@ -9,7 +9,7 @@ import {
   Eye, EyeOff, Folder, Settings2
 } from 'lucide-react'
 import toast from 'react-hot-toast'
-import { knowledgeApi, type KBFile, type KBJob, type WikiPage, type KBDirNode, type KBChunk } from '../api/knowledge'
+import { knowledgeApi, type KBFile, type KBJob, type WikiPage, type KBDirNode, type KBChunk, type WikiSchedule } from '../api/knowledge'
 import { providersApi, type Provider } from '../api/providers'
 import { Spinner, Button } from '../components/ui'
 import { useAppStore } from '../store/app'
@@ -691,6 +691,7 @@ function IndexStats({ kbId }: { kbId: string }) {
 
 function IndexBuilder({ kbId }: { kbId: string }) {
   const [activeLog, setActiveLog] = useState<string | null>(null)
+  const [chunkStrategy, setChunkStrategy] = useState<'token' | 'contextual'>('token')
   const qc = useQueryClient()
 
   const { data: jobsData, refetch: refetchJobs } = useQuery({
@@ -712,7 +713,7 @@ function IndexBuilder({ kbId }: { kbId: string }) {
 
   const buildMut = useMutation({
     mutationFn: ({ type, mode }: { type: string; mode: string }) =>
-      knowledgeApi.buildIndex(kbId, type, mode),
+      knowledgeApi.buildIndex(kbId, type, mode, chunkStrategy),
     onSuccess: (r) => {
       toast.success(`已触发构建 (Job: ${r.job_id})`)
       setActiveLog(r.job_id)
@@ -742,7 +743,23 @@ function IndexBuilder({ kbId }: { kbId: string }) {
       {/* Index status cards */}
       <IndexStats kbId={kbId} />
 
-      <div className="flex justify-end">
+      <div className="flex items-center justify-between">
+        <div className="flex items-center gap-3">
+          <label className="text-xs font-medium text-gray-600">分块策略:</label>
+          <select
+            value={chunkStrategy}
+            onChange={e => setChunkStrategy(e.target.value as 'token' | 'contextual')}
+            className="text-xs border border-gray-300 rounded px-2 py-1"
+          >
+            <option value="token">Token 分块(默认)</option>
+            <option value="contextual">Contextual 分块(LLM 增强)</option>
+          </select>
+          {chunkStrategy === 'contextual' && (
+            <span className="text-xs text-amber-600 bg-amber-50 px-2 py-0.5 rounded">
+              每篇文档额外 1 次 LLM 调用生成摘要
+            </span>
+          )}
+        </div>
         <Button variant="secondary" size="sm" icon={<RefreshCw size={13}/>}
           onClick={() => { refetchJobs(); qc.invalidateQueries({ queryKey: ['kb-detail', kbId] }) }}>
           刷新状态
@@ -829,6 +846,7 @@ function WikiBrowser({ kbId }: { kbId: string }) {
   const [pageLoading, setPageLoading] = useState(false)
   const [concurrency, setConcurrency] = useState(2)
   const [wikiMode, setWikiMode] = useState<'incremental' | 'rebuild'>('incremental')
+  const [showSchedule, setShowSchedule] = useState(false)
 
   const { data: tree, isLoading: treeLoading, refetch: refetchTree } = useQuery({
     queryKey: ['kb-wiki-tree', kbId],
@@ -881,6 +899,17 @@ function WikiBrowser({ kbId }: { kbId: string }) {
     onSuccess: () => { toast.success('已删除'); refetchTree() },
   })
 
+  const { data: scheduleData, refetch: refetchSchedule } = useQuery({
+    queryKey: ['kb-wiki-schedule', kbId],
+    queryFn: () => knowledgeApi.wikiSchedule(kbId),
+  })
+
+  const scheduleMut = useMutation({
+    mutationFn: (data: Partial<WikiSchedule>) => knowledgeApi.updateWikiSchedule(kbId, data),
+    onSuccess: () => { toast.success('定时设置已更新'); refetchSchedule() },
+    onError: (e: any) => toast.error(e.message ?? '更新失败'),
+  })
+
   const loadPage = async (path: string) => {
     setSelectedPage(path)
     setPageLoading(true)
@@ -983,6 +1012,51 @@ function WikiBrowser({ kbId }: { kbId: string }) {
             <AlertCircle size={12}/> {wikiJob.error}
           </div>
         )}
+
+        {/* Schedule toggle */}
+        <div className="mt-3 border-t border-gray-100 pt-3">
+          <button
+            onClick={() => setShowSchedule(v => !v)}
+            className="text-xs text-gray-500 hover:text-gray-700 flex items-center gap-1"
+          >
+            {showSchedule ? <ChevronDown size={12}/> : <ChevronRight size={12}/>}
+            定时自动重编译
+            {scheduleData?.enabled && (
+              <span className="ml-1 px-1.5 py-0.5 bg-green-100 text-green-700 rounded text-xs font-medium">已开启</span>
+            )}
+          </button>
+          {showSchedule && (
+            <div className="mt-2 flex items-center gap-4 flex-wrap">
+              <label className="flex items-center gap-2 text-xs text-gray-700">
+                <input
+                  type="checkbox"
+                  checked={scheduleData?.enabled ?? false}
+                  onChange={e => scheduleMut.mutate({ enabled: e.target.checked, interval: scheduleData?.interval ?? 'weekly' })}
+                  className="rounded"
+                />
+                启用定时编译
+              </label>
+              <div className="flex items-center gap-2">
+                <label className="text-xs text-gray-600">周期:</label>
+                <select
+                  value={scheduleData?.interval ?? 'weekly'}
+                  onChange={e => scheduleMut.mutate({ enabled: scheduleData?.enabled ?? false, interval: e.target.value as 'daily' | 'weekly' })}
+                  className="text-xs border border-gray-300 rounded px-2 py-1"
+                  disabled={!scheduleData?.enabled}
+                >
+                  <option value="daily">每天</option>
+                  <option value="weekly">每周</option>
+                </select>
+              </div>
+              {scheduleData?.next_run && scheduleData.enabled && (
+                <span className="text-xs text-gray-400">下次: {scheduleData.next_run.slice(0, 16)}</span>
+              )}
+              {scheduleData?.last_run && (
+                <span className="text-xs text-gray-400">上次: {scheduleData.last_run.slice(0, 16)}</span>
+              )}
+            </div>
+          )}
+        </div>
       </div>
 
       {/* Wiki browser */}
@@ -1053,7 +1127,7 @@ function QAPanel({
   }, [state.answer, state.streaming])
 
   const modeLabel: Record<string, string> = {
-    bm25: 'BM25', lambda: 'LambdaRAG', vector: '向量', wiki: 'Wiki',
+    bm25: 'BM25', lambda: 'LambdaRAG', vector: '向量', wiki: 'Wiki', fusion: 'RAG Fusion',
   }
 
   return (
@@ -1208,6 +1282,7 @@ function SearchTest({ kbId }: { kbId: string }) {
     { value: 'lambda', label: 'LambdaRAG 四路融合' },
     { value: 'vector', label: '向量语义' },
     { value: 'wiki', label: 'Wiki 全文' },
+    { value: 'fusion', label: 'RAG Fusion(多查询+RRF)' },
   ]
 
   const startQA = (side: 'left' | 'right', mode: string) => {