Mem0MemoryWriter
Mem0MemoryWriter
ChatMessage 객체를 Mem0에 장기 기억으로 저장해주는 컴포넌트예요. 메모리 강화 파이프라인에서 Agent나 Chat Generator 뒤에 두면 돼요.
출처: Mem0MemoryWriter
본문
개요
Mem0MemoryWriter는 ChatMessage 객체 목록을 Mem0MemoryStore에 저장해요. 메모리 강화 파이프라인의 끝부분에 두어 대화 사실, 사용자 선호도, 지속적인 프로젝트 컨텍스트를 향후 실행을 위해 저장하면 돼요.
저장되는 기억의 범위는 Mem0 엔티티 ID 중 적어도 하나로 지정해요: user_id, run_id, agent_id, app_id. 이들은 런타임 입력이라, 파이프라인 인스턴스 하나로 여러 사용자·세션·에이전트·애플리케이션의 기억을 저장할 수 있어요.
infer 초기화 파라미터는 Mem0이 들어오는 메시지를 저장하는 방식을 제어해요.
infer=True이면 Mem0이 메시지에서 기억을 추출해요. 사용자 메시지, 도구 컨텍스트, 최종 어시스턴트 응답을 포함하는 전체 Agent 턴을 저장할 때 유용해요.infer=False이면 주어진 메시지 텍스트를 그대로 저장해요. 상류 컴포넌트가 정확한 기억 텍스트를 이미 선택했을 때 유용해요.
설치
Mem0 통합을 설치해요.
pip install mem0-haystack
Mem0 API 키를 설정해요.
export MEM0_API_KEY="your-mem0-api-key"
사용법
단독 사용:
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.writers.mem0 import Mem0MemoryWriter
from haystack_integrations.memory_stores.mem0 import Mem0MemoryStore
store = Mem0MemoryStore()
writer = Mem0MemoryWriter(memory_store=store, infer=False)
result = writer.run(
messages=[ChatMessage.from_user("Alice prefers concise Python examples.")],
user_id="alice",
)
print(result["memories_written"])
파이프라인 안에서:
이 예시는 Agent의 전체 messages 출력을 infer=True로 Mem0MemoryWriter에 연결해서, Mem0이 전체 턴 컨텍스트에서 기억을 추출하게 해요.
from haystack import Pipeline
from haystack.components.agents import Agent
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.components.generators.utils import print_streaming_chunk
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.writers.mem0 import Mem0MemoryWriter
from haystack_integrations.memory_stores.mem0 import Mem0MemoryStore
store = Mem0MemoryStore()
pipeline = Pipeline()
pipeline.add_component(
"agent",
Agent(
chat_generator=OpenAIChatGenerator(model="gpt-4o-mini"),
system_prompt=(
"Answer the user and preserve durable user facts or preferences for future conversations."
),
streaming_callback=print_streaming_chunk,
),
)
pipeline.add_component("writer", Mem0MemoryWriter(memory_store=store, infer=True))
pipeline.connect("agent.messages", "writer.messages")
result = pipeline.run(
{
"agent": {
"messages": [
ChatMessage.from_user(
"My name is Alice and I prefer concise Python examples.",
),
],
},
"writer": {
"user_id": "alice",
},
},
)
print(result["writer"]["memories_written"])