Lưu trữ và truy vấn tài liệu

Retrieval Augmented Generation (RAG) với LangChain

Meri Nova

Machine Learning Engineer

Khởi tạo cơ sở dữ liệu 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/
Retrieval Augmented Generation (RAG) với LangChain

Lưu trữ tài liệu đồ thị

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)
Retrieval Augmented Generation (RAG) với LangChain

Lưu trữ tài liệu đồ thị

graph.add_graph_documents(
  graph_documents,

include_source=True,
baseEntityLabel=True
)
  • include_source=True: liên kết nút với tài liệu nguồn bằng cạnh MENTIONS
  • baseEntityLabel=True: thêm nhãn __Entity__ cho mỗi nút
Retrieval Augmented Generation (RAG) với LangChain

Các tài liệu đồ thị được biểu diễn bằng nút và cạnh.

Retrieval Augmented Generation (RAG) với LangChain

Phiên bản phóng to của hình trước, hiển thị các nút về mô hình OpenAI.

Retrieval Augmented Generation (RAG) với LangChain

Lược đồ cơ sở dữ liệu

print(graph.get_schema)
Thuộc tính nút:
Concept {id: STRING}
Architecture {id: STRING}
Organization {id: STRING}
Event {id: STRING}
Paper {id: STRING}

Các quan hệ:
(:Concept)-[:DEVELOPED_BY]->(:Person)
(:Architecture)-[:BASED_ON]->(:Concept)
(:Organization)-[:PROPOSED]->(:Concept)
(:Document)-[:MENTIONS]->(:Event)
(:Paper)-[:BASED_ON]->(:Concept)
Retrieval Augmented Generation (RAG) với LangChain

Truy vấn Neo4j - Ngôn ngữ truy vấn Cypher

Một nút tên James với quan hệ tên friends trỏ đến một nút người bí ẩn.

Retrieval Augmented Generation (RAG) với LangChain

Truy vấn Neo4j - Ngôn ngữ truy vấn Cypher

cypher4.jpg

Retrieval Augmented Generation (RAG) với LangChain

Truy vấn Neo4j - Ngôn ngữ truy vấn Cypher

cypher4.jpg

Retrieval Augmented Generation (RAG) với LangChain

Truy vấn Neo4j - Ngôn ngữ truy vấn Cypher

cypher4.jpg

Retrieval Augmented Generation (RAG) với LangChain

Truy vấn Neo4j - Ngôn ngữ truy vấn Cypher

cypher4.jpg

Retrieval Augmented Generation (RAG) với LangChain

Truy vấn đồ thị LLM

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

print(results)
[{'org': {'id': 'Openai'}}]
Retrieval Augmented Generation (RAG) với LangChain

Cùng luyện tập nào!

Retrieval Augmented Generation (RAG) với LangChain

Preparing Video For Download...