Graph RAG với LangChain và Neo4j
Adam Cowley
Manager, Developer Education at Neo4j










from langchain_neo4j import Neo4jChatMessageHistoryhistory = Neo4jChatMessageHistory(url=NEO4J_URI,username=NEO4J_USERNAME,password=NEO4J_PASSWORD,session_id="session_id_1",)# Thêm tin nhắn của người dùng history.add_user_message("hi!")# Thêm tin nhắn AI history.add_ai_message("what's up?")

from langchain_neo4j import Neo4jChatMessageHistory history = Neo4jChatMessageHistory( url=NEO4J_URI, username=NEO4J_USERNAME, password=NEO4J_PASSWORD, session_id="session_id_1",window=10 # mặc định 3 tin nhắn)# Lấy lịch sử print(history.messages)
[HumanMessage(content='hi!', ...), AIMessage(content='whats up?', ...)]
from pydantic import BaseModel, Field class ConversationFact(BaseModel): """ Lớp lưu trữ các sự kiện từ hội thoại theo định dạng object, subject, predicate. """object: str = Field(description="Đối tượng của sự kiện. Ví dụ: 'Adam' ")subject: str = Field(description="Chủ ngữ của sự kiện. Ví dụ: 'Ice cream'")relationship: str = Field(description="Quan hệ giữa object và subject. Ví dụ: 'LOVES'")class ConversationFacts(BaseModel): """ Lớp chứa danh sách các đối tượng ConversationFact. """ facts: list[ConversationFact] = Field(description="Danh sách các đối tượng ConversationFact.")
llm_with_output = (
init_chat_model("gpt-4o-mini", model_provider="openai", api_key="...")
.with_structured_output(ConversationFacts)
)
prompt = ChatPromptTemplate.from_messages(SystemMessagePromptTemplate.from_template("Trích xuất các sự kiện từ hội thoại."),MessagesPlaceholder(variable_name="history"),)chain = prompt | llm_with_outputchain.invoke({"history": history.messages,})
ConversationFacts(facts=[
ConversationFact(object='child', subject='Bluey', relationship='LOVES')
])
Graph RAG với LangChain và Neo4j