您可以将MongoDB Atlas与 LangGraph 集成以构建AI代理。本教程演示如何构建AI代理来回答有关MongoDB中示例数据的问题。
具体来说,代理使用该集成来实现代理 RAG和代理内存。它使用语义搜索和全文搜索工具来检索相关信息并回答有关数据的问题。它还通过将对话历史记录和重要交互存储在单独的集合中,使用MongoDB实现短期和长期记忆。
先决条件
如要完成本教程,您必须具备以下条件:
以下MongoDB 集群类型之一:
使用 Python 和 Docker 创建的本地 Atlas 部署。安装
atlas-local-lib-py(pip install atlas-local-lib-py),以编程方式创建和管理本地部署。要了解更多信息,请参阅 atlas-local-lib-py 存储库。安装了Search 和向量搜索的 MongoDB Community 集群。
Voyage AI API密钥。要学习;了解更多信息,请参阅API密钥和Python客户端。
OpenAI API密钥。您必须拥有一个具有可用于API请求的积分的 OpenAI 帐户。要学习;了解有关注册 OpenAI 帐户的更多信息,请参阅 OpenAI API网站。
注意
检查 langchain-voyageai 包的要求,确保您使用兼容的Python版本。
设置环境
要设置环境,请完成以下步骤:
初始化项目并安装依赖项。
创建一个新的项目目录,然后安装所需的依赖项:
mkdir langgraph-mongodb-ai-agent cd langgraph-mongodb-ai-agent pip install --quiet --upgrade python-dotenv langgraph "langgraph-checkpoint-mongodb>=0.5.0" "langgraph-store-mongodb>=0.3.0" 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
设置环境变量。
在项目中创建一个 .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作为向量数据库
要将MongoDB配置为向量数据库以进行存储和检索,请完成以下步骤:
加载示例数据。
在本教程中,您将使用我们的一个示例数据集作为数据源。如果还没有,请完成将示例数据加载到Atlas 集群的步骤。
具体而言,您将使用 embedded_movies 数据集,该数据集包含有关电影的文档,包括其情节的向量嵌入。
注意
如果您想使用自己的数据,请参阅LangChain 入门或如何手动创建vector embeddings,学习如何将vector embeddings引入Atlas。
定义搜索工具
在项目中创建 search_tools.py文件。在此文件中,您可以定义代理用于执行代理 RAG的搜索工具。
定义内存工具
在项目中创建 memory_tools.py文件。在此文件中,您可以定义代理用于存储和检索跨会话的重要交互以实现长期记忆的工具。
构建具有持久性的代理
在项目中创建 agent.py文件。在此文件中,您构建用于协调代理工作流程的图表。该代理使用MongoDB Checkpointer 组件来实现短期记忆,允许具有单独历史记录的多个并发对话。
该代理使用以下工作流程来响应查询:
启动:代理接收用户查询。
代理节点:工具绑定的 LLM 会分析查询并确定是否需要工具。
工具节点(如果需要):执行相应的搜索或内存工具。
End:LLM 使用工具的输出生成最终响应。
运行代理
最后,在项目中创建一个名为 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.