LangChain中LLM无法可靠检索知识图谱节点/信息的求助
问题:LangChain中NetworkxEntityGraph无法被GraphQAChain正确识别
问题背景
我基于表格构建了一个简易知识图谱(与实际图谱存在相同问题),通过NetworkxEntityGraph及循环语句创建,代码如下:
依赖导入与LLM初始化
import pandas as pd import numpy as np import os import time from langchain.chains import GraphQAChain from langchain_community.graphs.networkx_graph import NetworkxEntityGraph import networkx as nx from langchain.llms import OpenAI from langchain.chains import RetrievalQA # Manage the API keys from dotenv import load_dotenv load_dotenv(dotenv_path='./API_KEYs.env') # Google from langchain_google_genai import GoogleGenerativeAI import google.generativeai as genai GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY') genai.configure(api_key=GOOGLE_API_KEY) llm = GoogleGenerativeAI(model='gemini-pro', google_api_key=GOOGLE_API_KEY)
图谱构建代码
fake_data = {'entity_a': ['Joanie', 'Johny', 'I'], 'entity_b': ['Chachi', 'Here', 'Jenn-ay'], 'interaction': ['loves', 'Where_he_is', 'still_loves']} fake_data = pd.DataFrame(fake_data) G = NetworkxEntityGraph() #### ---- Add nodes ---- #### for id, row in fake_data.iterrows(): G._graph.add_node(row['entity_a']) G._graph.add_node(row['entity_b']) #### ---- Add edges ---- #### for id, row in fake_data.iterrows(): G._graph.add_edge( row['entity_a'], row['entity_b'], relation=row['interaction'] )
问题现象
直接查询图谱可正常获取节点及关系:
neighbors = list(G._graph.neighbors("Joanie")) related_edges = list(G._graph.edges("Joanie", data=True)) print("Neighbors:", neighbors) print("Related Edges:", related_edges)
输出:
Neighbors: ['Chachi'] Related Edges: [('Joanie', 'Chachi', {'relation': 'loves'})]
但使用GraphQAChain调用LLM时,无法识别图谱内容:
chain = GraphQAChain.from_llm( llm=llm, graph=G, verbose=True ) question = "Tell me about Joanie's relation to the other people in the graph." chain.invoke(question)
输出:
> Entering new GraphQAChain chain... Entities Extracted: NONE Full Context: > Finished chain. {'query': "Tell me about Joanie's relation to the other people in the graph.", 'result': 'This context does not mention anything about Joanie or her relation to the other people in the graph, so I cannot answer this question from the provided context.'}
即使是简单问题“Is Joanie in this graph?”,LLM仍返回“I don't know”。尝试使用旧教程中的GraphRetriever,发现该类已在LangChain更新后移除;后续测试中,即使LLM提取到实体Joanie且上下文显示“Joanie loves Chachi”,仍返回“I don't know”。
解决方案
针对LangChain最新版本的调整,给出以下修复步骤:
1. 使用公开方法构建图谱,避免操作私有属性
NetworkxEntityGraph的_graph是私有属性,直接操作可能导致LangChain无法识别节点和关系元数据。改用公开的add_node和add_edge方法:
G = NetworkxEntityGraph() for id, row in fake_data.iterrows(): # 添加节点时指定实体类型,帮助LLM识别 G.add_node(row['entity_a'], type="Person") G.add_node(row['entity_b'], type="Person") # 添加边并指定关系类型 G.add_edge(row['entity_a'], row['entity_b'], relation=row['interaction'])
2. 自定义实体提取逻辑适配Gemini
默认的实体提取器可能对Gemini的输出格式适配不佳,手动定义实体提取的Prompt和Chain:
from langchain.chains import LLMChain from langchain.prompts import PromptTemplate # 自定义实体提取Prompt,明确要求提取人物实体 entity_extraction_prompt = PromptTemplate( input_variables=["question"], template="Extract all person entities mentioned in the question. Return only the entities as a comma-separated list with no extra text.\nQuestion: {question}" ) # 创建实体提取Chain entity_extractor = LLMChain(llm=llm, prompt=entity_extraction_prompt) # 初始化GraphQAChain时指定自定义实体提取器 chain = GraphQAChain.from_llm( llm=llm, graph=G, entity_extractor=entity_extractor, verbose=True )
3. 重写GraphQAChain的上下文获取逻辑
默认的上下文获取可能未正确从Networkx图谱中提取关系数据,手动替换该方法:
from langchain.chains.graph_qa.base import GraphQAChain def custom_get_context(self, entities): context_parts = [] for entity in entities: # 获取实体的所有关联边 edges = list(self.graph._graph.edges(entity, data=True)) for edge in edges: # 格式化关系描述 context_parts.append(f"{edge[0]} {edge[2]['relation']} {edge[1]}") # 同时添加实体存在的信息 context_parts.append(f"{entity} exists in the graph.") return "\n".join(context_parts) # 替换原有的上下文获取方法 GraphQAChain._get_context = custom_get_context
4. 验证图谱元数据正确性
添加代码确认LangChain能识别图谱中的实体和关系:
print("Registered entities:", G.get_entities()) print("Registered relationships:", G.get_relationships())
如果输出为空,需手动补充NetworkxEntityGraph的元数据注册逻辑,或确保add_node/add_edge方法正确更新元数据。
内容的提问来源于stack exchange,提问作者Topher
相关产品推荐
相关产品推荐

