メモリのグラフ

Graph RAG with LangChain and Neo4j

Adam Cowley

Manager, Developer Education at Neo4j

RAGアプリのメモリ

短期記憶

  • 短命、スコープ限定の寿命
  • 会話の履歴

 

goldfish.png

長期記憶

  • セマンティック記憶:世界の事実
  • ハイパーパーソナライゼーションに有用

elephant.png

Graph RAG with LangChain and Neo4j

短期記憶

Graph RAG with LangChain and Neo4j

短期記憶

Graph RAG with LangChain and Neo4j

短期記憶

Graph RAG with LangChain and Neo4j

短期記憶から長期記憶へ

Graph RAG with LangChain and Neo4j

短期記憶から長期記憶へ

Graph RAG with LangChain and Neo4j

短期記憶から長期記憶へ

Graph RAG with LangChain and Neo4j

短期記憶から長期記憶へ

Graph RAG with LangChain and Neo4j

短期記憶から長期記憶へ

Graph RAG with LangChain and Neo4j

Neo4j のチャット履歴

from langchain_neo4j import Neo4jChatMessageHistory


history = 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?")
Graph RAG with LangChain and Neo4j

すべて保存する際の問題点

memory_methods.jpg

Graph RAG with LangChain and Neo4j

Neo4j のチャット履歴

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?', ...)]
Graph RAG with LangChain and Neo4j

会話の要約

from pydantic import BaseModel, Field

class ConversationFact(BaseModel):
    """
    A class that holds the facts from a conversation in a format of object, subject, predicate.
    """

object: str = Field(description="The object of the fact. For example, 'Adam' ")
subject: str = Field(description="The subject of the fact. For example, 'Ice cream'")
relationship: str = Field(description="The relationship between object and subject. Eg: 'LOVES'")
class ConversationFacts(BaseModel): """ A class that holds a list of ConversationFact objects. """ facts: list[ConversationFact] = Field(description="A list of ConversationFact objects.")
Graph RAG with LangChain and Neo4j

会話の要約

llm_with_output = (
    init_chat_model("gpt-4o-mini", model_provider="openai", api_key="...")
        .with_structured_output(ConversationFacts)
)
Graph RAG with LangChain and Neo4j

会話の要約

prompt = ChatPromptTemplate.from_messages(

SystemMessagePromptTemplate.from_template("Extract the facts from the conversation."),
MessagesPlaceholder(variable_name="history"),
)
chain = prompt | llm_with_output
chain.invoke({
"history": history.messages,
})
ConversationFacts(facts=[
    ConversationFact(object='child', subject='Bluey', relationship='LOVES')
])
Graph RAG with LangChain and Neo4j

Let's practice!

Graph RAG with LangChain and Neo4j

Preparing Video For Download...