存储与查询文档

使用 LangChain 的 Retrieval Augmented Generation (RAG)

Meri Nova

Machine Learning Engineer

实例化 Neo4j 数据库

from langchain_community.graphs import Neo4jGraph

graph = Neo4jGraph(url="bolt://localhost:7687", username="neo4j", password="...")
import os

url = os.environ["NEO4J_URI"]
user = os.environ["NEO4J_USERNAME"]
password = os.environ["NEO4J_PASSWORD"]

graph = Neo4jGraph(url=url, username=user, password=password)
1 https://neo4j.com/download/
使用 LangChain 的 Retrieval Augmented Generation (RAG)

存储图文档

from langchain_experimental.graph_transformers import LLMGraphTransformer

llm = ChatOpenAI(api_key="...", temperature=0, model="gpt-4o-mini")
llm_transformer = LLMGraphTransformer(llm=llm)

graph_documents = llm_transformer.convert_to_graph_documents(documents)
使用 LangChain 的 Retrieval Augmented Generation (RAG)

存储图文档

graph.add_graph_documents(
  graph_documents,

include_source=True,
baseEntityLabel=True
)
  • include_source=True:用 MENTIONS 边将节点关联到源文档
  • baseEntityLabel=True:为每个节点添加 __Entity__ 标签
使用 LangChain 的 Retrieval Augmented Generation (RAG)

以节点和边形式展示的图文档。

使用 LangChain 的 Retrieval Augmented Generation (RAG)

上一张图的放大版,展示与 OpenAI 模型相关的节点。

使用 LangChain 的 Retrieval Augmented Generation (RAG)

数据库模式

print(graph.get_schema)
Node properties:
Concept {id: STRING}
Architecture {id: STRING}
Organization {id: STRING}
Event {id: STRING}
Paper {id: STRING}

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

查询 Neo4j——Cypher 查询语言

一个名为 James 的节点,有一条名为 friends 的关系指向一个未知的人节点。

使用 LangChain 的 Retrieval Augmented Generation (RAG)

查询 Neo4j——Cypher 查询语言

cypher4.jpg

使用 LangChain 的 Retrieval Augmented Generation (RAG)

查询 Neo4j——Cypher 查询语言

cypher4.jpg

使用 LangChain 的 Retrieval Augmented Generation (RAG)

查询 Neo4j——Cypher 查询语言

cypher4.jpg

使用 LangChain 的 Retrieval Augmented Generation (RAG)

查询 Neo4j——Cypher 查询语言

cypher4.jpg

使用 LangChain 的 Retrieval Augmented Generation (RAG)

查询 LLM 图

results = graph.query("""
MATCH (gpt4:Model {id: "Gpt-4"})-[:DEVELOPED_BY]->(org:Organization)
RETURN org
""")

print(results)
[{'org': {'id': 'Openai'}}]
使用 LangChain 的 Retrieval Augmented Generation (RAG)

Passons à la pratique !

使用 LangChain 的 Retrieval Augmented Generation (RAG)

Preparing Video For Download...