[AI] Langchain 메모리 기능 이해하기

도톨이·2024년 6월 11일

AI

목록 보기
9/14
post-thumbnail

🧠 LangChain Memory 사용 가이드

LangChain에서 메모리는 언어 모델과의 상호작용에서 상태를 유지할 수 있게 합니다. 기본적으로 체인(Chains)과 에이전트(Agents)는 무상태(stateless)이며 각 쿼리를 독립적으로 처리합니다. 그러나 일부 애플리케이션, 특히 챗봇에서는 이전 상호작용을 기억하는 것이 매우 중요합니다.

LangChain은 두 가지 형태의 메모리 컴포넌트를 제공합니다:
1. 이전 채팅 메시지를 관리하고 조작하는 헬퍼 유틸리티
2. 이러한 유틸리티를 체인에 쉽게 통합하는 방법

🛠️ ChatMessageHistory

ChatMessageHistory 클래스는 대부분의 메모리 모듈을 뒷받침하는 핵심 유틸리티 클래스입니다. 이 클래스는 인간 메시지와 AI 메시지를 저장하고 편리하게 가져올 수 있는 메서드를 제공합니다.

final history = ChatMessageHistory();

history.addHumanChatMessage('hi!');
history.addAIChatMessage('whats up?');

print(await history.getChatMessages());
// [HumanChatMessage(content='hi!', example=false),
//  AIMessage(content='whats up?', example=false)]

🗂️ ConversationBufferMemory

ConversationBufferMemoryChatMessageHistory를 래핑한 클래스로, 메시지를 변수로 추출하는 기능을 제공합니다.

문자열로 추출하기

final memory = ConversationBufferMemory();

memory.chatHistory.addHumanChatMessage('hi!');
memory.chatHistory.addAIChatMessage('whats up?');

print(await memory.loadMemoryVariables());
// {'history': 'Human: hi!\nAI: whats up?'}

메시지 목록으로 추출하기

final memory = ConversationBufferMemory(returnMessages: true);

memory.chatHistory.addHumanChatMessage('hi!');
memory.chatHistory.addAIChatMessage('whats up?');

print(await memory.loadMemoryVariables());
// {'history': [HumanMessage(content='hi!', example=false),
//   AIMessage(content='whats up?', example=false)]}

🔗 체인에서 메모리 사용하기

체인에 메모리를 통합하여 상태를 유지하는 대화형 체인을 만들 수 있습니다.

final llm = OpenAI(
  apiKey: openaiApiKey,
  defaultOptions: const OpenAIOptions(temperature: 0),
);

final conversation = ConversationChain(
  llm: llm,
  memory: ConversationBufferMemory(),
);

final output1 = await conversation.run('Hi there!');
print(output1);
// -> 'Hi there! It's nice to meet you. How can I help you today?'

🧩 내부 동작

첫 번째 메시지 전송 시, 현재 대화가 비어있습니다.

> Entering new ConversationChain chain...
Prompt after formatting:
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.

Current conversation:

Human: Hi there!
AI:

> Finished chain.

두 번째 메시지 전송

이제 체인은 이전 메시지를 기억하고 이를 컨텍스트에 추가합니다.

final output2 = await conversation.run("I'm doing well! Just having a conversation with an AI.");
print(output2);
// -> 'That's great! It's always nice to have a conversation with someone new. What would you like to talk about?'
> Entering new ConversationChain chain...
Prompt after formatting:
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.

Current conversation:
Human: Hi there!
AI:  Hi there! It's nice to meet you. How can I help you today?
Human: I'm doing well! Just having a conversation with an AI.
AI:

> Finished chain.

세 번째 메시지 전송

체인이 이제 두 개의 메시지를 기억하고 있습니다.

final output3 = await conversation.run('Tell me about yourself');
print(output3);
// -> 'Sure! I am an AI language model created by OpenAI. I was trained on a large dataset of text from the internet, which allows me to understand and generate human-like language. I can answer questions, provide information, and even have conversations like this one. Is there anything else you'd like to know about me?'
> Entering new ConversationChain chain...
Prompt after formatting:
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.

Current conversation:
Human: Hi there!
AI:  Hi there! It's nice to meet you. How can I help you today?
Human: I'm doing well! Just having a conversation with an AI.
AI:  That's great! It's always nice to have a conversation with someone new. What would you 
like to talk about?
Human: Tell me about yourself.
AI:

> Finished chain.

요약

  • ChatMessageHistory: 인간 및 AI 메시지를 저장하고 관리하는 간단한 유틸리티 클래스입니다.
  • ConversationBufferMemory: ChatMessageHistory를 래핑하여 체인에 메모리 기능을 추가하는 클래스입니다.
  • 체인에서 메모리 사용: 체인에 메모리를 통합하여 상태를 유지하고 이전 대화를 기억하도록 설정합니다.

이를 통해 LangChain을 사용하여 사용자와의 상호작용을 기억하고 지속적으로 관리할 수 있는 대화형 애플리케이션을 구축할 수 있습니다. 📝✨

profile
Kotlin, Flutter, AI | Computer Science

0개의 댓글