使用 Neo4j 和 LangChain 构建 RAG 应用程序中的知识图谱并从中检索信息的实用指南
编者注:以下是由 Tomaz Bratanic 撰写的客座博客文章,他专注于 Neo4j 的图机器学习和 GenAI 研究。Neo4j。Neo4j 是一家图数据库和分析公司,帮助组织深入、轻松、快速地查找数十亿数据连接中隐藏的关系和模式。
图检索增强生成 (Graph RAG) 正在获得动力,并作为传统向量搜索检索方法的强大补充而崭露头角。这种方法利用图数据库的结构化特性,将数据组织为节点和关系,从而增强检索信息的深度和上下文相关性。

图谱非常适合以结构化方式表示和存储异构且相互关联的信息,毫不费力地捕获跨不同数据类型的复杂关系和属性。相比之下,向量数据库通常难以处理此类结构化信息,因为它们的优势在于通过高维向量处理非结构化数据。在您的 RAG 应用程序中,您可以将结构化图数据与通过非结构化文本进行的向量搜索相结合,以实现两全其美,这正是我们将在本博文中进行的操作。
知识图谱很棒,但如何创建呢? 构建知识图谱通常是利用基于图的数据表示能力中最具挑战性的一步。它涉及收集和结构化数据,这需要深入了解领域和图建模。为了简化此过程,我们一直在尝试使用 LLM。LLM 凭借其对语言和上下文的深刻理解,可以自动化知识图谱创建过程的很大一部分。通过分析文本数据,这些模型可以识别实体,理解实体之间的关系,并建议如何在图结构中最好地表示它们。作为这些实验的结果,我们在 LangChain 中添加了图构建模块的第一个版本,我们将在本博文中演示。
代码可在 GitHub 上找到。
Neo4j 环境设置
您需要设置 Neo4j 实例才能跟随本博文中的示例。最简单的方法是在 Neo4j Aura 上启动一个免费实例,它提供 Neo4j 数据库的云实例。或者,您也可以通过下载 Neo4j Desktop 应用程序并创建本地数据库实例来设置 Neo4j 数据库的本地实例。
os.environ["OPENAI_API_KEY"] = "sk-"
os.environ["NEO4J_URI"] = "bolt://localhost:7687"
os.environ["NEO4J_USERNAME"] = "neo4j"
os.environ["NEO4J_PASSWORD"] = "password"
graph = Neo4jGraph()
此外,您必须提供一个 OpenAI 密钥,因为我们将在本博文中使用他们的模型。
数据摄取
对于此演示,我们将使用 伊丽莎白一世 的维基百科页面。我们可以利用 LangChain 加载器 来无缝地从维基百科获取和拆分文档。
# Read the wikipedia article
raw_documents = WikipediaLoader(query="Elizabeth I").load()
# Define chunking strategy
text_splitter = TokenTextSplitter(chunk_size=512, chunk_overlap=24)
documents = text_splitter.split_documents(raw_documents[:3])
现在是时候根据检索到的文档构建图谱了。为此,我们实施了一个 LLMGraphTransformer
模块,该模块显着简化了在图数据库中构建和存储知识图谱的过程。
llm=ChatOpenAI(temperature=0, model_name="gpt-4-0125-preview")
llm_transformer = LLMGraphTransformer(llm=llm)
# Extract graph data
graph_documents = llm_transformer.convert_to_graph_documents(documents)
# Store to neo4j
graph.add_graph_documents(
graph_documents,
baseEntityLabel=True,
include_source=True
)
您可以定义希望知识图谱生成链使用的 LLM。目前,我们仅支持 OpenAI 和 Mistral 的函数调用模型。但是,我们计划在未来扩展 LLM 的选择范围。在此示例中,我们使用最新的 GPT-4。请注意,生成的图谱的质量很大程度上取决于您使用的模型。理论上,您始终希望使用功能最强大的模型。LLM 图转换器返回图文档,可以通过 add_graph_documents
方法将其导入到 Neo4j 中。 baseEntityLabel
参数为每个节点分配一个额外的 __Entity__
标签,从而增强索引和查询性能。 include_source
参数将节点链接到其原始文档,从而方便数据可追溯性和上下文理解。
您可以在 Neo4j 浏览器中检查生成的图谱。

请注意,此图像仅表示为了清晰起见而生成的图谱的一部分。
用于 RAG 的混合检索
在生成图谱之后,我们将使用混合检索方法,该方法将向量索引和关键字索引与用于 RAG 应用程序的图检索相结合。

该图表说明了一个检索过程,该过程从用户提出问题开始,然后将问题定向到 RAG 检索器。此检索器使用关键字和向量搜索来搜索非结构化文本数据,并将其与从知识图谱收集的信息相结合。由于 Neo4j 同时具有关键字索引和向量索引,因此您可以使用单个数据库系统实现所有三种检索选项。从这些来源收集的数据被馈送到 LLM 以生成并交付最终答案。
非结构化数据检索器
您可以使用 Neo4jVector.from_existing_graph
方法将关键字检索和向量检索都添加到文档中。此方法为混合搜索方法配置关键字搜索索引和向量搜索索引,目标是标记为 Document
的节点。此外,它还会计算缺失的文本嵌入值。
vector_index = Neo4jVector.from_existing_graph(
OpenAIEmbeddings(),
search_type="hybrid",
node_label="Document",
text_node_properties=["text"],
embedding_node_property="embedding"
)
然后可以使用 similarity_search
方法调用向量索引。
图检索器
另一方面,配置图检索器更复杂,但提供了更大的自由度。在此示例中,我们将使用全文索引来识别相关节点,然后返回其直接邻域。

图检索器首先识别输入中的相关实体。为了简单起见,我们指示 LLM 识别人物、组织和地点。为了实现这一点,我们将使用 LCEL 和新添加的 with_structured_output
方法来实现。
# Extract entities from text
class Entities(BaseModel):
"""Identifying information about entities."""
names: List[str] = Field(
...,
description="All the person, organization, or business entities
that " "appear in the text",
)
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are extracting organization and person entities from the
text.",
),
(
"human",
"Use the given format to extract information from the
following"
"input: {question}",
),
]
)
entity_chain = prompt | llm.with_structured_output(Entities)
让我们测试一下
entity_chain.invoke({"question": "Where was Amelia Earhart born?"}).names
# ['Amelia Earhart']
太棒了,现在我们可以检测问题中的实体,让我们使用全文索引将它们映射到知识图谱。首先,我们需要定义一个全文索引和一个函数,该函数将生成允许一些拼写错误的全文查询,我们在此处不赘述。
graph.query(
"CREATE FULLTEXT INDEX entity IF NOT EXISTS FOR (e:__Entity__) ON EACH [e.id]")
def generate_full_text_query(input: str) -> str:
"""
Generate a full-text search query for a given input string.
This function constructs a query string suitable for a full-text
search. It processes the input string by splitting it into words and
appending a similarity threshold (~2 changed characters) to each
word, then combines them using the AND operator. Useful for mapping
entities from user questions to database values, and allows for some
misspelings.
"""
full_text_query = ""
words = [el for el in remove_lucene_chars(input).split() if el]
for word in words[:-1]:
full_text_query += f" {word}~2 AND"
full_text_query += f" {words[-1]}~2"
return full_text_query.strip()
现在让我们将它们放在一起。
# Fulltext index query
def structured_retriever(question: str) -> str:
"""
Collects the neighborhood of entities mentioned
in the question
"""
result = ""
entities = entity_chain.invoke({"question": question})
for entity in entities.names:
response = graph.query(
"""CALL db.index.fulltext.queryNodes('entity', $query,
{limit:2})
YIELD node,score
CALL {
MATCH (node)-[r:!MENTIONS]->(neighbor)
RETURN node.id + ' - ' + type(r) + ' -> ' + neighbor.id AS
output
UNION
MATCH (node)<-[r:!MENTIONS]-(neighbor)
RETURN neighbor.id + ' - ' + type(r) + ' -> ' + node.id AS
output
}
RETURN output LIMIT 50
""",
{"query": generate_full_text_query(entity)},
)
result += "\n".join([el['output'] for el in response])
return result
structured_retriever
函数首先检测用户问题中的实体。接下来,它迭代检测到的实体,并使用 Cypher 模板来检索相关节点的邻域。让我们测试一下!
print(structured_retriever("Who is Elizabeth I?"))
# Elizabeth I - BORN_ON -> 7 September 1533
# Elizabeth I - DIED_ON -> 24 March 1603
# Elizabeth I - TITLE_HELD_FROM -> Queen Of England And Ireland
# Elizabeth I - TITLE_HELD_UNTIL -> 17 November 1558
# Elizabeth I - MEMBER_OF -> House Of Tudor
# Elizabeth I - CHILD_OF -> Henry Viii
# and more...
最终检索器
正如我们在开始时提到的,我们将结合非结构化检索器和图检索器来创建最终上下文,该上下文将传递给 LLM。
def retriever(question: str):
print(f"Search query: {question}")
structured_data = structured_retriever(question)
unstructured_data = [el.page_content for el in vector_index.similarity_search(question)]
final_data = f"""Structured data:
{structured_data}
Unstructured data:
{"#Document ". join(unstructured_data)}
"""
return final_data
由于我们正在处理 Python,我们可以简单地使用 f-string 连接输出。
定义 RAG 链
我们已成功实施 RAG 的检索组件。接下来,我们引入一个提示,该提示利用集成的混合检索器提供的上下文来生成响应,从而完成 RAG 链的实施。
template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
chain = (
RunnableParallel(
{
"context": _search_query | retriever,
"question": RunnablePassthrough(),
}
)
| prompt
| llm
| StrOutputParser()
)
最后,我们可以继续测试我们的混合 RAG 实施。
chain.invoke({"question": "Which house did Elizabeth I belong to?"})
# Search query: Which house did Elizabeth I belong to?
# 'Elizabeth I belonged to the House of Tudor.'
我还加入了一个查询重写功能,使 RAG 链能够适应允许后续问题的对话设置。鉴于我们使用向量和关键字搜索方法,我们必须重写后续问题以优化我们的搜索过程。
chain.invoke(
{
"question": "When was she born?",
"chat_history": [("Which house did Elizabeth I belong to?",
"House Of Tudor")],
}
)
# Search query: When was Elizabeth I born?
# 'Elizabeth I was born on 7 September 1533.'
您可以观察到 When was she born?
首先被重写为 When was Elizabeth I born?
。然后使用重写的查询来检索相关上下文并回答问题。
总结
随着 LLMGraphTransformer
的引入,生成知识图谱的过程现在应该更顺畅、更易于访问,从而使任何希望通过知识图谱提供的深度和上下文来增强其基于 RAG 的应用程序的人员更容易实现。这仅仅是一个开始,因为我们计划进行许多改进。
如果您对我们使用 LLM 生成图谱有任何见解、建议或问题,请随时与我们联系。
代码可在 GitHub 上找到。