You can integrate MongoDB with Strands Agents to save an agent's conversation sessions and long-term memory in a MongoDB deployment. This tutorial uses the strands-mongodb package to persist the agent's sessions and to save and search data. Then, it runs an agent that answers a question about penguins by using the memory stored in MongoDB.
In this tutorial, you perform the following tasks:
Set up your environment.
Save penguin facts to a memory store and define a MongoDB Vector Search query that uses these facts.
Configure an agent that uses MongoDB for sessions and memory.
Run the file and review the output.
Background
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: Persists agent sessions, context management data, and transcripts in MongoDB.MongoDBMemoryStore: Saves information as memory documents in MongoDB, and searches them by meaning, by keyword, or by both.
By default, MongoDB Vector Search generates the embeddings for the memories, so you don't need an embedding model or an embedding provider API key.
Prerequisites
To complete this tutorial, you must have the following resources:
One of the following MongoDB cluster types:
An Atlas cluster running MongoDB version 6.0.11, 7.0.2, or later. Ensure that your IP address is included in your Atlas project's access list.
A local Atlas deployment created using Python and Docker. Install
atlas-local-lib-py(pip install atlas-local-lib-py) to programmatically create and manage local deployments. To learn more, see the atlas-local-lib-py repository.A MongoDB Community cluster with Search and Vector Search installed.
An OpenAI API Key. You must have an OpenAI account with credits available for API requests. To learn more about registering an OpenAI account, see the OpenAI API website.
Python v3.10 or later.
Set Up the Environment
In this section, you prepare your environment by installing the required dependencies, setting your environment variables, and creating a project file.
Install the dependencies.
From your strands-mongodb-project directory, run the following command to install the required dependencies:
uv pip install 'strands-mongodb[all]' 'strands-agents[openai]' python-dotenvThe 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.
Set your environment variables.
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.
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
Your connection string should use the following format:
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.netIMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=trueTo learn more, see Connection Strings.
Create a project file.
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()In future steps, you add code to this file to configure your MongoDB connection, save memory documents, and create an agent that accesses these documents.
Configure the Memory Store
In this section, you connect to MongoDB, save facts about penguins to a memory store, and define a MongoDB Vector Search query that uses these facts.
Configure the MongoDB connection.
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",}Share this dictionary with every class that connects to MongoDB to ensure that the classes share one connection pool.
Create a writable memory store.
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,)This code sets the following parameters:
name: Identifies the memory store. The store adds a field namedstore_nameto every memory document and sets the field's value to"penguin_facts". The store reads only the memories that hold this value.scope: Separates these memory documents from memories that other users or agents save in the same collection.writable: Allows the memory store and the agent to save memories. The default value isFalse.
Save penguin facts.
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." )Search the memory documents.
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 Vector Search generates the embeddings for each new memory document asynchronously, after the write operation completes. Until the embeddings are ready, your vector search results might be incomplete. The preceding code retries the search every five seconds, for up to five minutes, until it returns all three memories.
Configure an Agent
In this section, you configure an agent that saves its sessions in MongoDB and uses the memory store to answer questions.
Create the agent.
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,)This code passes the following parameters:
model: Uses thegpt-4omodel from OpenAI to generate agent responses.storage: Provides the backend that the agent's subsystems use to save persistent data.session_manager: Saves the conversation under the specified session ID. Thestorageparameter alone does not persist sessions.memory_manager: Provides the agent with asearch_memorytool. Setting theadd_tool_config parametertoTruealso configures theadd_memorytool for saving new memories.callback_handler: Hides the SDK's streaming output from your console.
Run a conversation turn.
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())Run the File
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?"If the command runs successfully, the output resembles the following:
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.jsonThe agent answered the question by using the documents stored in MongoDB, and it saved the conversation under the penguin-research session ID.
Next Steps
To learn more about MongoDBStorage, MongoDBMemoryStore, and their full parameter and method reference, see Integrate MongoDB with Strands Agents.
To learn more about Strands Agents, see the Strands Agents documentation.