Docs Menu
Docs Home
/
Atlas
/ / /

LangGraph 및 MongoDB Atlas 로 AI 에이전트 구축

MongoDB Atlas와 LangGraph 를 통합하여 AI 에이전트를 빌드 할 수 있습니다. 이 튜토리얼에서는 MongoDB 의 샘플 데이터에 대한 질문에 답변하는 AI 에이전트 빌드 방법을 보여줍니다.

구체적으로, 에이전트 통합을 사용하여 에이전트적 RAG에이전트 메모리를 구현 . 시맨틱 검색 및 전체 텍스트 검색 도구를 사용하여 관련 정보를 조회 하고 데이터에 대한 질문에 답변 . 또한 대화 기록과 중요한 상호 작용을 별도의 컬렉션에 저장하여 MongoDB 사용하여 장단기 기억을 모두 구현합니다.

이 페이지의 코드는 전체 샘플 애플리케이션 빌드합니다. 단계별로 학습 하려는 경우 Python 노트북 으로 코드를 통해 작업할 수도 있습니다.

이 튜토리얼을 완료하려면 다음 조건을 충족해야 합니다.

  • 다음 MongoDB cluster 유형 중 하나입니다.

    • MongoDB 버전 6.0.11 을 실행 Atlas cluster , 7.0.2 이상입니다. IP 주소 가 Atlas 프로젝트의 액세스 목록에 포함되어 있는지 확인하세요.

    • Atlas CLI 사용하여 생성된 로컬 Atlas 배포서버 입니다. 자세히 학습 로컬 Atlas 배포 만들기를 참조하세요.

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

  • Voyage AI API 키입니다. 자세한 학습 은 API 키 및 Python 클라이언트를 참조하세요.

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

참고

langchain-voyageai 패키지의 요구 사항을 확인하여 호환되는 Python 버전을 사용하고 있는지 확인하세요.

환경을 설정하려면 다음 단계를 완료하세요.

1

새 프로젝트 디렉토리를 만든 후, 필요한 종속성을 설치합니다.

mkdir langgraph-mongodb-ai-agent
cd langgraph-mongodb-ai-agent
pip install --quiet --upgrade python-dotenv langgraph langgraph-checkpoint-mongodb langgraph-store-mongodb langchain langchain-mongodb langchain-voyageai langchain-openai pymongo

참고

프로젝트는 다음 구조를 사용합니다.

langgraph-mongodb-ai-agent
├── .env
├── config.py
├── search-tools.py
├── memory-tools.py
├── agent.py
├── main.py
2

프로젝트 에 .env 파일 만들고 다음 변수를 지정합니다. 자리 표시자 값을 유효한 API 키와 MongoDB 클러스터의 연결 문자열 로 바꿉니다.

VOYAGE_API_KEY = "<voyage-api-key>"
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

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

저장 및 검색을 위한 벡터 데이터베이스 로 MongoDB 구성하려면 다음 단계를 완료하세요.

1

이 튜토리얼에서는 샘플 데이터 세트 중 하나를 데이터 소스 로 사용합니다. 아직 완료하지 않았다면 샘플 데이터를 Atlas cluster 에 로드하는 단계를 완료하세요.

구체적으로 영화의 줄거리 벡터 임베딩을 포함한 영화에 대한 문서를 포함하는 embedded_movies 데이터 세트를 사용하게 됩니다.

참고

자체 데이터를 사용하려면 LangChain 시작하기 또는 벡터 임베딩 생성 방법을 참조하여 Atlas에 벡터 임베딩을 삽입하는 방법을 알아보세요.

2

프로젝트 에 config.py 이라는 파일 만듭니다. 이 파일 MongoDB 에이전트 의 벡터 저장 로 구성합니다. 또한 샘플 데이터에 대한 벡터 검색 및 전체 텍스트 검색 쿼리를 활성화 인덱스를 생성합니다.

프로젝트 에 search_tools.py 파일 만듭니다. 이 파일 에서는 에이전트 에이전트적 RAG를수행하는 데 사용하는 검색 도구를 정의합니다.

참고

특정 작업 수행에 필요한 모든 도구를 정의할 수 있습니다. 하이브리드 검색이나 상위 문서 조회와 같은 다른 검색 방법을 위한 도구도 정의할 수 있습니다.

프로젝트 에 memory_tools.py 파일 만듭니다. 이 파일 에서는 에이전트 장기 기억을 구현 위해 세션 전반에 걸쳐 중요한 상호 작용을 저장 하고 조회 사용할 수 있는 도구를 정의합니다.

프로젝트 에 agent.py 파일 만듭니다. 이 파일 에서는 에이전트의 워크플로를 조정하는 그래프 를 빌드 . 이 에이전트는 MongoDB Checkpointer 구성 요소를 사용하여 단기 메모리를 구현, 별도의 기록으로 여러 개의 동시 대화를 허용합니다.

에이전트 다음 워크플로를 사용하여 쿼리에 응답합니다.

  1. 시작: 에이전트 사용자 쿼리 수신합니다.

  2. 에이전트 노드: 도구 바인딩된 LLM은 쿼리를 분석하고 도구가 필요한지 결정합니다.

  3. 연장 노드 (필요한 경우): 적절한 검색 또는 메모리 연장을 실행합니다.

  4. 종료: LLM이 도구의 출력을 사용하여 최종 응답을 생성합니다.

LangGraph-MongoDB 에이전트의 워크플로를 보여주는 다이어그램입니다.
클릭하여 확대

지속성, 단기 기억 및 MongoDB 체크포인터에 대해 자세히 학습 다음 리소스를 참조하세요.

마지막으로 프로젝트에 main.py라는 파일을 만듭니다. 이 파일은 에이전트를 실행하고 사용자와 상호 작용할 수 있게 합니다.

프로젝트를 저장하고 다음 명령을 실행합니다. 에이전트를 실행할 때 다음을 수행합니다.

  • 에이전트 벡터 저장 초기화하고 인덱스가 아직 존재하지 않는 경우 인덱스를 생성합니다.

  • 세션 ID 입력하여 새 세션을 시작하거나 기존 세션을 계속할 수 있습니다. 각 세션은 유지되며 언제든지 이전 대화를 재개할 수 있습니다.

  • 영화에 대해 질문합니다. 에이전트 도구와 이전 상호 작용을 기반으로 응답을 생성합니다.

다음 출력은 샘플 상호 작용을 보여줍니다.

python main.py
Creating vector search index...
Vector search index created successfully!
Creating search index...
Search index created successfully!
Enter a session ID: 123
Ask me about movies! Type 'quit' to exit.
Your query: What are some movies that take place in the ocean?
🔧 Agent chose to use tool(s): plot_search
→ Executing plot_search
Answer: Here are some movies that take place in the ocean:
1. **20,000 Leagues Under the Sea** - A marine biologist, his daughter, and a mysterious Captain Nemo explore the ocean aboard an incredible submarine.
2. **Deep Rising** - A group of armed hijackers board a luxury ocean liner in the South Pacific Ocean, only to fight man-eating, tentacled sea creatures.
... (truncated)
Your query: What is the plot of the Titanic?
🔧 Agent chose to use tool(s): title_search
→ Executing title_search
Answer: The plot of *Titanic* involves the romantic entanglements of two couples aboard the doomed ship's maiden voyage
... (truncated)
Your query: What movies are like the movie I just mentioned?
🔧 Agent chose to use tool(s): plot_search
→ Executing plot_search
Answer: Here are some movies similar to *Titanic*:
1. **The Poseidon Adventure** - A group of passengers struggles to survive when their ocean liner capsizes at sea.
2. **Pearl Harbor** - Focused on romance and friendship amidst the backdrop of a historical tragedy, following two best friends and their love lives during wartime.
... (truncated)
Your query: I don't like sad movies.
🔧 Agent chose to use tool(s): save_memory
→ Executing save_memory
Answer: Got it—I'll keep that in mind. Let me know if you'd like recommendations that focus more on uplifting or happy themes!
(In different session)
Enter a session ID: 456
Your query: Recommend me a movie based on what you know about me.
🔧 Agent chose to use tool(s): retrieve_memories
→ Executing retrieve_memories
Answer: Based on what I know about you—you don't like sad movies—I'd recommend a fun, uplifting, or action-packed film. Would you be interested in a comedy, adventure, or family-friendly movie?
Your query: Sure!
🔧 Agent chose to use tool(s): plot_search, plot_search, plot_search
→ Executing plot_search
→ Executing plot_search
→ Executing plot_search
Answer: Here are some movie recommendations from various uplifting genres that suit your preferences:
### Comedy:
1. **Showtime** (2002): A spoof of buddy cop movies where two very different cops are forced to team up on a new reality-based TV cop show. It's packed with laughs and action!
2. **The Big Bus** (1976): A hilarious disaster film parody featuring a nuclear-powered bus going nonstop from New York to Denver, plagued by absurd disasters.
### Adventure:
1. **Journey to the Center of the Earth** (2008): A scientist, his nephew, and their mountain guide discover a fantastic and dangerous lost world at the earth's core.
2. **Jason and the Argonauts** (1963): One of the most legendary adventures in mythology, brought to life in this epic saga of good versus evil.
### Family-Friendly:
1. **The Incredibles** (2004): A family of undercover superheroes is forced into action to save the world while living in quiet suburban life.
2. **Mary Poppins** (1964): A magical nanny brings joy and transformation to a cold banker's unhappy family.
3. **Chitty Chitty Bang Bang** (1968): A whimsical adventure featuring an inventor, his magical car, and a rescue mission filled with fantasy.

돌아가기

LangGraph

스킬 배지 획득

'Gen AI'를 무료로 마스터하세요!

자세한 내용을 알아보세요.

이 페이지의 내용