GraphRAG 实体提取的别名局限性分析

1. 问题概述

GraphRAG 在实体提取阶段,将同一实体的不同别名视为独立实体,导致知识图谱中出现实体碎片化。以”孙悟空”为例:

文本A: "孙悟空大闹天宫"        → 实体: 孙悟空
文本B: "孙行者三打白骨精"      → 实体: 孙行者
文本C: "齐天大圣被压五行山下"  → 实体: 齐天大圣

最终图谱中出现三个独立节点,它们之间没有任何关联。查询”孙悟空做了什么”时,只能找到”大闹天宫”,而”三打白骨精”和”被压五行山下”的关系链完全断裂。

2. 当前 GraphRAG 的处理方式

2.1 实体提取阶段

源码: packages/graphrag/graphrag/index/operations/extract_graph/graph_extractor.py

LLM 从每个 text unit 中提取实体,核心逻辑:

# graph_extractor.py → _process_result()
if record_type == '"entity"' and len(record_attributes) >= 4:
    entity_name = clean_str(record_attributes[1].upper())  # 名称统一大写
    entity_type = clean_str(record_attributes[2].upper())
    entity_description = clean_str(record_attributes[3])
    entities.append({
        "title": entity_name,
        "type": entity_type,
        "description": entity_description,
        "source_id": source_id,
    })

关键点:
– 实体名称仅做 clean_str() + upper() 处理(去除 HTML 转义和控制字符,转大写)
没有任何别名识别或归一化逻辑
– LLM 提取什么名字,就原样记录什么名字

2.2 实体合并阶段

源码: packages/graphrag/graphrag/index/operations/extract_graph/extract_graph.py

多个 text unit 提取的实体通过 _merge_entities() 合并:

def _merge_entities(entity_dfs) -> pd.DataFrame:
    all_entities = pd.concat(entity_dfs, ignore_index=True)
    return (
        all_entities
        .groupby(["title", "type"], sort=False)  # ← 仅按 title + type 分组
        .agg(
            description=("description", list),
            text_unit_ids=("source_id", list),
            frequency=("source_id", "count"),
        )
        .reset_index()
    )

合并策略是 精确字符串匹配:只有 title(名称)和 type(类型)完全相同的实体才会被合并。

这意味着:
孙悟空孙行者不合并(title 不同)
SUN WUKONGMONKEY KING不合并
TechGlobalTG不合并(缩写 vs 全称)

2.3 描述摘要阶段

源码: packages/graphrag/graphrag/index/operations/summarize_descriptions/

合并后,同一实体(title 相同)的多条 description 会通过 LLM 汇总为一条:

# description_summary_extractor.py
async def __call__(self, id, descriptions):
    if len(descriptions) == 0:
        result = ""
    elif len(descriptions) == 1:
        result = descriptions[0]  # 只有一条描述,直接使用
    else:
        result = await self._summarize_descriptions(id, descriptions)  # 多条描述,LLM 汇总

摘要 prompt 的设计:

Given one or more entities, and a list of descriptions, all related to the same entity
or group of entities. Please concatenate all of these into a single, comprehensive
description. If the provided descriptions are contradictory, please resolve the
contradictions and provide a single, coherent summary.

问题:这个摘要步骤只处理已经被 _merge_entities() 合并到一起的描述。由于别名实体根本没有被合并,它们的描述永远不会被放在一起摘要。

2.4 关系的连带断裂

源码: extract_graph.py → _merge_relationships()

def _merge_relationships(relationship_dfs) -> pd.DataFrame:
    all_relationships = pd.concat(relationship_dfs, ignore_index=False)
    return (
        all_relationships
        .groupby(["source", "target"], sort=False)  # ← 按 source + target 精确匹配
        .agg(
            description=("description", list),
            text_unit_ids=("source_id", list),
            weight=("weight", "sum"),
        )
        .reset_index()
    )

关系合并同样依赖精确字符串匹配。假设:

文本A 提取: (孙悟空) --师徒--> (唐僧)
文本B 提取: (孙行者) --师徒--> (唐僧)

这两条关系 不会合并,因为 source 不同。最终图谱中:
孙悟空 → 唐僧 (weight=1)
孙行者 → 唐僧 (weight=1)

而正确的结果应该是一条 weight=2 的关系。更严重的是,如果某些关系只出现在别名上下文中,查询主名称时完全找不到。

2.5 查询阶段的影响

源码: packages/graphrag/graphrag/query/context_builder/entity_extraction.py

查询时通过 embedding 向量相似度匹配实体:

def map_query_to_entities(query, text_embedding_vectorstore, text_embedder, ...):
    search_results = text_embedding_vectorstore.similarity_search_by_text(
        text=query,
        text_embedder=lambda t: text_embedder.embedding(input=[t]).first_embedding,
        k=k * oversample_scaler,
    )

查询”孙悟空”时,embedding 相似度可能匹配到”孙悟空”节点,但”孙行者”和”齐天大圣”节点的 embedding 距离较远,可能不在 top-k 结果中。即使匹配到了,它们作为独立节点,各自的关系子图也是割裂的。

3. 根本原因总结

环节 当前行为 问题
LLM 提取 按文本中出现的名称原样提取 不同别名产生不同 entity title
实体合并 groupby(["title", "type"]) 精确匹配 别名实体无法合并
描述摘要 只摘要已合并实体的描述 别名实体的描述永远分离
关系合并 groupby(["source", "target"]) 精确匹配 别名导致关系碎片化
查询匹配 embedding 相似度搜索 别名节点可能不在 top-k 中
Prompt 无别名识别指令 LLM 没有被引导去统一别名

4. 解决方案:LLM 别名发现 + 外部知识库确定性合并

整体思路:两层保障。LLM 在提取时发现别名关系,覆盖大部分情况;外部知识库对特别关心的实体提供确定性兜底,确保关键实体不会因 LLM 不一致而遗漏。

4.1 整体流程

                    ┌─────────────────────┐
                    │  外部别名知识库       │
                    │  (JSON/DB, 人工维护)  │
                    └──────────┬──────────┘
                               │ 加载
                               ▼
text units ──→ LLM 提取(含aliases) ──→ 别名归一化 ──→ _merge_entities ──→ 后续流程
                                         ▲
                                         │
                              ┌──────────┴──────────┐
                              │ 1. 外部知识库优先匹配  │
                              │ 2. LLM aliases 补充   │
                              └─────────────────────┘

4.2 外部别名知识库

用户维护一份别名映射文件,定义特别关心的实体的 canonical name 和所有已知别名:

// alias_kb.json
[
  {
    "canonical": "孙悟空",
    "aliases": ["孙行者", "齐天大圣", "美猴王", "斗战胜佛"]
  },
  {
    "canonical": "猪八戒",
    "aliases": ["天蓬元帅", "猪悟能", "猪刚鬣", "呆子", "二师兄"]
  }
]

特点:
确定性:知识库中的映射是硬规则,不依赖 LLM 判断,100% 保证合并
可控:只需覆盖业务上特别关心的实体,不需要穷举所有实体
可增量维护:发现新的漏合并时,加一条记录即可

4.3 LLM 提取阶段增加 aliases 字段

修改提取 prompt(prompts/index/extract_graph.py),让 LLM 在提取实体时同时输出别名:

1. Identify all entities. For each identified entity, extract the following information:
- entity_name: Name of the entity, capitalized
- entity_type: One of the following types: [{entity_types}]
- entity_description: Comprehensive description of the entity's attributes and activities
- aliases: Other names, abbreviations, or titles for this entity found in the text.
  If none, leave empty.
Format each entity as ("entity"<|><entity_name><|><entity_type><|><entity_description><|><aliases>)

graph_extractor.py_process_result() 中解析 aliases:

if record_type == '"entity"' and len(record_attributes) >= 4:
    entity_name = clean_str(record_attributes[1].upper())
    entity_type = clean_str(record_attributes[2].upper())
    entity_description = clean_str(record_attributes[3])
    aliases = []
    if len(record_attributes) >= 5:
        aliases = [clean_str(a.upper()) for a in record_attributes[4].split(",") if a.strip()]
    entities.append({
        "title": entity_name,
        "type": entity_type,
        "description": entity_description,
        "source_id": source_id,
        "aliases": aliases,
    })

LLM 发现的别名覆盖外部知识库未收录的长尾情况。例如文本中出现”猴哥”指代孙悟空,知识库没收录,但 LLM 能识别并输出 aliases: 猴哥

4.4 别名归一化:两层合并

_merge_entities() 之前,先构建统一的 alias → canonical 映射,外部知识库优先:

def _build_alias_map(entity_dfs, alias_kb_path=None):
    """构建 alias → canonical 映射。外部知识库优先,LLM aliases 补充。"""
    alias_to_canonical = {}

    # 第一层:外部知识库(确定性,优先级最高)
    if alias_kb_path:
        import json
        with open(alias_kb_path) as f:
            kb_entries = json.load(f)
        for entry in kb_entries:
            canonical = entry["canonical"].upper()
            for alias in entry["aliases"]:
                alias_to_canonical[alias.upper()] = canonical

    # 第二层:LLM 提取的 aliases(补充知识库未覆盖的)
    all_entities = pd.concat(entity_dfs, ignore_index=True)
    name_freq = all_entities["title"].value_counts()

    for _, row in all_entities.iterrows():
        title = row["title"]
        for alias in row.get("aliases", []):
            if not alias or alias == title:
                continue
            # 外部知识库已有映射的,不覆盖
            if alias in alias_to_canonical or title in alias_to_canonical:
                continue
            # LLM aliases:频率高的作为 canonical
            if name_freq.get(alias, 0) > name_freq.get(title, 0):
                alias_to_canonical[title] = alias
            else:
                alias_to_canonical[alias] = title

    # 传递闭包:A→B, B→C 则 A→C
    def resolve(name):
        visited = set()
        while name in alias_to_canonical and name not in visited:
            visited.add(name)
            name = alias_to_canonical[name]
        return name

    return resolve

extract_graph() 中,合并前统一重写实体和关系中的名称:

async def extract_graph(...) -> tuple[pd.DataFrame, pd.DataFrame]:
    # ... LLM 提取 ...
    results = await derive_from_rows(...)

    entity_dfs = [r[0] for r in results if r]
    relationship_dfs = [r[1] for r in results if r]

    # 别名归一化(新增)
    resolve = _build_alias_map(entity_dfs, alias_kb_path=config.alias_kb_path)
    for df in entity_dfs:
        df["title"] = df["title"].map(resolve)
    for df in relationship_dfs:
        df["source"] = df["source"].map(resolve)
        df["target"] = df["target"].map(resolve)

    # 原有合并逻辑(现在能正确合并别名实体)
    entities = _merge_entities(entity_dfs)
    relationships = _merge_relationships(relationship_dfs)
    relationships = filter_orphan_relationships(relationships, entities)

    return (entities, relationships)

4.5 效果对比

以”孙悟空”为例:

场景 当前行为 改进后
文本A提到”孙悟空”,文本B提到”孙行者” 两个独立节点,关系断裂 外部知识库命中,统一为”孙悟空”
文本C提到”猴哥”(知识库未收录) 独立节点 LLM aliases 发现,归一化到”孙悟空”
文本D提到”天蓬元帅”(知识库有) 独立节点 外部知识库命中,统一为”猪八戒”
文本E提到某个冷门缩写(两层都没覆盖) 独立节点 仍为独立节点,发现后加入知识库即可

6. 源码文件索引

文件 作用
prompts/index/extract_graph.py 实体提取 prompt 定义
index/operations/extract_graph/graph_extractor.py LLM 提取结果解析,实体/关系构建
index/operations/extract_graph/extract_graph.py 实体/关系合并逻辑(_merge_entities, _merge_relationships
index/operations/extract_graph/utils.py 孤儿关系过滤
index/operations/summarize_descriptions/ 描述摘要(仅处理已合并实体)
index/workflows/extract_graph.py 提取 workflow 编排
index/workflows/finalize_graph.py 图谱最终化(degree 计算、去重)
index/operations/finalize_entities.py 实体最终化(按 title 去重)
query/context_builder/entity_extraction.py 查询时实体匹配
index/utils/string.py clean_str() 字符串清洗
prompt_tune/template/extract_graph.py 可调优的提取 prompt 模板

Comments

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注