使用 LangChain 和 Neo4j 的 Graph RAG
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",)# Add a human message history.add_user_message("hi!")# Add an AI message 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 # defaults to 3 messages)# Get history print(history.messages)
[HumanMessage(content='hi!', ...), AIMessage(content='whats up?', ...)]
from pydantic import BaseModel, Field class ConversationFact(BaseModel): """ 以主语、宾语、谓词三元组形式保存对话事实的类。 """object: str = Field(description="事实的宾语。例如:'Adam'")subject: str = Field(description="事实的主语。例如:'Ice cream'")relationship: str = Field(description="主语与宾语的关系。如:'LOVES'")class ConversationFacts(BaseModel): """ 保存 ConversationFact 列表的类。 """ facts: list[ConversationFact] = Field(description="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("Extract the facts from the conversation."),MessagesPlaceholder(variable_name="history"),)chain = prompt | llm_with_outputchain.invoke({"history": history.messages,})
ConversationFacts(facts=[
ConversationFact(object='child', subject='Bluey', relationship='LOVES')
])
使用 LangChain 和 Neo4j 的 Graph RAG