AI知识库

53AI知识库

学习大模型的前沿技术与行业应用场景


图谱驱动的智能:如何用Django实现GraphRAG的高效检索
发布日期:2024-08-08 06:26:29 浏览次数: 1676


前言

前面一章讲述了构建知识图谱来提高基于 RAG 的应用程序的准确性,并且使用 Neo4j 和 LangChain 在 RAG 应用程序中构建和检索知识图谱信息。

图形检索增强生成 (Graph RAG) 这种方法利用图形数据库的结构化特性,将数据组织为节点和关系,以增强检索信息的深度和上下文性。

由于篇幅可能会比较长,这一篇知识点较多,我单独分成了两个小节

一、给定 Cypher 查询结果图表

Cypher 是什么?可能很多小伙伴不太懂这个,一来就产生一个疑问,我这里简单描述一下。

Cypher 其实是 Neo4j的图形查询语言,可让您从图形中检索数据。

它就像是 SQL 语句,不过它是图形的 SQL,但它受到 SQL 的启发,因此我们可以专注于怎么从图形中获取什么数据(而不是如何获取数据)。

后面几章节我会详细对 Cypher 的 语句 进行详细说明。

打开我们 Jupyter(https://jupyter.org/try-jupyter/lab/index.html)或者 Colab(https://colab.research.google.com/drive/),因为下面使用到了 yfiles_jupyter_graphs 它支持的环境就是 Jupyter 环境,VS Code 或 Google Colab 环境:

%pip install --upgrade --quiet  langchain langchain-community langchain-openai langchain-experimental neo4j wikipedia tiktoken yfiles_jupyter_graphs
from neo4j importGraphDatabase
from yfiles_jupyter_graphs importGraphWidget

os.environ["NEO4J_URI"]="bolt://*********"
os.environ["NEO4J_USERNAME"]="ne*******"
os.environ["NEO4J_PASSWORD"]="de**********"
os.environ["OPENAI_API_KEY"]="sk-*********"

graph =Neo4jGraph()
# dire
ctly show the graph resulting from the given Cypher query
default_cypher ="MATCH (s)-[r:!MENTIONS]->(t) RETURN s,r,t LIMIT 50"

defshowGraphDetail(cypher: str = default_cypher):
# create a neo4j session to run queries
    driver =GraphDatabase.driver(
        uri = os.environ["NEO4J_URI"],
        auth =(os.environ["NEO4J_USERNAME"],
                os.environ["NEO4J_PASSWORD"]))
    session = driver.session()
    widget =GraphWidget(graph = session.run(cypher).graph())
    widget.node_label_mapping ='id'

return widget
showGraphDetail(default_cypher)

"MATCH (s)-[r:!MENTIONS]->(t) RETURN s,r,t LIMIT 50"  这就是一句我们的 Cypher 查询语句,它表示的意思是 "找出图数据库中所有通过非'MENTIONS'关系相连的节点对,返回这些节点和它们之间的关系,但最多只返回50组这样的结果。"

这个查询可以用来探索图中的各种关系,同时排除了 "MENTIONS" 这种特定的关系类型。

它对于了解图的结构和不同实体之间的连接方式很有用,尤其是当你想排除某种特定类型的关系时。 点击运行,出现下面界面:

我们在这里可以看到之前保存到 Neo4j 的图数据。

二、混合检索

图生成后,我们将使用混合检索方法,将向量和关键字索引与 RAG 应用程序的图检索相结合。

在检索过程中,从用户提出问题开始,然后将问题定向到 RAG 检索器。

该检索器采用关键字和向量搜索来搜索非结构化文本数据,并将其与从知识图谱中收集的信息相结合。

由于 Neo4j 同时具有关键字索引和向量索引,因此我们可以使用单个数据库系统实现所有三个检索选项。

从这些来源收集的数据将输入 llm 大模型以生成并提供最终答案。

在我们做图混合检索所之前,我们先看一下图形检索器咋么识别输入中的相关实体,打开我们的视图文件 testite/members/views.py ,新建视图:

# 实体类
from langchain_core.prompts importChatPromptTemplate
from langchain_core.pydantic_v1 importBaseModel,Field
from typing importTuple,List,Optional
from langchain_community.graphs importNeo4jGraph
from langchain_openai importChatOpenAI
from langchain_experimental.graph_transformers importLLMGraphTransformer
classEntities(BaseModel):
"""Identifying information about entities."""

    names:List[str]=Field(
...,
        description="All the person, organization, or business entities that "
"appear in the text",
)

deftestEntity(request):
    llm =ChatOpenAI(temperature=0, model_name="gpt-4o-mini")
# 构建提示角色
    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)

    res = entity_chain.invoke({"question":"Where was jack born?"}).names
returnJsonResponse({'response': res})

然后天机路由:

  path('test_entity/', views.testEntity, name='graphrag'),

浏览器访问 http://127.0.0.1:8000/polls/test_entity/ 可以得到如下输出:

三、Django知识图谱检索方法构建

现在我们可以检测问题中的实体,让我们使用全文索引将它们映射到知识图谱。

首先,我们需要定义一个全文索引和一个函数,该函数将生成允许一些拼写错误的全文查询。

该函数依旧加到视图文件中:

def generate_full_text_query(inputstr)->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
defstructured_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 {
              WITH node
              MATCH (node)-[r:!MENTIONS]->(neighbor)
              RETURN node.id + ' - ' + type(r) + ' -> ' + neighbor.id AS output
              UNION ALL
              WITH node
              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

structural_retriever 函数首先检测用户问题中的实体。接下来,它迭代检测到的实体并使用 Cypher 模板来检索相关节点的邻域。我们可以来测试一下:

print(structured_retriever("Who is Dursley I?"))

得到下列答案:

我们在开始时提到的,我们将结合非结构化和图形检索器来创建将传递给 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

定义 RAG Chain,前面我们基本实现了 RAG 的检索组件。接下来,我将介绍以对话的方式跟进问题的查询:

_template = """Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question,
in its original language.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:"""
# noqa: E501
CONDENSE_QUESTION_PROMPT =PromptTemplate.from_template(_template)

def_format_chat_history(chat_history: List[Tuple[strstr]])->List:
    buffer =[]
for human, ai in chat_history:
        buffer.append(HumanMessage(content=human))
        buffer.append(AIMessage(content=ai))
return buffer

_search_query =RunnableBranch(
# If input includes chat_history, we condense it with the follow-up question
(
RunnableLambda(lambda x:bool(x.get("chat_history"))).with_config(
            run_name="HasChatHistoryCheck"
),# Condense follow-up question and chat into a standalone_question
RunnablePassthrough.assign(
            chat_history=lambda x: _format_chat_history(x["chat_history"])
)
| CONDENSE_QUESTION_PROMPT
|ChatOpenAI(temperature=0)
|StrOutputParser(),
),
# Else, we have no chat history, so just pass through the question
RunnableLambda(lambda x : x["question"]),
)

接下来,我们引入一个提示,利用集成混合检索器提供的上下文来生成响应,从而完成 RAG  链的实现。

提示模板如下:

template = """Answer the question based only on the following context:
{context}

Question: {question}
Use natural language and be concise.
Answer:"""

prompt =ChatPromptTemplate.from_template(template)

chain =(
RunnableParallel(
{
"context": _search_query | retriever,
"question":RunnablePassthrough(),
}
)
| prompt
| llm
|StrOutputParser()
)

最后,我们通过下面两种方式测试图形混合检索,第二种我带入了第一种的会话历史,定义一个视图方法:

def hybridRetrievalRag(request):
    res = chain.invoke({"question":"Which house did Dursley I belong to?"})
# 或者
    res = chain.invoke(
{
"question":"他出身在哪里?",
"chat_history":[
("Which house did Dursley I belong to?","Mr. Dursley belonged to number four, Privet Drive")],
}
)
returnJsonResponse({'response': res})

然后老样子,添加我们的路由:

path('hybrid_retrieval/', views.hybridRetrievalRag, name='graphrag'),

浏览器访问 http://127.0.0.1:8000/polls/hybrid_retrieval/ 可以得到如下输出:

成功得到自己的答案,第二个为啥没有检索到,由于我们在上一篇的段落并没有讲述Mr. Dursley出身在哪里,在图谱中也没检索得到这个问题的关系。

四、总结

这一章我们讲述可怎么结合 Django + langchian + Neo4j 构建 GraphRag ,并完成检索,测试了它的准确性,也看的到它们结合使用的效率以及性能,这种通过知识图谱的检索形式必将成为未来 RAG 不可缺少的一部分。

整个篇章下来从微软的 GraphRag 到 Neo4j 图库存储,最后做混合检索,小伙伴是不是会疑惑,好像并没有完全的联系起来,因为neo4j的图谱是自己储存的,并没有储存 GraphRag 生成的数据。

对的,还缺少一步怎么把存 GraphRag 生成的数据导入到 Neo4j ,下一节我们将讲述, Neo4j 存储 GraphRag 图谱文件,中间涉及到转化。


53AI,企业落地应用大模型首选服务商

产品:大模型应用平台+智能体定制开发+落地咨询服务

承诺:先做场景POC验证,看到效果再签署服务协议。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

与创始人交个朋友

回到顶部

 
扫码咨询