Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/
Atlas
/ /

将MongoDB与 CrewAI 集成

您可以将MongoDB与 CrewAI 集成,以构建具有专门角色、工具和任务的自主AI代理和多代理应用程序。具体来说,您可以利用适用于 CrewAI 的MongoDB Vector Search 工具,启用团队中的AI助手从数据中检索相关信息,帮助完成任务。

要完成使用 CrewAI 和MongoDB 的教程,请参阅使用 CrewAI 和MongoDB构建代理 RAG 应用程序。

要安装适用于 CrewAI 的MongoDB Vector Search 工具,请根据您的Python包管理器运行以下命令之一:

pip install 'crewai-tools[mongodb]'
uv add crewai-tools --extra mongodb

注意

Python版本兼容性可能与 CrewAI 官方文档不同。在撰写本文时,crewai-tools包依赖于 embedchain,这需要介于 3.9 和 3.13.2 之间的Python版本(含)。

要使用MongoDB Vector Search Tool,请对其进行初始化,然后将其传递给代理。

要初始化该工具,您必须指定以下内容:

from crewai_tools import MongoDBVectorSearchTool
tool = MongoDBVectorSearchTool(
connection_string="<connection-string>",
database_name="<database-name>",
collection_name="<collection-name>",
# Other optional parameters...
)
# To test the tool
print(tool.run(query="<test-query>"))
# To use the tool in an agent
rag_agent = Agent(
name="rag_agent",
role="You are a helpful assistant that can answer questions with the help of the MongoDBVectorSearchTool.",
goal="...",
backstory="...",
tools=[tool],
)

(可选)您可以通过为工具的构造函数指定 MongoDBVectorSearchConfig 的实例来自定义工具的向量搜索查询。

要了解有关向量搜索查询的更多信息,请参阅运行向量搜索查询

from crewai_tools import MongoDBVectorSearchConfig, MongoDBVectorSearchTool
# Custom query configuration
query_config = MongoDBVectorSearchConfig(
limit = 10,
oversampling_factor = 2,
)
tool = MongoDBVectorSearchTool(
database_name="example_database",
collection_name="example_collection",
connection_string="<connection_string>",
query_config=query_config,
# Other optional parameters...
)
# To test the tool
print(tool.run(query="<test-query>"))
# To use the tool in an agent
rag_agent = Agent(
name="rag_agent",
role="You are a helpful assistant that can answer questions with the help of the MongoDBVectorSearchTool.",
goal="...",
backstory="...",
tools=[tool],
)

提示

MongoDBVectorSearchTool 类提供以下方法:

  • add_texts():将文本文档添加到指定的MongoDB集合。

  • create_vector_search_index():在集合上创建向量搜索索引。

  • run():对数据运行向量搜索查询。

import os
from crewai_tools import MongoDBVectorSearchTool
tool = MongoDBVectorSearchTool(
connection_string="<connection-string>",
database_name="<database-name>",
collection_name="<collection-name>"
)
# Example of loading text content from a local folder
texts = []
for fname in os.listdir("knowledge"):
path = os.path.join("knowledge", fname)
if os.path.isfile(path):
with open(path, "r", encoding="utf-8") as f:
texts.append(f.read())
# Method to add documents to the vector store
tool.add_texts(texts)
# Method to create the vector search index
tool.create_vector_search_index(dimensions=<number-of-dimensions>)
# Method to test the tool by running a vector search query
tool.run(query="<search-query>")

后退

构建 AI 代理

在此页面上