本教程演示如何使用 n8n 快速构建AI代理,以回答有关某些示例数据的问题。该代理利用MongoDB作为用于文档检索的向量存储和用于会话持久性的聊天内存存储。
关于MongoDB的 n8n 工作流
以下屏幕截图演示了您将在本教程中构建的工作流程。在此工作流中,您将创建一个使用两个MongoDB节点的AI代理:
MongoDB Atlas Vector Store Node,用于从示例数据中检索相关文档
用于存储对话历史记录的MongoDB聊天内存节点
它还使用 OpenAI 作为 LLM 和嵌入模型提供商。
当您向代理发送消息时,会触发以下操作:
AI代理节点处理用户消息并确定下一步动作。
AI代理检查是否需要调用任何工具。
如果是,则调用MongoDB Vector Store节点来检索文档。
如果没有,则继续执行下一个动作。
代理使用您为工作流程配置的 LLM 生成响应。
每次交互后, MongoDB聊天内存节点都会存储对话历史记录。

注意
AI助手节点配置中的红色星号表示所需参数。
先决条件
在开始之前,请确保您具备以下内容:
以下MongoDB 集群类型之一:
使用 Python 和 Docker 创建的本地 Atlas 部署。安装
atlas-local-lib-py(pip install atlas-local-lib-py),以编程方式创建和管理本地部署。要了解更多信息,请参阅 atlas-local-lib-py 存储库。A MongoDB Community cluster with Search and Vector Search installed.
示例数据已加载到MongoDB 部署中。
OpenAI API密钥,或您打算使用的任何其他受支持的 LLM 和嵌入模型提供商的API密钥。
Considerations
使用 n8n 和MongoDB时,请考虑以下事项:
对于MongoDB Atlas用户,请确保将您的 n8n 个IP地址添加到项目的IP访问列表中。要学习;了解更多信息,请参阅网络访问。
配置MongoDB Vector Store节点时,请确保将 Include Metadata 切换为 Off。如果您不将此设置切换为 Off,则AI代理可能不会运行,因为文档可能太大而无法加载到上下文窗口中。
创建向量搜索索引
You must create a vector search index on your collection before you can use the MongoDB vector store node.
To use a different index creation method, follow the steps in the index creation procedure. Use the following configuration:
{ "fields": [ { "type": "vector", "path": "plot_embedding", "numDimensions": 1536, "similarity": "dotProduct" } ] }
在 n8n 中配置档案
在本部分中,您将完成 n8n 中配置所需凭证的步骤。
为模型提供商添加凭证。
从下拉菜单中,选择要配置的凭证。
示例,选择 OpenAI 并单击 Continue。
要查看为模型提供商输入哪些参数,请检查凭证库。
示例,对于 OpenAI,输入API密钥、组织名称和基本URL。
单击 Save。n8n 将档案添加到您的个人空间。
为MongoDB添加凭证。
按照上一步所述相同说明将MongoDB凭证添加到 n8n。指定以下值:
设置 | 值 |
|---|---|
配置类型 | 在下拉菜单中,选择 Connection String 方法。 |
连接字符串 | 输入您的MongoDB Connection String。 To learn how to find your MongoDB connection string, see Connection Strings. |
Database | 输入 sample_mflix。 |
配置AI助手工作流程
Complete the following steps in n8n to build an AI agent workflow with MongoDB and n8n. To learn more about the workflow, see About the n8n Workflow with MongoDB.
添加MongoDB聊天内存子节点。
配置MongoDB聊天内存子节点以启用持久对话上下文。
单击AI代理节点上 Memory 标签旁边的 +Connector。
从侧面板中选择 MongoDB Chat Memory。
单击 Select credential,然后选择您的MongoDB凭证。
使用MongoDB聊天内存节点的默认配置。默认下,n8n 在指定数据库中创建一个名为
n8n_chat_histories的集合。点击屏幕左上角的 Back to canvas。在此阶段,您可以跳过此节点的测试。单击 Save。
单击AI助手图标返回AI助手节点配置。
添加MongoDB Atlas Vector Store节点作为工具。
配置MongoDB Atlas Vector Store节点以启用文档检索。
单击AI代理节点上 Tool 标签旁边的 +Connector。
在搜索面板中,选择 MongoDB Atlas Vector Store。
选择您配置的MongoDB凭证,然后指定以下值:
设置值Operation Mode
Retrieve Documents (As Tool for AI Agent)
Description
"Search through documents about movies to find relevant information"MongoDB Collection
embedded_moviesEmbedding
plot_embeddingMetadata Field
plotVector Index Name
vector_indexLimit
4Include Metadata
切换到 Off
重要提示:
如果不将此设置切换为 Off,则AI代理可能不会运行,因为文档可能太大而无法加载到上下文窗口中。
Rerank Results
切换到 Off