Graph RAG mit LangChain und 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",)# Nutzer-Nachricht hinzufügen history.add_user_message("hi!")# KI-Nachricht hinzufügen 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 # Standard: 3 Nachrichten)# Verlauf abrufen print(history.messages)
[HumanMessage(content='hi!', ...), AIMessage(content='whats up?', ...)]
from pydantic import BaseModel, Field class ConversationFact(BaseModel): """ Eine Klasse, die Fakten aus einem Gespräch im Format Objekt, Subjekt, Prädikat hält. """object: str = Field(description="Das Objekt des Fakts. Z. B. 'Adam' ")subject: str = Field(description="Das Subjekt des Fakts. Z. B. 'Ice cream'")relationship: str = Field(description="Die Beziehung zwischen Objekt und Subjekt. Z. B.: 'LOVES'")class ConversationFacts(BaseModel): """ Eine Klasse, die eine Liste von ConversationFact-Objekten hält. """ facts: list[ConversationFact] = Field(description="Eine Liste von ConversationFact-Objekten.")
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')
])
Graph RAG mit LangChain und Neo4j