您可以将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 toolprint(tool.run(query="<test-query>"))
# To use the tool in an agentrag_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 的实例来自定义工具的向量搜索查询。
要了解有关向量搜索查询的更多信息,请参阅运行向量搜索近似最近邻 (ANN) 和精确最近邻 (ENN) 查询。
from crewai_tools import MongoDBVectorSearchConfig, MongoDBVectorSearchTool
# Custom query configurationquery_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 toolprint(tool.run(query="<test-query>"))
# To use the tool in an agentrag_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 osfrom 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 foldertexts = []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 storetool.add_texts(texts)
# Method to create the vector search indextool.create_vector_search_index(dimensions=<number-of-dimensions>)
# Method to test the tool by running a vector search querytool.run(query="<search-query>")