AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

MongoDB Mem0 통합 시작하기

MongoDB Mem0과 통합하여 대화 전반에 걸쳐 지속되는 AI 에이전트의 장기 메모리를 구성할 수 있습니다. 이 튜토리얼에서는 MongoDB 벡터 저장 로 사용하도록 Mem0을 구성한 다음 메모리 강화 어시스턴트를 빌드합니다. 이 튜토리얼에서는 다음 작업을 수행합니다.

  1. 환경을 설정합니다.

  2. MongoDB Mem0 벡터 저장 로 사용합니다.

  3. 메모리 문서를 저장하고 조회 .

  4. 검색한 메모리를 기반으로 응답을 개인화하는 어시스턴트를 빌드하세요.

Mem0 은 AI 에이전트 및 어시스턴트를 위한 오픈소스 메모리 계층입니다. 모든 요청 에 대해 전체 대화 기록을 LLM에 전달하는 대신 Mem 은0 대화에서 불연속적인 팩트를 추출하고 각 팩트를 문서 로 저장하며 쿼리 시점에 가장 관련성이 높은 팩트만 검색합니다.

MongoDB 벡터 저장 로 사용하도록 Mem0을 구성하면 Mem0은 이러한 메모리 문서를 MongoDB 컬렉션 에 유지합니다. 시맨틱 검색에는 MongoDB Vector Search를 사용하고 전체 텍스트 키워드 검색에는 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 리포지토리 참조하세요.

    • 검색 및 벡터 검색이 설치된 MongoDB Community 클러스터 .

  • OpenAI API 키입니다. API 요청에 사용할 수 있는 크레딧이 있는 OpenAI 계정이 있어야 합니다. OpenAI 계정 등록에 대한 자세한 내용은 OpenAI API 웹사이트를 참조하세요.

  • Python v3.10 이상.

1

터미널에서 다음 명령을 실행하여 mem0-mongodb-project 라는 새 디렉토리 만들고 필요한 종속성을 설치합니다.

mkdir mem0-mongodb-project
cd mem0-mongodb-project
pip install mem0ai pymongo openai python-dotenv

Mem0 에는 PyMongo v4.13.2 이상이 필요합니다. 앞의 명령은 최신 버전의 PyMongo 설치합니다.

2

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

자세한 학습 은 연결 문자열을 참조하세요.

3

mem0-mongodb-project 디렉토리 에서 main.py이라는 파일 만듭니다. 이 파일 에 다음 코드를 추가하여 환경 변수를 로드합니다.

from mem0 import Memory
from openai import OpenAI
from dotenv import load_dotenv
import os
load_dotenv()

이후 단계에서는 이 파일 에 코드를 추가하여 Mem0을 구성하고 어시스턴트를 빌드 .

이 섹션에서는 MongoDB 벡터 저장 로 사용하도록 Mem0을 구성합니다. 그런 다음 Mem0이 대화에서 추출한 메모리를 저장 하고 시맨틱 검색 사용하여 조회 .

1

MongoDB Mem0 벡터 저장 로 사용하려면 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 벡터 저장 로 구성합니다.

인덱스 빌드 데 약 1분 정도 소요됩니다. 빌드되는 동안 인덱스 는 초기 동기화 상태 입니다. 빌드가 완료되면 컬렉션 의 데이터 쿼리를 시작할 수 있습니다.

2

사용자의 재배치에 대한 대화에서 메모리를 추출하고 저장 하려면 다음 코드를 추가합니다.

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을 사용하여 대화에서 팩트를 추출하고 각 팩트를 별도의 메모리 문서 로 컬렉션 에 씁니다.

3

다음 코드를 추가하여 동일한 사용자의 메모리 프로필에 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)
4

사용자 재배치에 대한 쿼리 에 답변하는 메모리 데이터를 검색 하려면 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 Vector Search 인덱스 빌드가 완료될 때까지 60 초 동안 기다립니다.

5

시맨틱 검색 실행 하지 않고 사용자의 전체 메모리 기록을 반환하려면 main.py 파일 에 다음 코드를 추가합니다.

all_memories = m.get_all(filters={"user_id": "alice"})
for mem in all_memories["results"]:
print(mem["id"], mem["memory"])

저장된 메모리 문서를 검사하려면 mem0_db.agent_memory Atlas UI 에서 컬렉션 찾습니다. 자세히 학습 컬렉션 보기를 참조하세요.

이 섹션에서는 메모리 저장 과 조회를 결합하여 응답을 개인화하는 어시스턴트를 만드는 방법을 보여줍니다. 어시스턴트는 응답하기 전에 현재 메시지와 가장 관련 있는 메모리를 검색하여 시스템 프롬프트에 추가합니다. 응답한 후 새로운 대화 차례를 저장하여 교환할 때마다 메모리가 커집니다.

1

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
2

다음 코드를 추가하여 개인화된 응답을 생성하고 새 대화 차례를 메모리로 저장하는 함수를 정의합니다.

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 와 Mem 통합하기 를 참조하세요.0

Mem 이 컬렉션0 에 생성하는 인덱스에 대해 자세히 학습 MongoDB 벡터 검색 인덱스 만들기및 MongoDB 검색 인덱스 관리를 참조하세요.