ConversationKGMemory

대화 메모리

대화 컨텍스트를 관리하는 다양한 메모리 시스템을 다룬다.

AI
RAG
LangChain
저자

Kwangmin Kim

공개

2024년 12월 31일

지식 그래프의 힘을 활용하여 정보를 저장하고 불러옵니다.

이를 통해 모델이 서로 다른 개체 간의 관계를 이해하는 데 도움을 주고, 복잡한 연결망과 역사적 맥락을 기반으로 대응하는 능력을 향상시킵니다.

# API KEY를 환경변수로 관리하기 위한 설정 파일
from dotenv import load_dotenv

# API KEY 정보로드
load_dotenv()
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationKGMemory
llm = ChatOpenAI(temperature=0)

memory = ConversationKGMemory(llm=llm, return_messages=True)
memory.save_context(
    {"input": "이쪽은 Pangyo 에 거주중인 김셜리씨 입니다."},
    {"output": "김셜리씨는 누구시죠?"},
)
memory.save_context(
    {"input": "김셜리씨는 우리 회사의 신입 디자이너입니다."},
    {"output": "만나서 반갑습니다."},
)
memory.load_memory_variables({"input": "김셜리씨는 누구입니까?"})

1 Chain 에 메모리 활용하기

ConversationChainConversationKGMemory 를 메모리로 지정하여 대화를 나눈 후 memory 를 확인해 보도록 하겠습니다.

from langchain.prompts.prompt import PromptTemplate
from langchain.chains import ConversationChain

llm = ChatOpenAI(temperature=0)

template = """The following is a friendly conversation between a human and an AI. 
The AI is talkative and provides lots of specific details from its context. 
If the AI does not know the answer to a question, it truthfully says it does not know. 
The AI ONLY uses information contained in the "Relevant Information" section and does not hallucinate.

Relevant Information:

{history}

Conversation:
Human: {input}
AI:"""
prompt = PromptTemplate(
    input_variables=["history", "input"], template=template)

conversation_with_kg = ConversationChain(
    llm=llm, prompt=prompt, memory=ConversationKGMemory(llm=llm)
)

첫 번째 대화를 시작합니다. 간단한 인물에 대한 정보를 제공해 보겠습니다.

conversation_with_kg.predict(
    input="My name is Teddy. Shirley is a coworker of mine, and she's a new designer at our company."
)

Shirley 라는 사람에 대한 질문을 진행합니다.

# Shirley 에 대한 질문
conversation_with_kg.memory.load_memory_variables({"input": "who is Shirley?"})

Subscribe

Enjoy this blog? Get notified of new posts by email: