Files
AgentScript/agent/backend/app/knowledge/knowledge_service.py
T
HenryandClaude Code 26e13ff032 feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。
排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。

Co-Authored-By: Claude Code <[email protected]>
2026-11-13 13:48:41 +08:00

285 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
知识库服务编排层
================
【功能说明】
编排「解析 → 切分 → 向量化入库 → 检索」完整链路,
对外暴露入库、检索、重建索引、统计能力。
是《核心诉求》文档知识管理模块的业务门面。
【技术选型理由】
1. 门面模式:API 层只调本模块,不直接碰 loader/splitter/vector_store,
模块边界清晰(硬约束 3 低耦合高内聚)。
2. 入库粒度按「文件」管理(每个 chunk 的 metadata 带 source),
支持单文件增量重建,而不是只能全量清库。
【实现思路】
- ingest_directory():扫描目录 → 解析 → 切分 → 入库,返回统计与告警;
- ingest_file():单文件增量入库(先删旧 chunk 再写新);
- query():自然语言检索,返回带来源的命中结果;
- rebuild():清空后全量重建(素材大改后使用)。
【潜在风险与应对】
风险1:素材目录里有大量图片/zip → 解析告警刷屏。
应对:load_directory 已跳过并归入 warnings,统计里单列跳过数。
风险2:入库中途失败 → 半成品索引。
应对:按文件为单位提交(单文件内原子),失败文件进 warnings,
不影响其他文件;必要时用 rebuild() 一键重建。
风险3:检索耗时随数据量增长。
应对:Chroma 自带 HNSW 索引;top_k 限流;后续可加缓存。
"""
from __future__ import annotations
import logging
import uuid
from pathlib import Path
from typing import Any
from app.knowledge.document_loader import load_directory, load_file
from app.knowledge.embeddings import EmbeddingProvider
from app.knowledge.text_splitter import split_documents
from app.knowledge.vector_store import KnowledgeVectorStore
logger = logging.getLogger("agent.knowledge.service")
class KnowledgeService:
"""知识库业务门面:解析/切分/入库/检索"""
def __init__(
self,
vector_store: KnowledgeVectorStore,
embedding_provider: EmbeddingProvider,
) -> None:
self._vs = vector_store
self._embedding = embedding_provider
# ---------- 入库 ----------
def ingest_directory(self, directory: Path) -> dict[str, Any]:
"""
扫描目录并全量入库(**按 source 替换,不重复追加**)。
【数据正确性关键】入库前先按 source 删除旧 chunk,再写入新 chunk,
连点多次不会产生重复数据(M6 发现的隐患在此修复)。
"""
directory = Path(directory)
logger.info("开始知识库入库:%s", directory)
docs, warnings = load_directory(directory)
scanned = len({d.metadata.get("source") for d in docs})
chunks = split_documents(docs)
if not chunks:
return {
"scanned_files": scanned,
"ingested_chunks": 0,
"skipped": len(warnings),
"warnings": warnings + ["未解析出任何可入库文本"],
}
# 按 source 先清旧再写新(replace-by-source)
sources = {d.metadata.get("source", "") for d in docs if d.metadata.get("source")}
deleted_old = 0
for src in sources:
deleted_old += self._vs.delete_by_source(src)
ids = [f"chunk_{uuid.uuid4().hex[:16]}" for _ in chunks]
texts = [c.page_content for c in chunks]
metas = [c.metadata for c in chunks]
try:
self._vs.add_documents(texts, metas, ids)
except Exception as exc: # noqa: BLE001 - 入库失败要报清楚
logger.error("向量入库失败:%s", exc)
return {
"scanned_files": scanned,
"ingested_chunks": 0,
"skipped": len(warnings),
"warnings": warnings + [f"向量入库失败:{exc}"],
}
return {
"scanned_files": scanned,
"ingested_chunks": len(chunks),
"deleted_old_chunks": deleted_old,
"skipped": len(warnings),
"warnings": warnings,
}
def ingest_files(self, file_paths: list[str]) -> dict[str, Any]:
"""
批量入库指定文件(**按 source 替换**)。
【用途】前端文件选择 UI 勾选后调用,只向量化选中的文档。
【数据正确性】每个文件先按 source 删旧 chunk 再写新,多次勾选不重复。
"""
file_paths = [str(p) for p in file_paths if str(p).strip()]
if not file_paths:
return {
"requested_files": 0,
"success_files": 0,
"ingested_chunks": 0,
"deleted_old_chunks": 0,
"warnings": ["未选择任何文件"],
}
logger.info("批量入库指定文件:%d 个", len(file_paths))
all_chunks = []
warnings: list[str] = []
success_files = 0
deleted_old = 0
for fp in file_paths:
try:
docs = load_file(Path(fp))
chunks = split_documents(docs)
if not chunks:
warnings.append(f"文件无可入库文本:{Path(fp).name}")
continue
# replace-by-source
deleted_old += self._vs.delete_by_source(fp)
all_chunks.extend(chunks)
success_files += 1
except Exception as exc: # noqa: BLE001 - 单文件失败不影响其余
warnings.append(f"解析失败:{Path(fp).name},原因:{exc}")
logger.warning("解析失败:%s %s", fp, exc)
if not all_chunks:
return {
"requested_files": len(file_paths),
"success_files": 0,
"ingested_chunks": 0,
"deleted_old_chunks": deleted_old,
"warnings": warnings or ["全部文件均无可入库文本"],
}
ids = [f"chunk_{uuid.uuid4().hex[:16]}" for _ in all_chunks]
try:
self._vs.add_documents(
[c.page_content for c in all_chunks],
[c.metadata for c in all_chunks],
ids,
)
except Exception as exc: # noqa: BLE001
logger.error("批量入库失败:%s", exc)
return {
"requested_files": len(file_paths),
"success_files": 0,
"ingested_chunks": 0,
"deleted_old_chunks": deleted_old,
"warnings": warnings + [f"向量入库失败:{exc}"],
}
return {
"requested_files": len(file_paths),
"success_files": success_files,
"ingested_chunks": len(all_chunks),
"deleted_old_chunks": deleted_old,
"warnings": warnings,
}
def list_ingestible_files(self, directory: Path) -> list[dict[str, Any]]:
"""
递归列出目录下全部可入库文件(供前端文件选择 UI)。
【返回】列表,每项含 path / relative_path / name / size / file_type
"""
from app.knowledge.document_loader import SUPPORTED_EXTENSIONS
root = Path(directory)
if not root.exists():
return []
files: list[dict[str, Any]] = []
for p in sorted(root.rglob("*")):
if not p.is_file():
continue
if p.suffix.lower() not in SUPPORTED_EXTENSIONS:
continue
try:
size = p.stat().st_size
except OSError:
size = 0
files.append(
{
"path": str(p),
"relative_path": str(p.relative_to(root)).replace("\\", "/"),
"name": p.name,
"size": size,
"file_type": p.suffix.lower().lstrip("."),
}
)
return files
def ingest_file(self, file_path: Path) -> dict[str, Any]:
"""
单文件增量入库(先删旧 chunk 再写新 chunk)。
【返回】统计字典:file / deleted_old / ingested_chunks / warnings
"""
file_path = Path(file_path)
deleted = self._vs.delete_by_source(str(file_path))
try:
docs = load_file(file_path)
except Exception as exc: # noqa: BLE001
return {
"file": file_path.name,
"deleted_old": deleted,
"ingested_chunks": 0,
"warnings": [f"解析失败:{exc}"],
}
chunks = split_documents(docs)
if not chunks:
return {
"file": file_path.name,
"deleted_old": deleted,
"ingested_chunks": 0,
"warnings": ["该文件无可入库文本"],
}
ids = [f"chunk_{uuid.uuid4().hex[:16]}" for _ in chunks]
self._vs.add_documents(
[c.page_content for c in chunks],
[c.metadata for c in chunks],
ids,
)
return {
"file": file_path.name,
"deleted_old": deleted,
"ingested_chunks": len(chunks),
"warnings": [],
}
def rebuild(self, directory: Path) -> dict[str, Any]:
"""清空后全量重建(素材大改后使用)。"""
logger.info("重建知识库索引:%s", directory)
self._vs.clear()
return self.ingest_directory(directory)
# ---------- 检索 ----------
def query(self, question: str, top_k: int = 5) -> list[dict[str, Any]]:
"""
自然语言检索项目知识。
【返回】命中列表,每项含 text / metadata / score / source。
"""
hits = self._vs.search(question, top_k=top_k)
for h in hits:
h["source"] = h.get("metadata", {}).get("source", "")
h["filename"] = h.get("metadata", {}).get("filename", "")
return hits
# ---------- 统计 ----------
def stats(self) -> dict[str, Any]:
"""返回向量库统计信息。"""
return {
"total_chunks": self._vs.count,
"embedding_provider": self._embedding.name,
}