DSPy ReAct와 Mem0로 메모리 지원 에이전트 구축하기
DSPy ReAct와 Mem0로 메모리 지원 에이전트 구축하기 (Building Memory-Enabled Agents with DSPy ReAct and Mem0)
이 튜토리얼에서는 DSPy의 ReAct 프레임워크와 Mem0의 메모리 기능을 결합해, 상호작용 간 정보를 기억할 수 있는 지능형 대화 에이전트를 구축하는 방법을 알아볼게요. 컨텍스트 정보를 저장·검색·사용해 개인화되고 일관된 응답을 제공하는 에이전트를 만드는 법을 배웁니다.
출처: 문서
본문
무엇을 만들게 될까 (What You'll Build)
이 튜토리얼이 끝나면 다음을 할 수 있는 메모리 지원 에이전트를 갖게 돼요:
- 사용자 선호도와 과거 대화를 기억하기
- 사용자와 주제에 대한 사실 정보를 저장하고 검색하기
- 결정을 알리기 위해 메모리를 사용하고 개인화된 응답 제공하기
- 컨텍스트 인식을 갖춘 복잡한 다중 턴 대화 처리하기
- 다양한 유형의 메모리(사실, 선호도, 경험) 관리하기
사전 요구 사항 (Prerequisites)
- DSPy와 ReAct 에이전트에 대한 기본 이해
- Python 3.9+ 설치
- 선호하는 LLM 제공자의 API 키
설치 및 설정 (Installation and Setup)
pip install dspy mem0ai
1단계: Mem0 통합 이해 (Understanding Mem0 Integration)
Mem0은 AI 에이전트를 위한 메모리를 저장, 검색, 조회할 수 있는 메모리 계층을 제공해요. 이를 DSPy와 통합하는 방법을 이해하는 것부터 시작해 볼게요:
import dspy
from mem0 import Memory
import os
from typing import List, Dict, Any, Optional
from datetime import datetime
# Configure environment
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
# Initialize Mem0 memory system
config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini",
"temperature": 0.1
}
},
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-small"
}
}
}
2단계: 메모리 인식 도구 만들기 (Create Memory-Aware Tools)
메모리 시스템과 상호작용할 수 있는 도구를 만들어볼게요:
import datetime
class MemoryTools:
"""Tools for interacting with the Mem0 memory system."""
def __init__(self, memory: Memory):
self.memory = memory
def store_memory(self, content: str, user_id: str = "default_user") -> str:
"""Store information in memory."""
try:
self.memory.add(content, user_id=user_id)
return f"Stored memory: {content}"
except Exception as e:
return f"Error storing memory: {str(e)}"
def search_memories(self, query: str, user_id: str = "default_user", limit: int = 5) -> str:
"""Search for relevant memories."""
try:
results = self.memory.search(query, user_id=user_id, limit=limit)
if not results:
return "No relevant memories found."
memory_text = "Relevant memories found:\n"
for i, result in enumerate(results["results"]):
memory_text += f"{i}. {result['memory']}\n"
return memory_text
except Exception as e:
return f"Error searching memories: {str(e)}"
def get_all_memories(self, user_id: str = "default_user") -> str:
"""Get all memories for a user."""
try:
results = self.memory.get_all(user_id=user_id)
if not results:
return "No memories found for this user."
memory_text = "All memories for user:\n"
for i, result in enumerate(results["results"]):
memory_text += f"{i}. {result['memory']}\n"
return memory_text
except Exception as e:
return f"Error retrieving memories: {str(e)}"
def update_memory(self, memory_id: str, new_content: str) -> str:
"""Update an existing memory."""
try:
self.memory.update(memory_id, new_content)
return f"Updated memory with new content: {new_content}"
except Exception as e:
return f"Error updating memory: {str(e)}"
def delete_memory(self, memory_id: str) -> str:
"""Delete a specific memory."""
try:
self.memory.delete(memory_id)
return "Memory deleted successfully."
except Exception as e:
return f"Error deleting memory: {str(e)}"
def get_current_time() -> str:
"""Get the current date and time."""
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
3단계: 메모리 강화 ReAct 에이전트 구축 (Build the Memory-Enhanced ReAct Agent)
이제 메모리를 사용할 수 있는 메인 ReAct 에이전트를 만들어볼게요:
class MemoryQA(dspy.Signature):
"""
You're a helpful assistant and have access to memory method.
Whenever you answer a user's input, remember to store the information in memory
so that you can use it later.
"""
user_input: str = dspy.InputField()
response: str = dspy.OutputField()
class MemoryReActAgent(dspy.Module):
"""A ReAct agent enhanced with Mem0 memory capabilities."""
def __init__(self, memory: Memory):
super().__init__()
self.memory_tools = MemoryTools(memory)
# Create tools list for ReAct
self.tools = [
self.memory_tools.store_memory,
self.memory_tools.search_memories,
self.memory_tools.get_all_memories,
get_current_time,
self.set_reminder,
self.get_preferences,
self.update_preferences,
]
# Initialize ReAct with our tools
self.react = dspy.ReAct(
signature=MemoryQA,
tools=self.tools,
max_iters=6
)
def forward(self, user_input: str):
"""Process user input with memory-aware reasoning."""
return self.react(user_input=user_input)
def set_reminder(self, reminder_text: str, date_time: str = None, user_id: str = "default_user") -> str:
"""Set a reminder for the user."""
reminder = f"Reminder set for {date_time}: {reminder_text}"
return self.memory_tools.store_memory(
f"REMINDER: {reminder}",
user_id=user_id
)
def get_preferences(self, category: str = "general", user_id: str = "default_user") -> str:
"""Get user preferences for a specific category."""
query = f"user preferences {category}"
return self.memory_tools.search_memories(
query=query,
user_id=user_id
)
def update_preferences(self, category: str, preference: str, user_id: str = "default_user") -> str:
"""Update user preferences."""
preference_text = f"User preference for {category}: {preference}"
return self.memory_tools.store_memory(
preference_text,
user_id=user_id
)
4단계: 메모리 강화 에이전트 실행 (Running the Memory-Enhanced Agent)
메모리 지원 에이전트와 상호작용하는 간단한 인터페이스를 만들어볼게요:
import time
def run_memory_agent_demo():
"""Demonstration of memory-enhanced ReAct agent."""
# Configure DSPy
lm = dspy.LM(model='openai/gpt-4o-mini')
dspy.configure(lm=lm)
# Initialize memory system
memory = Memory.from_config(config)
# Create our agent
agent = MemoryReActAgent(memory)
# Sample conversation demonstrating memory capabilities
print("🧠 Memory-Enhanced ReAct Agent Demo")
print("=" * 50)
conversations = [
"Hi, I'm Alice and I love Italian food, especially pasta carbonara.",
"I'm Alice. I prefer to exercise in the morning around 7 AM.",
"I'm Alice. What do you remember about my food preferences?",
"I'm Alice. Set a reminder for me to go grocery shopping tomorrow.",
"I'm Alice. What are my exercise preferences?",
"I'm Alice. I also enjoy hiking on weekends.",
"I'm Alice. What do you know about me so far?"
]
for i, user_input in enumerate(conversations, 1):
print(f"\n📝 User: {user_input}")
try:
response = agent(user_input=user_input)
print(f"🤖 Agent: {response.response}")
time.sleep(1)
except Exception as e:
print(f"❌ Error: {e}")
# Run the demonstration
if __name__ == "__main__":
run_memory_agent_demo()
예상 출력 (Expected Output)
🧠 Memory-Enhanced ReAct Agent Demo
==================================================
📝 User: Hi, I'm Alice and I love Italian food, especially pasta carbonara.
🤖 Agent: Hi Alice! It's great to meet you! Pasta carbonara is a delicious choice. Do you have a favorite place to get it, or do you enjoy making it at home?
📝 User: I'm Alice. I prefer to exercise in the morning around 7 AM.
🤖 Agent: Nice to meet you, Alice! I've noted that you prefer to exercise in the morning around 7 AM. If you have any questions or need tips related to your morning workouts, feel free to ask!
📝 User: I'm Alice. What do you remember about my food preferences?
🤖 Agent: I remember that you love Italian food, and your favorite dish is pasta carbonara!
📝 User: I'm Alice. Set a reminder for me to go grocery shopping tomorrow.
🤖 Agent: I have set a reminder for you, Alice, to go grocery shopping tomorrow.
📝 User: I'm Alice. What are my exercise preferences?
🤖 Agent: Your exercise preference is to work out in the morning around 7 AM.
📝 User: I'm Alice. I also enjoy hiking on weekends.
🤖 Agent: Nice to meet you, Alice! It's great to hear that you enjoy hiking on weekends. If you need any recommendations for trails or tips for your hikes, feel free to ask!
📝 User: I'm Alice. What do you know about me so far?
🤖 Agent: So far, I know that you enjoy hiking on weekends, prefer to exercise in the morning around 7 AM, and love Italian food, especially pasta carbonara. Additionally, you have a reminder set for grocery shopping on October 7, 2023.
다음 단계 (Next Steps)
- 데이터베이스(PostgreSQL, MongoDB)로 메모리 영속성 구현하기
- 더 나은 구성을 위한 메모리 분류 및 태깅 추가하기
- 데이터 관리를 위한 메모리 만료 정책 만들기
- 프로덕션 애플리케이션을 위한 다중 사용자 메모리 격리 구축하기
- 메모리 분석 및 인사이트 추가하기
- 향상된 의미 검색을 위해 벡터 데이터베이스와 통합하기
- 장기 저장 효율을 위한 메모리 압축 구현하기
이 튜토리얼은 DSPy의 ReAct 프레임워크를 Mem0의 메모리 기능으로 강화해, 상호작용 간 정보를 학습하고 기억하며 실제 애플리케이션에서 더 유용한 지능형 컨텍스트 인식 에이전트를 만드는 방법을 보여줘요.