MongoDB를 Mem0와 연동하여 대화 전체에 걸쳐 유지되는 AI 에이전트의 장기 메모리를 구성할 수 있습니다. 이 튜토리얼에서는 Mem0을 구성하여 MongoDB를 벡터 저장소로 사용하고 난 후 메모리 증강 도우미를 빌드합니다. 이 튜토리얼에서는 다음 작업을 수행합니다.
환경을 설정합니다.
MongoDB를 Mem0 벡터 저장소로 사용합니다.
메모리 문서 저장 및 조회.
조회하는 기억을 기반으로 응답을 개인화하는 도우미를 빌드합니다.
배경
Mem0은 AI 에이전트 및 어시스턴트를 위한 오픈 소스 메모리 계층입니다. 요청 있을 때마다 전체 대화 기록을 LLM에 전달하는 대신, Mem0은 대화에서 불연속적인 사실을 추출하고 각 사실을 문서 로 저장하며 쿼리 시점에 가장 관련성이 높은 사실만 검색합니다.
Mem0을(를) MongoDB를 벡터 저장소로 사용하도록 구성할 때, Mem0은(는) 이 메모리 문서를 MongoDB 컬렉션에 유지합니다. 이것은 의미 검색을 위해 MongoDB 벡터 검색을 사용하고, 전문 키워드 검색을 위해 MongoDB Search를 사용합니다. Mem0가 컬렉션에 첫 연결할 때 인덱스 두 개를 만들어 줍니다.
전제 조건
이 튜토리얼을 완료하려면 다음 리소스가 있어야 합니다:
다음 MongoDB cluster 유형 중 하나입니다.
MongoDB 버전 6.0.11을 실행하는 Atlas 클러스터, 7.0.2 이상. 당신의 IP 주소가 Atlas 프로젝트의 액세스 목록에 포함되어 있는지 확인하세요.
Python과 Docker를 사용하여 만든 로컬 Atlas 배포서버입니다.
atlas-local-lib-py(pip install atlas-local-lib-py)를 설치하여 로컬 배포서버를 프로그래밍으로 만들고 관리할 수 있습니다. 자세한 내용은 atlas-local-lib-py 리포지토리를 참조하십시오.A MongoDB Community cluster with Search and Vector Search installed.
OpenAI API 키입니다. API 요청에 사용할 수 있는 크레딧이 있는 OpenAI 계정이 있어야 합니다. OpenAI 계정 등록에 대해 자세히 학습하려면 OpenAI API 웹사이트를 참조하세요.
Python v3.10 이상.
환경 설정
환경 변수를 설정합니다.
mem0-mongodb-project 디렉토리에서 .env 파일을 만들고 다음 코드를 추가합니다.
OPENAI_API_KEY="<openai-api-key>" MONGODB_URI="<connection-string>"
<connection-string>을 Atlas 클러스터 또는 로컬 Atlas 배포서버의 연결 문자열로 교체합니다.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
중요한: 연결 문자열 에 데이터베이스 사용자의 자격 증명 포함되어 있는지 확인하세요. 연결 문자열 찾는 방법에 대해 자세히 학습하려면 클라이언트 라이브러리를 통해 클러스터에 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true
자세한 학습 은 연결 문자열을 참조하세요.
메모리 데이터 저장 및 조회
이 섹션에서 Mem0을 구성하여 MongoDB를 벡터 저장소로 사용합니다. 그런 다음, Mem0이 대화에서 추출한 기억을 저장하고 시맨틱 검색을 사용하여 이를 조회합니다.
MongoDB를 vector 저장소로 구성합니다.
Mem0 벡터 저장소로서의 MongoDB를 사용하려면 main.py 파일에 다음 코드를 추가합니다.
config = { "llm": { "provider": "openai", "config": { "model": "gpt-4o-mini", "temperature": 0.1, "max_tokens": 2000, }, }, "embedder": { "provider": "openai", "config": { "model": "text-embedding-3-small", "embedding_dims": 1536, }, }, "vector_store": { "provider": "mongodb", "config": { "mongo_uri": os.environ["MONGODB_URI"], "db_name": "mem0_db", "collection_name": "agent_memory", "embedding_model_dims": 1536, }, }, } m = Memory.from_config(config)
이 코드는 config 사전에서 다음 키를 설정합니다:
llm: 대화에서 사실을 추출하는 모델로gpt-4o-mini을(를) 지정합니다.embedder:text-embedding-3-small을(를) 임베딩 생성 모델로 지정합니다.vector_store: MongoDB를 벡터 저장소로 구성합니다
The index should take about one minute to build. While it builds, the index is in an initial sync state. When it finishes building, you can start querying the data in your collection.
대화 내용을 기억으로 저장합니다.
사용자의 이전에 대한 대화에서 메모리를 추출하고 저장하려면 다음 코드를 추가하세요.
messages = [ {"role": "user", "content": "I'm moving to Berlin next month."}, {"role": "assistant", "content": "I'll remember that you're relocating to Berlin."}, ] result = m.add(messages, user_id="alice") print(result)
대화 데이터를 add() 메서드에 전달하면, Mem0은 LLM을 사용하여 대화에서 사실을 추출하고 각 사실을 별도의 메모리 문서로 컬렉션에 쓰기 (write)합니다.
두 번째 대화에서 메모리 저장.
Mem0이 동일한 사용자의 기억 프로필에 추가하는 두 번째 대화에서의 기억을 저장하려면 다음 코드를 추가합니다:
messages = [ {"role": "user", "content": "I prefer concise answers and I use Python daily."}, {"role": "assistant", "content": "Noted. I'll keep my responses brief and Python-focused."}, ] result = m.add(messages, user_id="alice") print(result)
저장된 기억을 검색합니다.
사용자의 재배치에 대한 쿼리에 대한 답변을 제공하는 메모리 데이터를 검색하려면 main.py 파일에 다음 코드를 추가합니다.
print("\nWaiting for the MongoDB Vector Search index to finish building...") time.sleep(60) results = m.search( query="When is Alice moving?", filters={"user_id": "alice"}, top_k=5, ) for mem in results["results"]: print(mem["memory"], "- score:", mem["score"])
쿼리를 실행하기 전에 코드는 MongoDB 벡터 검색 인덱스가 빌드를 완료할 수 있도록 60 초 동안 기다립니다.
팁
저장된 메모리 문서를 확인하려면 Atlas UI에서 mem0_db.agent_memory 컬렉션을 찾아보세요. 더 자세히 학습하려면 컬렉션 보기를 참조하세요.
메모리 증강 어시스턴트 빌드
이 섹션에서는 메모리 저장과 검색을 결합하여 자신의 응답을 개인화하는 어시스턴트를 구성하는 방법을 보여줍니다. 어시스턴트가 응답하기 전에 현재 메시지와 가장 관련성이 높은 기억을 조회하여 시스템 프롬프트에 추가합니다. 응답한 후, 새로운 대화 턴을 저장합니다. 따라서 모든 교환을 통해 기억이 늘어납니다.
기억을 조회하고 시스템 프롬프트를 빌드합니다.
main.py 파일에서, 메시지에 가장 관련있는 메모리를 검색하고 그 메모리를 시스템 프롬프트에 추가하는 함수를 정의하는 다음 코드를 추가하세요.
openai_client = OpenAI() USER_ID = "alice" def build_system_prompt(user_message): # Retrieve the memories that are most relevant to the message relevant = m.search( query=user_message, filters={"user_id": USER_ID}, top_k=5, ) memory_text = "\n".join(f"- {mem['memory']}" for mem in relevant["results"]) # Add the retrieved memories to the system prompt system_prompt = "You are a helpful personal assistant." if memory_text: system_prompt += ( " Use the following facts to personalize your response:\n" f"{memory_text}" ) return system_prompt
응답을 생성하고 대화 턴을 저장합니다.
개인화된 응답을 생성하고 새 대화 턴을 메모리로 저장핕는 함수를 정의하려면 다음 코드를 추가하세요.
def chat(user_message): # Generate a response response = openai_client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": build_system_prompt(user_message)}, {"role": "user", "content": user_message}, ], ) assistant_message = response.choices[0].message.content # Store the new conversation turn as memories m.add( [ {"role": "user", "content": user_message}, {"role": "assistant", "content": assistant_message}, ], user_id=USER_ID, ) return assistant_message print(chat("Can you recommend a programming meetup in my city?"))
어시스턴이 프롬프트를 조립하기 전에 MongoDB에서 Alice의 위치 및 언어 기호도를 조회했기 때문에, 베를린에서 Python 모임을 추천합니다.
파일 실행
main.py 파일을 실행하려면 mem0-mongodb-project 디렉토리에서 다음 명령을 실행하세요:
python main.py
명령이 성공적으로 실행되면 출력은 다음과 유사합니다.
# Output from the first add() method that stores relocation data {'results': [{'id': '...', 'memory': 'User is moving to Berlin around September 2026.', 'event': 'ADD'}]} # Output from the second add() method that stores user preferences {'results': [{'id': '...', 'memory': 'Prefers concise answers', 'event': 'ADD'}, {'id': '...', 'memory': 'Uses Python daily', 'event': 'ADD'}]} Waiting for the MongoDB Vector Search index to finish building... # Output from the search() method that retrieves the relocation memory User is moving to Berlin in September 2026. - score: 0.38553877995545677User is moving to Berlin around September 2026. - score: 0.7043201923370361 # Output from the get_all() method that returns the full memory history <id> User is moving to Berlin around September 2026. <id> Prefers concise answers <id> Uses Python daily # Output from the chat() method that asks the assistant about programming meetups Since you're moving to Berlin around September 25, 2026, I recommend checking platforms like Meetup.com or Eventbrite closer to your move for local Python programming meetups. You can also follow local tech communities on social media for updates on events.
다음 단계
Mem0 구성 키와 Memory 메서드 전체 세트에 대해 자세히 학습하려면 MongoDB와 Mem0 통합을 참조하세요.
To learn more about the indexes that Mem0 creates on your collection, see Create a MongoDB Vector Search Index and Manage MongoDB Search Indexes.