结合Neo4j与Milvus的图谱与向量搜索构建GraphRAG Agent

文摘   2025-02-04 11:01   安徽  

本文介绍了如何使用 GPT-4o、Llama 3.1 8B、LangGraph、Neo4j 图数据库和 Milvus 向量数据库构建一个 GraphRAG Agent。该 Agent 结合了图数据库和向量搜索的强大功能,为用户查询提供准确且相关的答案。


传统的 RAG 系统仅依赖向量数据库来检索相关文档。而我们的方法则进一步结合了 Neo4j,用以捕捉实体和概念之间的关系,从而提供更为细致的信息理解。通过将这两种技术结合,我们希望构建一个更加稳健且富有信息的 RAG 系统。




构建RAG Agent  



我们的 Agent 遵循了过一系列 LangGraph 组件来实现的三个关键组件:

  • 路由:一个专门的路由机制根据查询决定是否使用向量数据库、知识图谱,或两者的结合。 

  • 回退:在初始检索不足的情况下,Agent 会回退到使用 Tavily 进行网页搜索。

  • 自我修正:Agent 会评估自己的答案,并尝试纠正幻觉或不准确的内容。


接下来,我们还有其他组件,例如:

  • 检索:我们使用 Milvus,一个开源的高性能向量数据库,来存储和检索与用户查询在语义上相似的文档片段。

  • 图谱增强:使用 Neo4j 从检索到的文档构建知识图谱,通过关系和实体丰富上下文。

  • LLM 集成:使用本地 LLM Llama 3.1 8B 生成答案,并评估检索到的信息的相关性和准确性,而 GPT-4o 则用于生成 Neo4j 所使用的查询语言 Cypher。


GraphRAG 架构  



我们 GraphRAG Agent 的架构可以通过一个包含多个互联节点的工作流来可视化:

  • 问题路由:Agent 首先分析问题,以确定最佳的检索策略(向量搜索、图谱搜索或两者结合)。

  • 检索:根据路由决策,从 Milvus 中检索相关文档,或者从 Neo4j 图谱中提取信息。

  • 生成:LLM 使用检索到的上下文生成答案。

  • 评估:Agent 评估生成的答案是否相关、准确,以及是否存在幻觉。

  • 优化(如有必要):如果答案被认为不令人满意,Agent 可能会优化搜索或尝试纠正错误。



代码实现  



为了展示我们 LLM Agent 的能力,下面我们将探讨两个不同的组件:图生成和复合Agent。


虽然完整的代码可以在本文底部找到,但这些代码片段能帮助更好地理解这些 Agent 如何在 LangChain 框架中工作。


图生成


该组件旨在通过利用 Neo4j 的能力来改进问答过程。它通过利用嵌入在 Neo4j 图数据库中的知识来回答问题。其工作流程如下:

  1. GraphCypherQAChain:允许 LLM 与 Neo4j 图数据库进行交互。它通过两种方式使用LLM:

    1. cypher_llm:此 LLM 实例负责生成 Cypher 查询,以根据用户的问题从图中提取相关信息。

    2. 验证:确保 Cypher 查询经过验证,以确保语法正确。

  2. 上下文检索:在 Neo4j 图中执行验证后的查询,以检索必要的上下文。

  3. 答案生成:语言模型使用检索到的上下文生成答案。


### Generate Cypher Queryllm = ChatOllama(model=local_llm, temperature=0)
# Chaingraph_rag_chain = GraphCypherQAChain.from_llm( cypher_llm=llm, qa_llm=llm, validate_cypher=True, graph=graph, verbose=True, return_intermediate_steps=True, return_direct=True, )
# Runquestion = "agent memory"generation = graph_rag_chain.invoke({"query": question})


该组件使 RAG 系统能够利用 Neo4j,从而提供更全面、准确的答案。


复合 Agent,图与向量

这里是关键:我们的 Agent 可以将 Milvus 和 Neo4j 的结果结合起来,从而更好地理解信息,提供更准确、细致的答案。其工作流程如下:

  1. 提示:我们定义一个提示,指示 LLM 使用来自 Milvus 和 Neo4j 的上下文来回答问题。

  2. 检索:Agent 从 Milvus(使用向量搜索)和 Neo4j(使用图生成)中检索相关信息。

  3. 答案生成:Llama 3.1 8B 处理该提示,并生成简洁的答案,利用复合链结合向量和图数据库的知识。


### Composite Vector + Graph Generationscypher_prompt = PromptTemplate(    template="""You are an expert at generating Cypher queries for Neo4j.    Use the following schema to generate a Cypher query that answers the given question.    Make the query flexible by using case-insensitive matching and partial string matching where appropriate.    Focus on searching paper titles as they contain the most relevant information.        Schema:    {schema}        Question: {question}        Cypher Query:""",    input_variables=["schema", "question"],)
# QA promptqa_prompt = PromptTemplate(    template="""You are an assistant for question-answering tasks.     Use the following Cypher query results to answer the question. If you don't know the answer, just say that you don't know.     Use three sentences maximum and keep the answer concise. If topic information is not available, focus on the paper titles.        Question: {question}     Cypher Query: {query}    Query Results: {context}         Answer:""",    input_variables=["question", "query", "context"],)
llm = ChatOpenAI(model="gpt-4o", temperature=0)
# Chaingraph_rag_chain = GraphCypherQAChain.from_llm(    cypher_llm=llm,    qa_llm=llm,    validate_cypher=True,    graph=graph,    verbose=True,    return_intermediate_steps=True,    return_direct=True,    cypher_prompt=cypher_prompt,    qa_prompt=qa_prompt,)


接下来,我们来看看我们搜索的结果,结合图数据库和向量数据库的优势来增强我们的论文发现过程。


我们首先使用 Neo4j 进行图搜索:

# Example input dataquestion = "What paper talks about Multi-Agent?"generation = graph_rag_chain.invoke({"query": question})print(generation)
> Entering new GraphCypherQAChain chain...Generated Cypher:cypherMATCH (p:Paper)WHERE toLower(p.title) CONTAINS toLower("Multi-Agent")RETURN p.title AS PaperTitle, p.summary AS Summary, p.url AS URL
> Finished chain.{'query': 'What paper talks about Multi-Agent?', 'result': [{'PaperTitle': 'Collaborative Multi-Agent, Multi-Reasoning-Path (CoMM) Prompting Framework', 'Summary': 'In this work, we aim to push the upper bound of the reasoning capability of LLMs by proposing a collaborative multi-agent, multi-reasoning-path (CoMM) prompting framework. Specifically, we prompt LLMs to play different roles in a problem-solving team, and encourage different role-play agents to collaboratively solve the target task. In particular, we discover that applying different reasoning paths for different roles is an effective strategy to implement few-shot prompting approaches in the multi-agent scenarios. Empirical results demonstrate the effectiveness of the proposed methods on two college-level science problems over competitive baselines. Our further analysis shows the necessity of prompting LLMs to play different roles or experts independently.', 'URL': 'https://github.com/amazon-science/comm-prompt'}]


图搜索在查找关系和元数据方面表现优异。它可以快速基于标题、作者或预定义的类别找到相关论文,并提供结构化的数据视图。


接下来,我们转向向量搜索,以获取不同的视角:

# Example input dataquestion = "What paper talks about Multi-Agent?"
# Get vector + graph answersdocs = retriever.invoke(question)vector_context = rag_chain.invoke({"context": docs, "question": question})
> The paper discusses "Adaptive In-conversation Team Building for Language Model Agents" and talks about Multi-Agent. It presents a new adaptive team-building paradigm that offers a flexible solution for building teams of LLM agents to solve complex tasks effectively. The approach, called Captain Agent, dynamically forms and manages teams for each step of the task-solving process, utilizing nested group conversations and reflection to ensure diverse expertise and prevent stereotypical outputs.

向量搜索在理解上下文和语义相似性方面非常出色。它能够发现与查询概念相关的论文,即使这些论文中没有明确包含搜索词。


最后,我们结合两种搜索方法:

这是我们 RAG Agent 中的关键部分,使得同时使用向量和图数据库成为可能。

composite_chain = prompt | llm | StrOutputParser()answer = composite_chain.invoke({"question": question, "context": vector_context, "graph_context": graph_context})
print(answer)
> The paper "Collaborative Multi-Agent, Multi-Reasoning-Path (CoMM) Prompting Framework" talks about Multi-Agent. It proposes a framework that prompts LLMs to play different roles in a problem-solving team and encourages different role-play agents to collaboratively solve the target task. The paper presents empirical results demonstrating the effectiveness of the proposed methods on two college-level science problems.


通过整合图搜索和向量搜索,我们发挥了两种方法的优势。图搜索提供了精确性,并能导航结构化的关系,而向量搜索通过语义理解提供了深度。

这种结合方法提供了几个优势:

  • 改进的召回:它能够找到可能被单一方法遗漏的相关论文。

  • 增强的上下文:它提供了论文间关系的更细致理解。

  • 灵活性:它能够适应不同类型的查询,从具体的关键词搜索到更广泛的概念探索。




总结  




在本文中,我们展示了如何使用 Neo4j 和 Milvus 构建一个 GraphRAG Agent。通过结合图数据库和向量搜索的优势,这个 Agent 能够为用户查询提供准确且相关的答案。


我们的 RAG Agent 架构,拥有专门的路由、回退机制和自我修正功能,使其更加稳健和可靠。图生成和复合 Agent 组件的示例展示了该 Agent 如何利用向量和图数据库来提供全面且细致的答案。



当前的代码可以在GitHub上找到:

https://github.com/milvus-io/bootcamp/blob/master/bootcamp/RAG/advanced_rag/langgraph-graphrag-agent-local.ipynb




PyTorch研习社
打破知识壁垒,做一名知识的传播者
 最新文章