儲存與查詢文件

使用 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)

資料庫綱要(Schema)

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)

一起來練習吧!

使用 LangChain 的 Retrieval Augmented Generation(RAG)

Preparing Video For Download...