MongoDB.local SF, Jan 15: See the speaker lineup & ship your AI vision faster. Use WEB50 to save 50%
Find out more >
Docs 菜单
Docs 主页
/ /

使用 LangGraph 和MongoDB Atlas构建AI助手

您可以将MongoDB Atlas与 LangGraph 集成以构建AI代理。本教程演示如何构建AI代理来回答有关MongoDB中示例数据的问题。

具体来说,代理使用该集成来实现代理 RAG代理内存。它使用语义搜索和全文搜索工具来检索相关信息并回答有关数据的问题。它还通过将对话历史记录和重要交互存储在单独的集合中,使用MongoDB实现短期和长期记忆。

本页上的代码构建了一个完整的示例应用程序。如果您希望逐步学习;了解,还可以将代码作为 Python笔记本 来学习。

如要完成本教程,您必须具备以下条件:

  • 以下MongoDB 集群类型之一:

    • 运行MongoDB 版本的Atlas6.0.11 集群,7.0.2 或更高版本。确保您的 IP解决 包含在Atlas项目的 访问权限列表 中。

    • 使用Atlas CLI创建的本地Atlas部署。要学习;了解更多信息,请参阅创建本地Atlas部署。

    • 安装了Search 和 Vector Search的MongoDB Community或 Enterprise集群。

  • Voyage AI API密钥。要学习;了解更多信息,请参阅API密钥和Python客户端。

  • OpenAI API密钥。您必须拥有一个具有可用于API请求的积分的 OpenAI 帐户。要学习;了解有关注册 OpenAI 帐户的更多信息,请参阅 OpenAI API网站。

注意

检查 langchain-voyageai 包的要求,确保您使用兼容的Python版本。

要设置环境,请完成以下步骤:

1

创建一个新的项目目录,然后安装所需的依赖项:

mkdir langgraph-mongodb-ai-agent
cd langgraph-mongodb-ai-agent
pip install --quiet --upgrade python-dotenv langgraph langgraph-checkpoint-mongodb langgraph-store-mongodb langchain langchain-mongodb langchain-voyageai langchain-openai pymongo

注意

您的项目将使用以下结构:

langgraph-mongodb-ai-agent
├── .env
├── config.py
├── search-tools.py
├── memory-tools.py
├── agent.py
├── main.py
2

在项目中创建 .env文件并指定以下变量。将占位符值替换为有效的API密钥和MongoDB集群的连接字符串。

VOYAGE_API_KEY = "<voyage-api-key>"
OPENAI_API_KEY = "<openai-api-key>"
MONGODB_URI = "<connection-string>"

注意

<connection-string> 替换为您的 Atlas 集群或本地部署的连接字符串。

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

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

要学习;了解更多信息,请参阅通过驱动程序连接到集群。

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

mongodb://localhost:<port-number>/?directConnection=true

要学习;了解更多信息,请参阅连接字符串。

要将MongoDB配置为向量数据库以进行存储和检索,请完成以下步骤:

1

在本教程中,您将使用我们的一个示例数据集作为数据源。如果还没有,请完成将示例数据加载到Atlas 集群的步骤。

具体而言,您将使用 embedded_movies 数据集,该数据集包含有关电影的文档,包括其情节的向量嵌入。

注意

如果您想使用自己的数据,请参阅 LangChain 入门如何创建向量嵌入,以了解如何将向量嵌入导入 Atlas。

2

在项目中创建一个名为 config.py 的文件。此文件将MongoDB配置为代理的向量存储。它还创建索引以启用对示例数据的向量搜索和全文搜索查询。

在项目中创建 search_tools.py文件。在此文件中,您可以定义代理用于执行代理 RAG的搜索工具。

注意

您可以定义执行特定任务所需的任何工具。您还可以为混合搜索父文档检索等其他检索方法定义工具。

在项目中创建 memory_tools.py文件。在此文件中,您可以定义代理用于存储和检索跨会话的重要交互以实现长期记忆的工具。

在项目中创建 agent.py文件。在此文件中,您构建用于协调代理工作流程的图表。该代理使用MongoDB Checkpointer 组件来实现短期记忆,允许具有单独历史记录的多个并发对话。

该代理使用以下工作流程来响应查询:

  1. 启动:代理接收用户查询。

  2. 代理节点:工具绑定的 LLM 会分析查询并确定是否需要工具。

  3. 工具节点(如果需要):执行相应的搜索或内存工具。

  4. End:LLM 使用工具的输出生成最终响应。

展示 LangGraph-MongoDB 代理工作流程的图表。
点击放大

提示

要学习;了解有关持久性、短期记忆和MongoDB检查点的更多信息,请参阅以下资源:

最后,在项目中创建一个名为 main.py 的文件。此文件运行代理并允许您与其交互。

保存项目,然后运行以下命令。当您运行代理时:

  • 代理会初始化向量存储并创建索引(如果尚不存在)。

  • 您可以输入会话ID来启动新会话或继续现有会话。每个会话都是持久的,您可以随时恢复之前的对话。

  • 询问有关电影的问题。该代理会根据您的工具和之前的交互生成响应。

以下输出演示了一个示例交互:

python main.py
Creating vector search index...
Vector search index created successfully!
Creating search index...
Search index created successfully!
Enter a session ID: 123
Ask me about movies! Type 'quit' to exit.
Your query: What are some movies that take place in the ocean?
🔧 Agent chose to use tool(s): plot_search
→ Executing plot_search
Answer: Here are some movies that take place in the ocean:
1. **20,000 Leagues Under the Sea** - A marine biologist, his daughter, and a mysterious Captain Nemo explore the ocean aboard an incredible submarine.
2. **Deep Rising** - A group of armed hijackers board a luxury ocean liner in the South Pacific Ocean, only to fight man-eating, tentacled sea creatures.
... (truncated)
Your query: What is the plot of the Titanic?
🔧 Agent chose to use tool(s): title_search
→ Executing title_search
Answer: The plot of *Titanic* involves the romantic entanglements of two couples aboard the doomed ship's maiden voyage
... (truncated)
Your query: What movies are like the movie I just mentioned?
🔧 Agent chose to use tool(s): plot_search
→ Executing plot_search
Answer: Here are some movies similar to *Titanic*:
1. **The Poseidon Adventure** - A group of passengers struggles to survive when their ocean liner capsizes at sea.
2. **Pearl Harbor** - Focused on romance and friendship amidst the backdrop of a historical tragedy, following two best friends and their love lives during wartime.
... (truncated)
Your query: I don't like sad movies.
🔧 Agent chose to use tool(s): save_memory
→ Executing save_memory
Answer: Got it—I'll keep that in mind. Let me know if you'd like recommendations that focus more on uplifting or happy themes!
(In different session)
Enter a session ID: 456
Your query: Recommend me a movie based on what you know about me.
🔧 Agent chose to use tool(s): retrieve_memories
→ Executing retrieve_memories
Answer: Based on what I know about you—you don't like sad movies—I'd recommend a fun, uplifting, or action-packed film. Would you be interested in a comedy, adventure, or family-friendly movie?
Your query: Sure!
🔧 Agent chose to use tool(s): plot_search, plot_search, plot_search
→ Executing plot_search
→ Executing plot_search
→ Executing plot_search
Answer: Here are some movie recommendations from various uplifting genres that suit your preferences:
### Comedy:
1. **Showtime** (2002): A spoof of buddy cop movies where two very different cops are forced to team up on a new reality-based TV cop show. It's packed with laughs and action!
2. **The Big Bus** (1976): A hilarious disaster film parody featuring a nuclear-powered bus going nonstop from New York to Denver, plagued by absurd disasters.
### Adventure:
1. **Journey to the Center of the Earth** (2008): A scientist, his nephew, and their mountain guide discover a fantastic and dangerous lost world at the earth's core.
2. **Jason and the Argonauts** (1963): One of the most legendary adventures in mythology, brought to life in this epic saga of good versus evil.
### Family-Friendly:
1. **The Incredibles** (2004): A family of undercover superheroes is forced into action to save the world while living in quiet suburban life.
2. **Mary Poppins** (1964): A magical nanny brings joy and transformation to a cold banker's unhappy family.
3. **Chitty Chitty Bang Bang** (1968): A whimsical adventure featuring an inventor, his magical car, and a rescue mission filled with fantasy.

后退

LangGraph

获得技能徽章

免费掌握“Gen AI”!

了解详情

在此页面上