Docs 菜单
Docs 主页
/
Atlas
/ /

将 MongoDB 与 LangGraph 集成

您可以将MongoDB与 LangGraph 集成,以构建AI代理和高级 RAG 应用程序。本页概述了MongoDB LangGraph 集成,以及如何在 LangGraph 工作流程中使用MongoDB来实现代理状态持久化、内存和检索。

要构建使用本页上所有组件的示例AI代理,请参阅 教程。

注意

有关 JavaScript 集成,请参阅 LangGraph JS/TS

LangGraph 是 LangChain 生态系统中的一个专用框架,旨在构建 AI 代理和复杂的多代理工作流程。图表是 LangGraph 的核心组件,代表了代理的工作流程。MongoDB LangGraph 集成支持以下功能:

  • MongoDB LangGraph Checkpointer:您可以在MongoDB中持久保存 LangGraph 代理的状态,从而提供短期记忆

  • MongoDB LangGraph Store:您可以在MongoDB集合中存储和检索LangGraph 代理的重要记忆,从而提供长期记忆

  • 检索工具:您可以使用 MongoDB LangChain 集成快速为您的 LangGraph 工作流创建检索工具。

通过将 LangGraph 应用程序与MongoDB集成,您可以将检索功能和代理内存整合到单个数据库中,从而简化架构并降低操作复杂性。

MongoDB LangGraph Checkpointer 允许您将代理的状态保留在MongoDB中,以实现短期记忆。此功能可为 LangGraph 代理启用人机交互、内存、时间旅行和容错功能。

要安装此组件的包:

pip install langgraph-checkpoint-mongodb
from langgraph.checkpoint.mongodb import MongoDBSaver
from pymongo import MongoClient
# Connect to your MongoDB cluster
client = MongoClient("<connection-string>")
# Initialize the MongoDB checkpointer
checkpointer = MongoDBSaver(client)
# Instantiate the graph with the checkpointer
app = graph.compile(checkpointer=checkpointer)

The MongoDB LangGraph Store 允许您在MongoDB集合中存储和检索内存,从而为您的 LangGraph 代理启用长期内存。这使您能够构建可以记住过去交互的代理,并使用该信息为未来的决策提供信息。

要安装此组件的包:

pip install langgraph-store-mongodb
from langgraph.store.mongodb import MongoDBStore, create_vector_index_config
from langchain_voyageai import VoyageAIEmbeddings
# Optional vector search index configuration for the memory collection
index_config = create_vector_index_config(
embed = VoyageAIEmbeddings(),
dims = <dimensions>,
fields = ["<field-name>"],
filters = ["<filter-field-name>", ...] # Optional list of fields that can filtered during search
# Other fields...
)
# Store memories in MongoDB collection
with MongoDBStore.from_conn_string(
conn_string=MONGODB_URI,
db_name="<database-name>",
collection_name="<collection-name>",
index_config=index_config # If specified, automatically embeds and indexes the field value
) as store:
store.put(
namespace=("user", "memories"), # Namespace for the memories
key=f"memory_{hash(content)}", # Unique identifier for each memory
value={"content": content} # Document data that contains the memory content
)
# Retrieve memories from MongoDB collection
with MongoDBStore.from_conn_string(
conn_string=MONGODB_URI,
db_name="<database-name>",
collection_name="<collection-name>",
index_config=index_config # If specified, uses vector search to retrieve memories. Otherwise, uses metadata filtering
) as store:
results = store.search(
("user", "memories"),
query="<query-text">,
limit=3
)
for result in results:
print(result.value)
# To delete memories, use store.delete(namespace, key)
# To batch operations, use store.batch(ops)
方法
说明

put(namespace, key, value, *, index)

使用指定的命名空间、键和值将单个项目存储在存储中。

search(namespace_prefix, /, *, ...)

搜索给定 namespace_prefix 内的项目。如果配置了向量索引,则支持基本键值筛选和语义查询搜索。

search 方法具有以下模式:

  • 元数据筛选(无查询):在不带查询参数的情况下调用时,它会执行标准MongoDB筛选查询。您可以指定一个过滤字典来匹配储值文档中的字段。

    例如: store.search(("docs",), filter={"author": "Bob", "status": "published"})

  • 语义搜索(带查询):如果存储使用 index_config 进行初始化并且提供了查询字符串,则会执行语义搜索。该方法会嵌入查询文本,并使用MongoDB Vector Search 来查找最相关的项目。

    例如: store.search(("docs",), query="information about AI assistants")

get(namespace, key, *, refresh_ttl)

从存储中检索单个项目。或者,您可以在访问权限时刷新项目的TTL 。

delete(namespace, key)

从由其命名空间和键标识的存储中删除单个项目。

list_namespaces(*, prefix, ...)

列出存储中的唯一命名空间。允许按路径前缀、后缀和文档深度进行过滤。

batch(ops)

在单个批处理中执行一系列操作(GetOpPutOpSearchOpDeleteOp)。首先执行读取操作,然后批量应用程序去重写入操作。abatch(ops) 是此方法的异步版本。

ensure_index_filters(filters)

为MongoDB Vector Search索引准备过滤字段列表的方法。

您可以无缝地将 LangChain 检索器用作 LangGraph 工作流程中的工具,以从MongoDB检索相关数据。

MongoDB LangChain 集成原生支持全文搜索、向量搜索、混合搜索和父文档检索。有关检索方法的完整列表,请参阅MongoDB LangChain 检索器。

  1. 要使用MongoDB Vector Search 和 LangChain 创建基本检索工具,请执行以下操作:

    from langchain.tools.retriever import create_retriever_tool
    from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
    from langchain_voyageai import VoyageAIEmbeddings
    # Instantiate the vector store
    vector_store = MongoDBAtlasVectorSearch.from_connection_string(
    connection_string = "<connection-string>", # MongoDB cluster URI
    namespace = "<database-name>.<collection-name>", # Database and collection name
    embedding = VoyageAIEmbeddings(), # Embedding model to use
    index_name = "vector_index", # Name of the vector search index
    # Other optional parameters...
    )
    # Create a retrieval tool
    retriever = vector_store.as_retriever()
    retriever_tool = create_retriever_tool(
    retriever,
    "vector_search_retriever", # Tool name
    "Retrieve relevant documents from the collection" # Tool description
    )
  2. 要在 LangGraph 中添加工具作为节点,请执行以下操作:

    1. 将工具转换为节点。

    2. 将节点添加到图中。

    from langgraph.graph import StateGraph
    from langgraph.prebuilt import ToolNode
    # Define the graph
    workflow = StateGraph()
    # Convert the retriever tool into a node
    retriever_node = ToolNode([retriever_tool])
    # Add the tool as a node in the graph
    workflow.add_node("vector_search_retriever", retriever_node)
    graph = workflow.compile()

后退

Spring AI

获得技能徽章

免费掌握“Gen AI”!

了解详情

在此页面上