对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

开始使用 MongoDB Strands Agents 集成

您可以将 MongoDB 与 Strands Agents 集成,以便将代理的对话会话和长期记忆保存在 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 集群类型之一:

    • 运行 MongoDB 6.0.11 版本的 Atlas 集群,7.0.2或以上版本。确保您的 IP 地址 包含在 Atlas 项目的 访问列表 中。

    • 使用 Python 和 Docker 创建的本地 Atlas 部署。安装 atlas-local-lib-py (pip install atlas-local-lib-py),以编程方式创建和管理本地部署。要了解更多信息,请参阅 atlas-local-lib-py 存储库。

    • 安装了Search 和向量搜索的 MongoDB Community 集群。

  • 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 集群或本地部署的连接字符串。

连接字符串应使用以下格式:

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 向量搜索会在写入操作完成后异步生成每个新内存文档的嵌入向量。在嵌入向量生成之前,您的向量搜索结果可能不完整。前面的代码会每隔五秒重试一次搜索,最多持续五分钟,直到返回所有三个内存文档。

在本节中,您将配置一个代理,该代理将其会话保存在 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_handler:隐藏 SDK 的流式输出,使其不显示在控制台中。

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 文档。