创建 Graph RAG 链

使用 LangChain 的 Retrieval Augmented Generation (RAG)

Meri Nova

Machine Learning Engineer

构建 Graph RAG 架构

一个图数据库。

使用 LangChain 的 Retrieval Augmented Generation (RAG)

构建 Graph RAG 架构

文档被转换为图文档并存入图数据库。

使用 LangChain 的 Retrieval Augmented Generation (RAG)

构建 Graph RAG 架构

使用 Cypher 查询从数据库检索图文档。还显示用户输入与返回给用户的自然语言回复。

使用 LangChain 的 Retrieval Augmented Generation (RAG)

构建 Graph RAG 架构

"自然语言到 Cypher"转换器将自然语言输入转为 Cypher 查询,并将检索到的图文档转回自然语言。

使用 LangChain 的 Retrieval Augmented Generation (RAG)

从用户输入到 Cypher 查询

一个包含三个节点和三条关系的简单图。两个节点代表人物,另一个代表 James 去过的地点。

使用 LangChain 的 Retrieval Augmented Generation (RAG)

从用户输入到 Cypher 查询

用户输入"James 去过哪些地方?"。

使用 LangChain 的 Retrieval Augmented Generation (RAG)

从用户输入到 Cypher 查询

使用图模式与用户输入生成 Cypher 查询。

使用 LangChain 的 Retrieval Augmented Generation (RAG)

GraphCypherQAChain

Graph RAG 架构:将用户输入转为 Cypher 查询并返回自然语言回复。

使用 LangChain 的 Retrieval Augmented Generation (RAG)

GraphCypherQAChain

Graph RAG 架构,突出显示"生成 Cypher 链"和"汇总结果链"。

使用 LangChain 的 Retrieval Augmented Generation (RAG)

刷新模式

graph.refresh_schema()
print(graph.get_schema)
Node properties:
Document {title: STRING, id: STRING, text: STRING, summary: STRING, source: STRING}
Concept {id: STRING}
Organization {id: STRING}
Relationship properties:

The relationships:
(:Document)-[:MENTIONS]->(:Organization)
(:Concept)-[:DEVELOPED_BY]->(:Person)
使用 LangChain 的 Retrieval Augmented Generation (RAG)

查询图谱

from langchain_community.chains.graph_qa.cypher import GraphCypherQAChain

chain = GraphCypherQAChain.from_llm( llm=ChatOpenAI(api_key="...", temperature=0), graph=graph, verbose=True )
result = chain.invoke({"query": "What is the most accurate model?"})
1 https://api.python.langchain.com/en/latest/chains/langchain_community.chains.graph_qa.cypher. GraphCypherQAChain.html
使用 LangChain 的 Retrieval Augmented Generation (RAG)

查询图谱

print(f"Final answer: {result['result']}")
> Entering new GraphCypherQAChain chain...
Generated Cypher:
MATCH (m:Model)
RETURN m
ORDER BY m.accuracy DESC
LIMIT 1;
Full Context:
[{'m': {'id': 'Artificial Neural Networks'}}]

> Finished chain.


Final answer: Artificial Neural Networks
使用 LangChain 的 Retrieval Augmented Generation (RAG)

自定义

chain = GraphCypherQAChain.from_llm(
    llm=ChatOpenAI(api_key="...", temperature=0), graph=graph, verbose=True
)
  • qa_prompt:生成结果的提示模板
  • cypher_prompt:生成 Cypher 的提示模板
  • cypher_llm:用于生成 Cypher 的 LLM
  • qa_llm:用于生成结果的 LLM
使用 LangChain 的 Retrieval Augmented Generation (RAG)

Passons à la pratique !

使用 LangChain 的 Retrieval Augmented Generation (RAG)

Preparing Video For Download...