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

MongoDB Strands 에이전트 통합 시작하기

MongoDB를 Strands 에이전트와 통합하면 에이전트의 대화 세션과 장기 기억 데이터를 MongoDB 환경에 저장할 수 있습니다. 이 튜토리얼에서는 strands-mongodb를 사용합니다. 이 패키지는 에이전트 세션을 유지하고 데이터를 저장 및 검색하는 데 사용됩니다. 그런 다음 MongoDB에 저장된 메모리를 사용하여 펭귄에 대한 질문에 답하는 에이전트를 실행합니다.

이 튜토리얼에서는 다음 작업을 수행합니다.

  1. 환경을 설정합니다.

  2. 펭귄에 대한 정보를 메모리 저장소에 저장하고, 이러한 정보를 활용하는 MongoDB 벡터 검색 쿼리를 정의하세요.

  3. 세션 및 메모리 관리에 MongoDB를 사용하는 에이전트를 구성합니다.

  4. 파일을 실행하고 출력을 검토하세요.

Strands Agents is AWS's open-source Python SDK for building AI agents. This tutorial uses the following strands-mongodb classes to connect an agent to MongoDB:

  • MongoDBStorage에이전트 세션, 컨텍스트 관리 데이터 및 대화 기록을 MongoDB에 저장합니다.

  • MongoDBMemoryStore: 정보를 MongoDB에 메모리 문서로 저장하고, 의미, 키워드 또는 둘 다를 사용하여 검색합니다.

기본적으로 MongoDB 벡터 검색은 메모리에 대한 임베딩을 생성하므로 임베딩 모델이나 임베딩 제공자 API 키가 필요하지 않습니다.

이 튜토리얼을 완료하려면 다음 리소스가 있어야 합니다:

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

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

  • Python v3.10 이상.

  • uv.

이 섹션에서는 필수 종속성을 설치하고, 환경 변수를 설정하고, 프로젝트 파일을 생성하여 환경을 준비합니다.

1

Run the following commands in your terminal to create a new directory named strands-mongodb-project and start a virtual environment:

mkdir strands-mongodb-projectcd strands-mongodb-projectuv venvsource .venv/bin/activate
2

strands-mongodb-project 디렉토리에서 다음 명령을 실행하여 필요한 종속 항목을 설치합니다.

uv pip install 'strands-mongodb[all]' 'strands-agents[openai]' python-dotenv

The strands-agents[openai] extra installs the OpenAI model provider that this tutorial uses. To use a different provider, see Model Providers in the Strands Agents documentation.

3

In your strands-mongodb-project directory, create an .env file and add the following code:

OPENAI_API_KEY="<openai-api-key>"MONGODB_URI="<connection-string>"

Replace <openai-api-key> with your OpenAI API key.

<connection-string>을 Atlas 클러스터 또는 로컬 Atlas 배포서버의 연결 문자열로 교체합니다.

연결 문자열은 다음 형식을 사용해야 합니다.

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

중요한: 연결 문자열 에 데이터베이스 사용자의 자격 증명 포함되어 있는지 확인하세요. 연결 문자열 찾는 방법에 대해 자세히 학습하려면 클라이언트 라이브러리를 통해 클러스터에 연결하기를 참조하세요.

4

In your strands-mongodb-project directory, create a file named main.py. Add the following code to this file to load your environment variables, import the required modules, and define the --query command-line argument:

import argparseimport asyncioimport os from dotenv import load_dotenvfrom strands import Agentfrom strands.memory import MemoryManagerfrom strands.models.openai import OpenAIModelfrom strands.session import SnapshotSessionManagerfrom strands_mongodb import MongoDBMemoryStore, MongoDBStoragefrom strands_mongodb.types import MongoDBConfig load_dotenv() parser = argparse.ArgumentParser()parser.add_argument("--query", required=True)args = parser.parse_args()

다음 단계에서는 이 파일에 코드를 추가하여 MongoDB 연결을 구성하고, 메모리 문서를 저장하고, 이러한 문서에 액세스하는 에이전트를 생성합니다.

이 섹션에서는 MongoDB에 연결하고, 펭귄에 대한 정보를 메모리 저장소에 저장하고, 이러한 정보를 사용하는 MongoDB 벡터 검색 쿼리를 정의합니다.

1

Add the following code to your main.py file to create a MongoDBConfig dictionary that accesses the strands_tutorial database:

connection: MongoDBConfig = { "connection_string": os.environ["MONGODB_URI"], "database": "strands_tutorial",}

MongoDB에 연결하는 모든 클래스가 하나의 연결 풀을 공유하도록 하려면 이 사전을 모든 클래스와 공유하십시오.

2

Add the following code to your main.py file to create a MongoDBMemoryStore instance that saves each memory as a document in the memory collection:

store = MongoDBMemoryStore( name="penguin_facts", config=connection, scope="field-researcher", writable=True,)

이 코드는 다음 매개변수를 설정합니다.

  • name: Identifies the memory store. The store adds a field named store_name to every memory document and sets the field's value to "penguin_facts". The store reads only the memories that hold this value.

  • scope이 메모리 문서를 다른 사용자나 에이전트가 동일한 컬렉션에 저장하는 메모리와 구분합니다.

  • writable: Allows the memory store and the agent to save memories. The default value is False.

3

Add the following code to your main.py file to define the program's entry point and save three memory documents, which store penguin facts:

async def main() -> None: await store.add( "Emperor penguins can dive deeper than any other bird," " reaching depths of over 500 meters." ) await store.add( "Gentoo penguins are the fastest underwater swimmers among" " penguins, reaching speeds of up to 36 kilometers per hour." ) await store.add( "Adélie penguins live along the Antarctic coastline." )
4

Add the following code to your main() function to search the memory documents. The code prints every memory document that the search returns, ranked by relevance to the --query value.

found = []for _ in range(60): found = await store.search(args.query) if len(found) >= 3: break await asyncio.sleep(5)else: raise SystemExit("The search indexes are not ready. Try again.") print("Search results:")for entry in found: print(f"- {entry.content}")

MongoDB 벡터 검색은 쓰기 작업이 완료된 후 각 새 메모리 문서에 대한 임베딩을 비동식으로 생성합니다. 임베딩이 준비될 때까지 벡터 검색 결과가 불완전할 수 있습니다. 위의 코드는 세 개의 메모리를 모두 반환할 때까지 최대 5분 동안 5초마다 검색을 재시도합니다.

이 섹션에서는 세션을 MongoDB에 저장하고 메모리 저장소를 사용하여 질문에 답변하는 에이전트를 구성합니다.

1

Add the following code to your main.py file's main() function to create a MongoDBStorage instance. The instance saves the agent's sessions in the storage collection:

storage = MongoDBStorage(connection)
2

Add the following code to your main() function to create an agent that uses MongoDB for sessions and memory:

agent = Agent( model=OpenAIModel( client_args={"api_key": os.environ["OPENAI_API_KEY"]}, model_id="gpt-4o", ), storage=storage, session_manager=SnapshotSessionManager( session_id="penguin-research" ), memory_manager=MemoryManager( stores=[store], add_tool_config=True ), callback_handler=None,)

이 코드는 다음과 같은 매개변수를 전달합니다.

  • model: Uses the gpt-4o model from OpenAI to generate agent responses.

  • storage에이전트의 하위 시스템이 영구 데이터를 저장하는 데 사용하는 백엔드를 제공합니다.

  • session_manager: Saves the conversation under the specified session ID. The storage parameter alone does not persist sessions.

  • memory_manager: Provides the agent with a search_memory tool. Setting the add_tool_config parameter to True also configures the add_memory tool for saving new memories.

  • callback_handlerSDK의 스트리밍 출력을 콘솔에서 숨깁니다.

3

Add the following code to your main() function to send the --query value to the agent and print the agent's answer. The code also lists the keys prefixed with session/ to show that the agent saved the session in MongoDB.

result = await agent.invoke_async(args.query)print("\nAgent:", str(result).strip()) print("\nSession keys:")for key in await storage.list("session/"): print(f"- {key}") await store.close()

Then, add the following code after the main() function to run it:

asyncio.run(main())

To run the main.py file, run the following command from your strands-mongodb-project directory. Use the --query flag to specify the question that the application sends to the agent:

uv run main.py --query "Which penguin species can dive the deepest?"

명령이 성공적으로 실행되면 출력은 다음과 유사합니다.

Search results:- Emperor penguins can dive deeper than any other bird, reaching depths of over 500 meters.- Adélie penguins live along the Antarctic coastline.- Gentoo penguins are the fastest underwater swimmers among penguins, reaching speeds of up to 36 kilometers per hour. Agent: Emperor penguins can dive deeper than any other bird, reaching depths of over 500 meters. Session keys:- session/penguin-research/scopes/agent/default/snapshots/snapshot_latest.json

The agent answered the question by using the documents stored in MongoDB, and it saved the conversation under the penguin-research session ID.

To learn more about MongoDBStorage, MongoDBMemoryStore, and their full parameter and method reference, see Integrate MongoDB with Strands Agents.

Strands Agents에 대한 자세한 내용은 Strands Agents 문서를 참조하십시오.