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

langgraph: _build_chunks 按 id 去重,消除重复 doc_id 的幂等覆盖

验证发现:microbiome 数据源 809 条中有 30 个 id 重复(779 个唯一 id),
_build_chunks 会生成 844 个重复 doc_id,被 Chroma 幂等覆盖,导致日志声称
25550 块而实际入库 24706 块(不一致、且浪费 embedding 计算)。
现按 item id 去重(保留先出现者)并告警重复数量,日志与入库数一致。
Xiaogang Liao 5 дней назад
Родитель
Сommit
732ec1af6e
1 измененных файлов с 15 добавлено и 1 удалено
  1. 15 1
      cfc-langgraph/app/tasks/knowledge_sync.py

+ 15 - 1
cfc-langgraph/app/tasks/knowledge_sync.py

@@ -74,11 +74,25 @@ def _build_chunks(splitter, items: list[dict], source: str) -> tuple[list[Docume
     """
     """
     chunks: list[Document] = []
     chunks: list[Document] = []
     ids: list[str] = []
     ids: list[str] = []
+    seen_ids: set[str] = set()
+    unique_items: list[dict] = []
     for item in items:
     for item in items:
+        item_id = item.get("id")
+        if item_id is None:
+            continue
+        key = str(item_id)
+        if key in seen_ids:
+            continue  # 数据源重复 id(如 join 重复行),仅保留先出现者,避免 doc_id 幂等覆盖
+        seen_ids.add(key)
+        unique_items.append(item)
+    if len(unique_items) != len(items):
+        logger.warning("知识库同步[%s]: 数据源含 %d 条重复 id,去重后 %d 篇",
+                       source, len(items) - len(unique_items), len(unique_items))
+    for item in unique_items:
         item_id = item.get("id")
         item_id = item.get("id")
         title = item.get("title", "")
         title = item.get("title", "")
         content = item.get("content", "")
         content = item.get("content", "")
-        if item_id is None or not content:
+        if not content:
             continue
             continue
         # 若 content 已含 title 前缀则不重复拼接
         # 若 content 已含 title 前缀则不重复拼接
         full_text = f"{title}\n\n{content}" if title and title not in content else content
         full_text = f"{title}\n\n{content}" if title and title not in content else content