您可以将 MongoDB 与 Strands Agents 集成。 strands-mongodb 是一个用于构建 AI 代理的开源 Python SDK。 该软件包允许您使用 MongoDB 部署作为以下类的后端:
MongoDBStorage ,用于将代理会话、上下文管理和转录持久化到 MongoDB 中。
MongoDBMemoryStore可以通过语义含义、关键字或两者的组合来保存和调用事实。
开始体验
要完成配置 Strands Agents 以使用 MongoDB 的教程,请参阅 MongoDB Strands Agents 集成入门。
安装
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-mongodb:Strands 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.
from strands_mongodb.types import MongoDBConfig
connection: MongoDBConfig = { "connection_string": "<connection-string>", "database": "agents",}要了解有关查找连接字符串的更多信息,请参阅通过客户端库连接到集群。
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.
配置
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:
方法 | 说明 | 参数 | 返回值 |
|---|---|---|---|
| Stores persistent data as bytes in a key, replacing any existing value. If you set |
|
|
| 返回存储在键中的字节。 |
|
|
| 删除一个键。如果删除的键不存在,此方法不会引发错误。 |
|
|
| 返回以指定前缀开头的键名,并按升序排列。仅返回键,不返回存储的值。 |
|
|
| By default, this method ranks stored key names by how many words they share with a query. To search the stored values instead, set |
|
|
| 删除所有以指定前缀开头的键。 |
|
|
| Returns a new |
|
|
| Creates or verifies the TTL index that | 无 |
|
| Releases the connection pool for every instance that shares the same | 无 |
|
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.
MongoDB内存存储
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 specifiedscopefield 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:
方法 | 说明 | 参数 | 返回值 |
|---|---|---|---|
| 在该存储的范围内存储一条内存信息。写入操作会根据范围、存储名称和内容进行去重,因此再次添加相同的事实不会创建第二个文档。 |
|
|
| 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 | 无 |
|
| Deletes one memory, identified by the |
|
|
| Deletes every memory that this store can read. To use this method, you must set | 无 |
|
| Releases the connection pool for every instance that shares the same | 无 |
|
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
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.
搜索索引
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
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
权限
下表描述了数据库用户执行不同操作所需的权限:
特权 | 需要 | 需要 |
|---|---|---|
每次阅读,两门课程 | 始终 | |
| 始终对于可写存储或存储实例 | |
Collation check that every | 始终 | |
验证索引 | 始终 | |
创建索引 | Only when |
要授予这些权限,请创建一个作用域限定于您的存储和内存集合的自定义角色。
注意
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.
其他资源
要了解有关将 Strands Agents 与 MongoDB 结合使用的更多信息,请参阅以下资源:
链状代理商文档
strands-mongodb GitHub 仓库
strands-mongodb 在 PyPI 上