메모리 그래프

LangChain과 Neo4j로 배우는 Graph RAG

Adam Cowley

Manager, Developer Education at Neo4j

RAG 애플리케이션의 메모리

단기 기억

  • 수명 짧고, 범위 제한
  • 대화 이력

 

goldfish.png

장기 기억

  • 의미 기억: 세계에 대한 사실
  • 초개인화에 유용

elephant.png

LangChain과 Neo4j로 배우는 Graph RAG

단기 기억

LangChain과 Neo4j로 배우는 Graph RAG

단기 기억

LangChain과 Neo4j로 배우는 Graph RAG

단기 기억

LangChain과 Neo4j로 배우는 Graph RAG

단기 기억에서 장기 기억으로

LangChain과 Neo4j로 배우는 Graph RAG

단기 기억에서 장기 기억으로

LangChain과 Neo4j로 배우는 Graph RAG

단기 기억에서 장기 기억으로

LangChain과 Neo4j로 배우는 Graph RAG

단기 기억에서 장기 기억으로

LangChain과 Neo4j로 배우는 Graph RAG

단기 기억에서 장기 기억으로

LangChain과 Neo4j로 배우는 Graph RAG

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?")
LangChain과 Neo4j로 배우는 Graph RAG

모두 저장할 때의 문제점

memory_methods.jpg

LangChain과 Neo4j로 배우는 Graph RAG

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?', ...)]
LangChain과 Neo4j로 배우는 Graph RAG

대화 요약하기

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.")
LangChain과 Neo4j로 배우는 Graph RAG

대화 요약하기

llm_with_output = (
    init_chat_model("gpt-4o-mini", model_provider="openai", api_key="...")
        .with_structured_output(ConversationFacts)
)
LangChain과 Neo4j로 배우는 Graph RAG

대화 요약하기

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')
])
LangChain과 Neo4j로 배우는 Graph RAG

연습해 봅시다!

LangChain과 Neo4j로 배우는 Graph RAG

Preparing Video For Download...