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

MongoDB를 Strands 에이전트와 통합하세요

MongoDB를 Strands Agents 와 통합할 수 있습니다. AI 에이전트 구축을 위한 오픈 소스 Python SDK입니다.strands-mongodb 이 패키지를 사용하면 다음 클래스의 백엔드로 MongoDB 배포를 사용할 수 있습니다.

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

  • MongoDBMemoryStore 는 의미론적 의미, 키워드 또는 이 둘의 조합을 통해 사실을 저장하고 불러옵니다.

MongoDB를 사용하도록 Strands Agent를 구성하는 방법에 대한 튜토리얼을 완료하려면 MongoDB Strands Agent 통합 시작하기를 참조하세요.

To install the strands-mongodb package and the dependencies for the MongoDBStorage and MongoDBMemoryStore classes, run the following command:

pip install 'strands-mongodb[all]'

이 명령은 다음 종속성을 설치합니다.

  • strands-mongodbStrands Agents용 MongoDB 통합 패키지입니다.

  • strands-agents: The Strands Agents SDK. The package requires v1.54 or later.

  • pymongo: The official Python driver for MongoDB. The package requires v4.14 or later.

  • pymongo-search-utils: Utilities for working with MongoDB's vector search features. The package requires v0.3 or later.

  • opentelemetry-api: The OpenTelemetry API for Python. The package requires v1.30 or later.

  • typing-extensions: Backported typing features for Python. The package requires v4.13.2 or later.

또는 다음 명령 중 하나를 실행하여 개별 클래스에 필요한 종속성을 설치하십시오.

pip install 'strands-mongodb[storage]' # MongoDBStoragepip install 'strands-mongodb[memory]' # MongoDBMemoryStore

To configure your MongoDB connection, pass a MongoDBConfig dictionary to the MongoDBStorage or MongoDBMemoryStore class. Create one MongoDBConfig dictionary per process and pass it to every class you use, which allows them to share one connection pool.

You can specify either an existing client or a connection string to configure your connection. Select the Existing client or Connection string tab to view a corresponding example:

from pymongo import AsyncMongoClientfrom strands_mongodb.types import MongoDBConfig client = AsyncMongoClient("<connection-string>")connection: MongoDBConfig = { "client": client, "database": "agents",}

참고

해당 패키지는 클라이언트 소유권을 가져가지 않습니다. 클라이언트 종료는 사용자 책임입니다.

To learn more about AsyncMongoClient, see Create a MongoClient.

The MongoDBStorage class allows you to save an agent's persistent data in MongoDB. Once configured, the SDK stores the agent's sessions, context management data, and transcripts as documents in a MongoDB collection instead of in local files or memory. The persistent data is stored under string keys, and each key becomes a document's _id value. As a result, read and write operations perform primary-key lookups.

This section describes how to configure and use the methods provided by the MongoDBStorage class.

To configure this class, pass a MongoDBConfig dictionary and a collection name to the MongoDBStorage constructor. The following example writes persistent data to MongoDB, retrieves this data, lists keys that start with a specified prefix, and deletes the data:

import asyncio from strands_mongodb import MongoDBStorage async def main() -> None: storage = MongoDBStorage(connection, collection="storage") try: await storage.write("notes/colony", b"emperor penguins live in Antarctica") print(await storage.read("notes/colony")) print(await storage.list("notes/")) await storage.delete("notes/colony") finally: await storage.close() asyncio.run(main())

이 클래스를 사용하도록 에이전트를 구성하는 방법을 알아보려면 에이전트 구성하기를 참조하세요.

The following table lists the methods provided by the MongoDBStorage class:

메서드
설명
매개변수
반환 값

write()

Stores persistent data as bytes in a key, replacing any existing value. If you set ttl_seconds, this method also adds an expires_at field to the document it writes.

key: The key to store the data under.
data: The bytes to store.

None

read()

키에 저장된 바이트를 반환합니다.

key읽는 법의 핵심.

bytes, or None when the key is absent

delete()

키 하나를 제거합니다. 존재하지 않는 키를 삭제하는 경우 이 메서드는 오류를 발생시키지 않습니다.

key제거하는 열쇠.

None

list()

지정된 접두사로 시작하는 키의 이름을 오름차순으로 반환합니다. 저장된 값은 포함하지 않고 키만 반환합니다.

query일치시킬 키 접두사입니다.

list[str]

search()

By default, this method ranks stored key names by how many words they share with a query. To search the stored values instead, set MongoDBStorage's search_strategy parameter to a strategy that reads values, such as the SDK's KeywordSearchStrategy or MongoDBVectorSearchStrategy for vector search.

query검색할 텍스트입니다.

list[StorageSearchResult]

delete_prefix()

지정된 접두사로 시작하는 모든 키를 제거합니다.

prefix제거할 키 접두사입니다.

int이는 삭제된 문서의 수를 나타냅니다.

namespace()

Returns a new MongoDBStorage scoped to a prefix in the same collection, sharing the original connection pool, collection, TTL, and search strategy. This method is synchronous.

prefix: 새 인스턴스의 범위를 지정하는 접두사입니다.

MongoDBStorage

ensure_indexes()

Creates or verifies the TTL index that ttl_seconds requires. Call this method once at startup.

none

None

close()

Releases the connection pool for every instance that shares the same MongoDBConfig dictionary. Call this method once at process shutdown.

none

None

When you pass a MongoDBStorage instance to an Agent, the agent's session and context subsystems call write(), read(), delete(), list(), and search() for you. You call ensure_indexes(), close(), namespace(), and delete_prefix() yourself.

The MongoDBMemoryStore class allows you to save an agent's long-term memory in MongoDB. Once configured, the agent stores facts in a MongoDB collection and retrieves them by meaning, by keyword, or both. The store uses MongoDB Vector Search for semantic recall and MongoDB Search for keyword recall.

MongoDB 벡터 검색을 사용하려면 MongoDB는 데이터의 벡터 임베딩과 쿼리의 임베딩을 비교합니다. 기본적으로 MongoDB는 이러한 임베딩을 자동으로 생성하므로 벡터나 임베딩 제공자 API 키를 관리할 필요가 없습니다.

This section describes how to configure and use the methods provided by the MongoDBMemoryStore class.

To configure this class, pass a name and a MongoDBConfig dictionary to the MongoDBMemoryStore constructor.

This example creates a memory store, adds a memory, and then searches for the memory by semantic meaning. When instantiating a MongoDBMemoryStore, the example also sets the following optional parameters:

  • scope: Limits the memory store's access to documents that store the specified scope field value. The example uses the scope "user-abc".

  • writable메모리 저장소에 대한 쓰기 작업을 활성화합니다.

import asyncio from strands_mongodb import MongoDBMemoryStore async def main() -> None: store = MongoDBMemoryStore( name="preferences", config=connection, scope="user-abc", writable=True ) try: await store.add("Studies emperor penguins in Antarctica.") results = await store.search("Which animals does this researcher observe?") for entry in results: print(f"search type: {entry.metadata['_search_type']}") print(f"score: {entry.metadata['_relevance_score']}") print(f"content: {entry.content}") finally: await store.close() asyncio.run(main())

MongoDBMemoryStore 다음 검색 유형을 사용하여 쿼리에 대한 답변을 제공합니다.

  • 의미를 기준으로 일치시키는 벡터 검색입니다.

  • 키워드를 기준으로 일치시키는 텍스트 검색입니다.

  • 하이브리드 검색은 두 가지 검색 유형을 결합한 것입니다.

The search_type key in the MongoDBConfig dictionary controls which search types the store uses. The default value, "auto", prepares every search type the deployment supports and prefers the highest one available.

Because this deployment prepares both indexes, a search_type value of "auto" uses hybrid search. Hybrid search ranks results differently from vector search, so scores from the two are not directly comparable. A min_score or max_score value that you configured for vector search can exclude results that you expect to keep.

이 클래스를 사용하도록 에이전트를 구성하는 방법을 알아보려면 에이전트 구성하기를 참조하세요.

The following table lists the methods provided by the MongoDBMemoryStore class:

메서드
설명
매개변수
반환 값

add()

이 저장소의 범위 내에 하나의 메모리를 저장합니다. 쓰기 작업은 범위, 저장소 이름 및 콘텐츠에 대해 중복 제거되므로 동일한 정보를 다시 추가해도 두 번째 문서가 생성되지 않습니다.

content: The text of the memory.
metadata: Optional key-value pairs to store with the memory.

MongoDBAddResult, which contains ids, inserted, and duplicates

search()

Returns the memories that best match a query in order of relevance. Accepts a plain string or a MongoDBSearchQuery dictionary for a per-query filter, limit, or vector.

query: The text to search for, or a MongoDBSearchQuery dictionary.
options: Optional SDK search options, such as max_search_results.

list[MemoryEntry]. Each entry's metadata includes _relevance_score, _search_type, _scope, and _id.

initialize()

Identifies which search features the deployment supports, and then creates this store's indexes. This method is called automatically by MemoryManager and by every method that reads or writes memories.

none

None

delete()

Deletes one memory, identified by the _id that a search result reports. To use this method, you must set writable to True.

memory_id: The _id value from a search result.

int, which is 1 if a document was deleted or 0 if none matched

delete_all()

Deletes every memory that this store can read. To use this method, you must set writable to True.

none

int삭제된 문서 수를 나타냅니다.

close()

Releases the connection pool for every instance that shares the same MongoDBConfig dictionary.

none

None

When you register this store with MemoryManager, the agent calls initialize(), search(), and, when you enable it, add(). You call delete(), delete_all(), and close() yourself, because the SDK's MemoryStore interface has no deletion or connection methods.

에이전트가 세션과 장기 기억 데이터를 동일한 MongoDB 배포 환경에 저장하도록 구성할 수 있습니다. 이 구성을 통해 에이전트는 실행 중에 해당 데이터를 자동으로 저장하고 검색할 수 있습니다.

To configure the agent, pass a MongoDBConfig dictionary to both the MongoDBStorage and MongoDBMemoryStore constructors, then pass the resulting instances to the Agent constructor.

다음 예제는 세션과 메모리 모두에 MongoDB를 사용하는 에이전트를 생성합니다.

from strands import Agentfrom strands.memory import MemoryManagerfrom strands.session import SnapshotSessionManagerfrom strands_mongodb import MongoDBStorage, MongoDBMemoryStore store = MongoDBMemoryStore( name="preferences", config=connection, scope="user-abc", writable=True,) agent = Agent( model=your_model, storage=MongoDBStorage(connection), session_manager=SnapshotSessionManager(session_id="support-ticket-4127"), memory_manager=MemoryManager(stores=[store], add_tool_config=True),)

다음 고려 사항이 적용됩니다.

  • To allow the agent to save memories, set the writable key to True.

  • The MemoryManager class always provides the model with a search_memory tool, but it provides an add_memory tool only when add_tool_config is set to True. If you want the model to decide when to save a memory, enable the add_tool_config parameter.

  • The add_tool_config parameter raises a ValueError if no store you pass is writable.

  • The storage parameter alone does not persist sessions. You must set session_manager to save the sessions under the specified session_id value.

MongoDBMemoryStore creates two search indexes on first use, unless you set the ensure_indexes key to False.

The MongoDB Vector Search index is named by the MongoDBConfig dictionary's vector_index_name key and has the following definition:

{ "fields": [ { "type": "autoEmbed", "path": "content", "model": "voyage-4-lite", "modality": "text" }, { "type": "filter", "path": "scope" }, { "type": "filter", "path": "store_name" } ]}

참고

By default, this MongoDB Vector Search index uses the autoEmbed type, which instructs MongoDB to generate the embeddings automatically.

The MongoDB Search index is named by the MongoDBConfig dictionary's text_index_name key and has the following definition:

{ "mappings": { "dynamic": false, "fields": { "content": [{ "type": "string" }] } }}

이러한 인덱스를 수동으로 생성하는 방법에 대한 자세한 내용은 MongoDB 벡터 검색 인덱스 생성 및 MongoDB 검색 인덱스를 참조하세요.

To supply your own vector embeddings, set the MongoDBConfig dictionary's embedding_dimensions and similarity keys. Do not set the embedding_model key. With this configuration, MongoDB indexes an embedding field as the vector type, instead of a content field as the autoEmbed type.

다음으로, 다음 방법 중 하나로 벡터를 제공하십시오.

  • Pass an embedder object to the MongoDBMemoryStore constructor, which instructs the store to embed memories and string queries

  • When calling the search() method, pass a precomputed vector in the vector key of a MongoDBSearchQuery dictionary

다음 표는 데이터베이스 사용자가 다양한 작업을 수행하는 데 필요한 권한을 설명합니다.

특권
필요한 것
필수 항목

두 수업 모두에서 모든 읽기

항상

write(), add(), delete(), and similar methods

쓰기 가능한 저장소 또는 스토리지 인스턴스의 경우 항상 그렇습니다.

Collation check that every initialize() call runs before any index

항상

인덱스 검증

항상

인덱스 생성

Only when ensure_indexes is set to True, its default value

이러한 권한을 부여하려면 스토리지 및 메모리 컬렉션에 한정된 사용자 지정 역할을 생성하십시오.

참고

By default, the initialize() and ensure_indexes() methods create the indexes the package requires if they don't already exist. Production applications often run as a user without the createIndex, createCollection, and createSearchIndexes privileges, or leave index creation to a separate deployment step. In that case, set the MongoDBConfig dictionary's ensure_indexes key to False. This instructs the package to verify the indexes instead of creating them.

MongoDB와 함께 Strands Agent를 사용하는 방법에 대한 자세한 내용은 다음 자료를 참조하십시오.