ConversationEntityMemory

대화 메모리

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

AI
RAG
LangChain
저자

Kwangmin Kim

공개

2024년 12월 31일

엔티티 메모리는 대화에서 특정 엔티티에 대한 주어진 사실을 기억합니다.

엔티티 메모리는 엔티티에 대한 정보를 추출하고(LLM 사용) 시간이 지남에 따라 해당 엔티티에 대한 지식을 축적합니다(역시 LLM 사용).

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

# API KEY 정보로드
load_dotenv()
from langchain_openai import ChatOpenAI
from langchain.chains import ConversationChain
from langchain.memory import ConversationEntityMemory
from langchain.memory.prompt import ENTITY_MEMORY_CONVERSATION_TEMPLATE

Entity 메모리를 효과적으로 사용하기 위하여, 제공되는 프롬프트를 사용합니다.

# Entity Memory를 사용하는 프롬프트 내용을 출력합니다.
print(ENTITY_MEMORY_CONVERSATION_TEMPLATE.template)
# LLM 을 생성합니다.
llm = ChatOpenAI(model_name="gpt-4.1-mini", temperature=0)

# ConversationChain 을 생성합니다.
conversation = ConversationChain(
    llm=llm,
    prompt=ENTITY_MEMORY_CONVERSATION_TEMPLATE,
    memory=ConversationEntityMemory(llm=llm),
)

대화를 시작합니다.

입력한 대화를 바탕으로 ConversationEntityMemory 는 주요 Entity 정보를 별도로 저장합니다.

conversation.predict(
    input="테디와 셜리는 한 회사에서 일하는 동료입니다."
    "테디는 개발자이고 셜리는 디자이너입니다. "
    "그들은 최근 회사에서 일하는 것을 그만두고 자신들의 회사를 차릴 계획을 세우고 있습니다."
)

Entity는 memory.entity_store.store 에서 확인할 수 있습니다.

# entity memory 를 출력합니다.
conversation.memory.entity_store.store

Subscribe

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