Você pode integrar o MongoDB com os Agentes Strands., um SDK Python de código aberto para a criação de agentes de IA. O strands-mongodb Este pacote permite que você utilize uma implementação do MongoDB como backend para as seguintes classes:
O MongoDBStorage é responsável por armazenar sessões de agentes, gerenciamento de contexto e transcrições no MongoDB.
O MongoDBMemoryStore salva e recupera informações por significado semântico, palavra-chave ou uma combinação de ambos.
Começar
Para concluir o tutorial que configura os Agentes Strands para usar o MongoDB, consulte Introdução à integração dos Agentes Strands com o MongoDB.
Instalação
To install the strands-mongodb package and the dependencies for the MongoDBStorage and MongoDBMemoryStore classes, run the following command:
pip install 'strands-mongodb[all]'Este comando instala as seguintes dependências:
strands-mongodbO pacote de integração do MongoDB para agentes Strands.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.
Alternativamente, instale as dependências para classes individuais executando um dos seguintes comandos:
pip install 'strands-mongodb[storage]' # MongoDBStoragepip install 'strands-mongodb[memory]' # MongoDBMemoryStoreUso
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",}Observação
O pacote não assume a propriedade do cliente. Você é responsável por fechá-lo.
To learn more about AsyncMongoClient, see Create a MongoClient.
from strands_mongodb.types import MongoDBConfig
connection: MongoDBConfig = { "connection_string": "<connection-string>", "database": "agents",}Para saber mais sobre como encontrar sua string de conexão, consulte Conectar a um cluster via bibliotecas de cliente.
Armazenamento MongoDB
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.
Configuração
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())Para aprender como configurar um agente para usar essa classe, consulte Configurar um Agente.
Métodos
The following table lists the methods provided by the MongoDBStorage class:
Método | Descrição | Parâmetros | Valor de retorno |
|---|---|---|---|
| Stores persistent data as bytes in a key, replacing any existing value. If you set |
|
|
| Retorna os bytes armazenados em uma chave. |
|
|
| Remove uma chave. Se você excluir uma chave que não existe, este método não gera um erro. |
|
|
| Retorna os nomes das chaves que começam com um prefixo, em ordem crescente. Retorna apenas as chaves, não os valores armazenados. |
|
|
| By default, this method ranks stored key names by how many words they share with a query. To search the stored values instead, set |
|
|
| Remove todas as chaves que começam com um prefixo especificado. |
|
|
| Returns a new |
|
|
| Creates or verifies the TTL index that | none |
|
| Releases the connection pool for every instance that shares the same | 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.
MongoDBMemoryStore
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.
Para usar a Pesquisa Vetorial do MongoDB, o MongoDB compara os vetores de incorporação dos seus dados com a incorporação da consulta. Por padrão, o MongoDB gera essas incorporações automaticamente, portanto, você não precisa gerenciar vetores ou chaves de API do provedor de incorporação.
This section describes how to configure and use the methods provided by the MongoDBMemoryStore class.
Configuração
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 specifiedscopefield value. The example uses the scope"user-abc".writablePermite operações de escrita no armazenamento em memória.
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())Tipos de pesquisa
MongoDBMemoryStore Utiliza os seguintes tipos de pesquisa para responder a uma consulta:
Busca vetorial, que realiza correspondências por significado.
Pesquisa de texto, que encontra correspondência por palavra-chave.
Busca híbrida, que combina os dois tipos de busca.
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.
Para aprender como configurar um agente para usar essa classe, consulte Configurar um Agente.
Métodos
The following table lists the methods provided by the MongoDBMemoryStore class:
Método | Descrição | Parâmetros | Valor de retorno |
|---|---|---|---|
| Armazena uma única informação na memória dentro do escopo deste armazenamento. As gravações são desduplicadas com base no escopo, nome do armazenamento e conteúdo; portanto, adicionar o mesmo fato novamente não cria um segundo documento. |
|
|
| Returns the memories that best match a query in order of relevance. Accepts a plain string or a |
|
|
| Identifies which search features the deployment supports, and then creates this store's indexes. This method is called automatically by | none |
|
| Deletes one memory, identified by the |
|
|
| Deletes every memory that this store can read. To use this method, you must set | none |
|
| Releases the connection pool for every instance that shares the same | 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.
Configurar um agente
Você pode configurar um agente para armazenar suas sessões e memória de longo prazo na mesma implementação do MongoDB. Essa configuração permite que o agente salve e recupere esses dados automaticamente durante a execução.
To configure the agent, pass a MongoDBConfig dictionary to both the MongoDBStorage and MongoDBMemoryStore constructors, then pass the resulting instances to the Agent constructor.
O exemplo a seguir cria um agente que usa o MongoDB tanto para sessões quanto para memória:
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),)As seguintes considerações se aplicam:
To allow the agent to save memories, set the
writablekey toTrue.The
MemoryManagerclass always provides the model with asearch_memorytool, but it provides anadd_memorytool only whenadd_tool_configis set toTrue. If you want the model to decide when to save a memory, enable theadd_tool_configparameter.The
add_tool_configparameter raises aValueErrorif no store you pass is writable.The
storageparameter alone does not persist sessions. You must setsession_managerto save the sessions under the specifiedsession_idvalue.
Índices de pesquisa
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" } ]}Observação
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" }] } }}Para saber mais sobre como criar esses índices manualmente, consulte Criar um índice de pesquisa vetorial do MongoDB e Índice de pesquisa do MongoDB.
Incorporação manual
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.
Em seguida, forneça os vetores de uma das seguintes maneiras:
Pass an
embedderobject to theMongoDBMemoryStoreconstructor, which instructs the store to embed memories and string queriesWhen calling the
search()method, pass a precomputed vector in thevectorkey of aMongoDBSearchQuerydictionary
Permissões
A tabela a seguir descreve os privilégios que seu usuário de banco de dados precisa para realizar diferentes ações:
Privilégio | Necessário para | Necessário quando |
|---|---|---|
Todas as leituras, em ambas as turmas. | Sempre | |
| Sempre, para uma instância de armazenamento ou armazenamento gravável. | |
Collation check that every | Sempre | |
Verificação de índices | Sempre | |
Criação de índices | Only when |
Para conceder esses privilégios, crie uma função personalizada com escopo definido para suas coleções de armazenamento e memória.
Observação
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.
Recursos adicionais
Para saber mais sobre como usar os Agentes Strands com o MongoDB, consulte os seguintes recursos:
Agentes Strands documentação
fios-mongodb Repositório GitHub
fios-mongodb no PyPI