AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

MongoDBと Lgachein の統合

MongoDB をLgChuin と統合して、生成系AIと RAG アプリケーションを構築できます。このページでは、LgChuin MongoDB Python統合とアプリケーションで使用できるさまざまなコンポーネントの概要について説明します。

はじめる

注意

コンポーネントとメソッドの完全なリストについては、API参照 を参照してください。

JavaScript 統合については、LangChain JS/TS をご覧ください。

LgChuin でMongoDB ベクトル検索を使用するには、まず langchain-mongodbパッケージをインストールする必要があります。

pip install langchain-mongodb

MongoDBAtlasVectorSearch は、 MongoDBのコレクションからベクトル埋め込みを保存および検索できるベクトルストアです。このコンポーネントを使用してデータの埋め込みを保存し、 MongoDB ベクトル検索を使用して埋め込みを検索できます。

このコンポーネントにはMongoDB ベクトル検索インデックスが必要です。

Atlas は 2 つの埋め込みモードをサポートしています。

  • 手動埋め込み: 指定した埋め込みモデルを使用して、クライアント側で埋め込みベクトルを生成します。

  • 自動埋め込み: MongoDB は、手動で生成する必要なく、サーバー側にテキストを埋め込みます。「 自動埋め込み 」を参照してください。「自動埋め込み」を参照してください。

ベクトルストアをインスタンス化する最も簡単な方法は、 MongoDBクラスターまたはローカル配置の接続文字列を使用することです。

from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearchfrom langchain_voyageai import VoyageAIEmbeddings # Instantiate the vector store using your MongoDB connection stringvector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string="<connection-string>", # MongoDB cluster URI namespace="<database-name>.<collection-name>", # Database and collection name embedding=VoyageAIEmbeddings(model="voyage-3-large"), # Embedding model to use index_name="vector_index", # Name of the vector search index # Other optional parameters...)

LangChain 検索 は、ベクトルストアから関連するドキュメントを取得するために使用するコンポーネントです。LgChuin に組み込まれている検索ドライバーまたは次のMongoDB検索ドライバーを使用して、 MongoDBからデータをクエリして検索できます。

MongoDB をベクトルストアとしてインスタンス化したら、ベクトルストアのインスタンスを検索用に使用して、MongoDB ベクトル検索を使用してデータをクエリできます。

from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearchfrom langchain_voyageai import VoyageAIEmbeddings # Instantiate the vector storevector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string="<connection-string>", # MongoDB cluster URI namespace="<database-name>.<collection-name>", # Database and collection name embedding=VoyageAIEmbeddings(model="voyage-3-large"), # Embedding model to use index_name="vector_index", # Name of the vector search index) # Use the vector store as a retrieverretriever = vector_store.as_retriever() # Define your queryquery = "some search query" # Print resultsdocuments = retriever.invoke(query)for doc in documents: print(doc)

MongoDBAtlasFullTextSearchRetriever は、MongoDB Search を使用して全文検索を実行する検索システムです。具体的には、Lucene の標準 BM25 アルゴリズムを使用します。

この検索インデックスにはMongoDB Search インデックスが必要です。

from langchain_mongodb.retrievers.full_text_search import ( MongoDBAtlasFullTextSearchRetriever,)from pymongo import MongoClient # Connect to your MongoDB clusterclient = MongoClient("<connection-string>")collection = client["<database-name>"]["<collection-name>"] # Initialize the retrieverretriever = MongoDBAtlasFullTextSearchRetriever( collection=collection, # MongoDB Collection in Atlas search_field="<field-name>", # Name of the field to search search_index_name="<index-name>", # Name of the search index) # Define your queryquery = "some search query" # Print resultsdocuments = retriever.invoke(query)for doc in documents: print(doc)

MongoDBAtlasHybridSearchRetriever は、 レプリカ ランク統合(RRF)アルゴリズムを使用して、ベクトル検索と全文検索の結果を組み合わせた検索結果です。「ハイブリッド検索の実行方法」を参照してください。

この検索インデックスには、既存のベクトルストア、MongoDB ベクトル検索インデックス、およびMongoDB Search インデックスが必要です。

from langchain_mongodb.retrievers.hybrid_search import ( MongoDBAtlasHybridSearchRetriever,)from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearchfrom langchain_voyageai import VoyageAIEmbeddings # Instantiate the vector storevector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string="<connection-string>", # MongoDB cluster URI namespace="<database-name>.<collection-name>", # Database and collection name embedding=VoyageAIEmbeddings(model="voyage-3-large"), # Embedding model to use index_name="vector_index", # Name of the vector search index) # Initialize the retrieverretriever = MongoDBAtlasHybridSearchRetriever( vectorstore=vector_store, # Vector store instance search_index_name="<index-name>", # Name of the MongoDB Search index top_k=5, # Number of documents to return fulltext_penalty=60.0, # Penalty for full-text search vector_penalty=60.0, # Penalty for vector search) # Define your queryquery = "some search query" # Print resultsdocuments = retriever.invoke(query)for doc in documents: print(doc)

MongoDBAtlasParentDocumentRetriever は、最初に小さなチャンクをクエリし、その後、大きな親ドキュメントを LLM に返す検索システムです。このタイプの検索システムは、親ドキュメント検索と呼ばれます。親ドキュメント検索により、より小さなチャンクでのより詳細な検索が可能になり、同時に LLM に親ドキュメントの完全なコンテキストが提供されるため、RAG エージェントとアプリケーションの応答が向上します。

このレトリーバーは、親ドキュメントと子ドキュメントの両方を 1 つの MongoDB コレクションに保存できるため、子ドキュメントの埋め込みを計算してインデックスを作成するだけで効率的な検索が可能になります。

内部的には、このレトリーバーは以下を作成します。

  • 子ドキュメントに対するベクトル検索クエリを取り扱う MongoDBAtlasVectorSearch のインスタンス。

  • 親ドキュメントの保存と検索を取り扱う MongoDBDocStore のインスタンス。

ベクトルストアと親ドキュメントストアがドキュメントテキストに同じフィールド名を使用するように、text_key を page_content に設定します。このパラメータがないと、リトリーバーは親ドキュメントをあるフィールドに書き込み、別のフィールドから書き込み (write)ため、クエリは KeyError: 'text' で失敗します。

from langchain_mongodb.retrievers import MongoDBAtlasParentDocumentRetrieverfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_voyageai import VoyageAIEmbeddings retriever = MongoDBAtlasParentDocumentRetriever.from_connection_string( connection_string="<connection-string>", # MongoDB cluster URI embedding_model=VoyageAIEmbeddings( # Embedding model to use model="voyage-3-large" ), child_splitter=RecursiveCharacterTextSplitter(), # Text splitter to use database_name="<database-name>", # Database to store the collection collection_name="<collection-name>", # Collection to store the collection text_key="page_content", # Match the key the parent document store uses # Additional vector store or parent class arguments...) # Define your queryquery = "some search query" # Print resultsdocuments = retriever.invoke(query)for doc in documents: print(doc)

MongoDBAtlasSelfQueryRetriever は、それ自体をクエリするレプリカです。検索クエリークエリーは LM を使用して処理され、可能なメタデータフィルターを識別し、フィルター付きで構造化ベクトル検索クエリーを作成し、そのクエリを実行して最も関連性の高いドキュメントを検索します。

例、「2010 以降の評価が 8 を超えるアクション映画は何ですか」のようなクエリでは、取得者は genre、year、rating フィールドのフィルターを識別し、それらを使用できますクエリに一致するドキュメントを検索するためにフィルタリングします。

この検索インデックスには、既存のベクトルストアとMongoDB ベクトル検索インデックスが必要です。

from langchain_mongodb.retrievers import MongoDBAtlasSelfQueryRetrieverfrom langchain_mongodb import MongoDBAtlasVectorSearchfrom langchain_classic.chains.query_constructor.schema import AttributeInfofrom langchain_voyageai import VoyageAIEmbeddingsfrom langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-4o", temperature=0) vector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string="<connection-string>", namespace="langchain_db.movies", embedding=VoyageAIEmbeddings(model="voyage-3-large"), index_name="vector_index",) # Given an existing vector store with movies data, define metadata describing the datametadata_field_info = [ AttributeInfo( name="genre", description="The genre of the movie. One of ['science fiction', 'comedy', 'drama', 'thriller', 'romance', 'animated']", type="string", ), AttributeInfo( name="year", description="The year the movie was released", type="integer", ), AttributeInfo( name="rating", description="A 1-10 rating for the movie", type="float" ),] # Create the retriever from the VectorStore, an LLM and info about the documentsretriever = MongoDBAtlasSelfQueryRetriever.from_llm( llm=llm, vectorstore=vector_store, metadata_field_info=metadata_field_info, document_contents="Descriptions of movies", enable_limit=True,) # This example results in the following composite filter sent to $vectorSearch:# {'filter': {'$and': [{'year': {'$lt': 1960}}, {'rating': {'$gt': 8}}]}}documents = retriever.invoke("Movies made before 1960 that are rated higher than 8")print(documents)

GraphRAG は、ベクトル埋め込みとしてではなく、エンティティとその関係の知識グラフとしてデータを構造化する従来の RAG の代替アプローチです。ベクトルベースの RAG はクエリにセマンティックに類似するドキュメントを検索しますが、GraphRAG はクエリに接続されたエンティティを検索し、グラフ内の関係を走査して関連情報を検索します。

このアプローチは関係がベースとなる質問で特に役立ちます。たとえば、「A 会社と B 会社のつながりは何ですか?」や「X さんのマネージャーは誰ですか?」などの質問です。

MongoDBGraphStore は、LangChain MongoDB 統合内のコンポーネントであり、エンティティ(ノード)とその関係(エッジ)を MongoDB コレクションに保存することで GraphRAG を実装できるようにします。コレクション内の他のドキュメントを参照する関係フィールドのあるドキュメントとして各エンティティを保存し、$graphLookup 集計ステージを使用してクエリを実行します。

from langchain_mongodb.graphrag import MongoDBGraphStorefrom langchain_openai import ChatOpenAIfrom langchain_core.documents import Document # Initialize the graph storegraph_store = MongoDBGraphStore( connection_string="<connection-string>", # MongoDB cluster URI database_name="<database-name>", # Database to store the graph collection_name="<collection-name>", # Collection to store the graph entity_extraction_model=ChatOpenAI( # LLM to extract entities model="gpt-4o", temperature=0 ), # Other optional parameters...) # Add documents to the graphdocs = [ Document( page_content=( "MongoDB is a document database. " "Dev Ittycheria is the CEO of MongoDB." ) ), Document(page_content="MongoDB Atlas is the cloud platform offered by MongoDB."),]graph_store.add_documents(docs) # Query the graphquery = "Who is the CEO of MongoDB?"answer = graph_store.chat_response(query)print(answer.content)

キャッシュは、同様のクエリまたは反復的なクエリの反復的な応答を保存して、再計算を避けることで、LM のパフォーマンスを最適化するために使用されます。MongoDB は、Lgachein アプリケーションに対して次のキャッシュを提供します。

MongoDBCache を使用すると、 MongoDBコレクションに基本的なキャッシュを保存できます。

from langchain_mongodb import MongoDBCachefrom langchain_core.globals import set_llm_cache set_llm_cache( MongoDBCache( connection_string="<connection-string>", # MongoDB cluster URI database_name="langchain_db", # Database to store the cache collection_name="cache", # Collection to store the cache ))

セマンティックキャッシュは、ユーザー入力とキャッシュされた結果のセマンティックな類似性に基づいて、キャッシュされたプロンプトを検索する、より高度なキャッシュ形式です。

MongoDBAtlasSemanticCache は、 MongoDB ベクトル検索を使用してキャッシュされたプロンプトを検索するセマンティックキャッシュです。このコンポーネントにはMongoDB ベクトル検索インデックスが必要です。

from langchain_mongodb import MongoDBAtlasSemanticCachefrom langchain_core.globals import set_llm_cachefrom langchain_voyageai import VoyageAIEmbeddings set_llm_cache( MongoDBAtlasSemanticCache( embedding=VoyageAIEmbeddings(model="voyage-3-large"), # Embedding model connection_string="<connection-string>", # MongoDB cluster URI database_name="langchain_db", # Database to store the cache collection_name="semantic_cache", # Collection to store the cache ))

LangChain DeepAgentsは、長時間実行されるマルチステップのタスク向けに設計されたエージェントハーネスです。プランニング、コンテキストマネジメント、サブエージェントへの作業の委任を取り扱います。このハーネスは、エージェントのファイルが実際にどこに配置されるかを変更できる、交換可能なバックエンドプロトコルをサポートしています。langchain-mongodb-deepagents-vfsパッケージはそのプロトコルの実装です。Amazon S3がファイルを保持し、埋め込みプロバイダー(AWS BedrockまたはOpenAI)が埋め込みを計算し、MongoDB Atlasがチャンクと埋め込みを保持し、MongoFilesystemBackendクラスが各ファイル操作を適切なハンドラーにルーティングします。

エージェントが S3 内の大量の既存ファイルを検索する必要がある場合は、このパッケージを使用します。grepは、Reciprocal Rank Fusion (RRF) アルゴリズムを使用してフルテキスト検索とベクトル検索の結果を統合する 1 つの MongoDB 集計として実行されるため、すべてのファイルをエージェントに読み込んで 1 つずつフィルターすることなく、増やすことができます。glob と ls は、ファイル名とディレクトリの検索を直接取り扱います。エージェントがread、write、edit、upload_files、またはdownload_filesを呼び出すとき、それらの呼び出しはS3に直接転送されます。そこにはお客様のファイルが保存されています。他のツールで追加されたファイルは、バックエンドのウォッチャーによって自動的に検出され、インデックス化されます。

パッケージをインストールする前に、次のものが準備されていることを確認してください。

  • MongoDB Atlas 接続文字列

  • AWS 認証情報 (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION)、IAM ポリシーで次の権限が付与されます。

    • s3:GetObject、s3:PutObject、s3:ListBucket、およびs3:DeleteObjectをおその S3 バケット上で

    • bedrock:InvokeModel amazon.titan-embed-text-v2:0 上、AWS_DEFAULT_REGION と同じリージョン内で、デフォルトの Bedrock プロバイダーを使用する場合に必要です。

  • 埋め込みプロバイダーの選択: Bedrock (デフォルト、上記の Amazon Web Services 認証情報を使用)または OpenAI (EMBEDDING_PROVIDER=openai を設定し、OPENAI_API_KEY を提供)

パッケージをインストールするには、MongoDB で AWS Bedrock または OpenAI を使用して検索埋め込みを生成するかどうかを決定し、対応するコマンドを実行します。

pip install "langchain-mongodb-deepagents-vfs[bedrock]"
pip install "langchain-mongodb-deepagents-vfs[openai]"

MongoFilesystemBackend を S3 バケット名と Atlas 接続文字列でインスタンス化します。次の例では、S3 に 2 つの書き込み (write)ファイルを書き込み、その後、各検索方法を示します。

  • grep ファイルのコンテンツを検索する

  • glob パターンでファイル パスをマッチする

  • ls ディレクトリのコンテンツを一覧表示する

from langchain_mongodb_deepagents_vfs import MongoFilesystemBackend # Instantiate the backendbackend = MongoFilesystemBackend( s3_bucket_name="<bucket-name>", # S3 bucket that stores your files mongodb_connection_string="<connection-string>", # MongoDB Atlas connection string) # Write two files to S3: one .txt, one .md, so glob can demonstrate# filtering by extensionbackend.write("mongodb_vfs/docs/notes.txt", "Our authentication flow uses OAuth 2.0.")backend.write("mongodb_vfs/docs/overview.md", "This directory contains onboarding docs.") # Search for files that mention "authentication flow"# Newly written files can take a few seconds to become searchableresult = backend.grep("authentication flow", path="mongodb_vfs/docs/")print("grep matches:")for match in result.matches or []: print(match["path"], match["line"], match["text"]) # Find files that match a glob patternresult = backend.glob("*.txt", path="mongodb_vfs/docs/")print("glob matches:", result.matches) # List the contents of a directoryresult = backend.ls("mongodb_vfs/docs/")print("ls entries:", result.entries) print("init_errors:", backend.init_errors)

デフォルトでは、バックエンドはバケット内の mongodb_vfs/ プレフィックスにすべての操作を制限します。これを変更するには、MongoFilesystemBackend に別の s3_prefix 値を渡します。または、バケット全体のアクセスには s3_prefix="" を渡します。

注意

このバックエンドをDeepAgentsエージェントに接続する方法を学ぶには、DeepAgentsクイックスタートをご覧ください。

MongoDB Agent Tools は、LorgGraph React Agent に渡すと、 MongoDBリソースを操作できるようにするツールのコレクションです。

名前
説明

MongoDBDatabaseToolkit

MongoDBデータベース をクエリするためのツール。

InfoMongoDBDatabaseTool

MongoDBデータベースに関するメタデータを取得するためのツール。

ListMongoDBDatabaseTool

MongoDB database のコレクション名を取得するためのツール。

QueryMongoDBCheckerTool

LM を呼び出してデータベースクエリが正しいかどうかを確認するツール。

from langchain_openai import ChatOpenAIfrom langgraph.prebuilt import create_react_agentfrom langchain_mongodb.agent_toolkit import ( MONGODB_AGENT_SYSTEM_PROMPT, MongoDBDatabase, MongoDBDatabaseToolkit,) db_wrapper = MongoDBDatabase.from_connection_string( "<connection-string>", database="<database-name>")llm = ChatOpenAI(model="gpt-4o-mini", timeout=60)toolkit = MongoDBDatabaseToolkit(db=db_wrapper, llm=llm) system_message = MONGODB_AGENT_SYSTEM_PROMPT.format(top_k=5) test_query = "Which country's customers spent the most?"agent = create_react_agent(llm, toolkit.get_tools(), prompt=system_message)agent.step_timeout = 60events = agent.stream( {"messages": [("user", test_query)]}, stream_mode="values",) messages = []for event in events: messages.extend(event["messages"])print(messages[-1].content)

ドキュメントローダーは LangChain アプリケーションにデータをロードするのに役立つツールです。

MongoDBLoader は、MongoDB データベースからドキュメントのリストを返すドキュメントローダーです。

from langchain_mongodb.loaders import MongoDBLoader loader = MongoDBLoader.from_connection_string( connection_string="<connection-string>", # MongoDB cluster URI db_name="langchain_db", # Database that contains the collection collection_name="documents", # Collection to load documents from filter_criteria={"category": "ai"}, # Optional document to specify a filter field_names=["title", "summary"], # Optional list of fields to include metadata_names=["category"], # Optional metadata fields to extract) docs = loader.load()

MongoDBChatMessageHistory は、MongoDB データベースにチャット メッセージ履歴を保存および管理できるコンポーネントです。ユーザーと AI が生成したメッセージの両方を、一意のセッション識別子に関連付けて保存することができます。チャットボットなど、時間の経過に伴うインタラクションを追跡するアプリケーションにこのコンポーネントを使用します。

from langchain_mongodb.chat_message_histories import MongoDBChatMessageHistory chat_message_history = MongoDBChatMessageHistory( session_id="<session-id>", # Unique session identifier connection_string="<connection-string>", # MongoDB cluster URI database_name="langchain_db", # Database to store the chat history collection_name="chat_history", # Collection to store the chat history) chat_message_history.add_user_message("Hello")chat_message_history.add_ai_message("Hi")
print(chat_message_history.messages)
[HumanMessage(content='Hello', additional_kwargs={}, response_metadata={}), AIMessage(content='Hi', additional_kwargs={}, response_metadata={}, tool_calls=[], invalid_tool_calls=[])]

MongoDB でデータを管理および保存するために、次のカスタム データ ストアを使用できます。

MongoDBDocStore は、MongoDB を使用してドキュメントを保存および管理するカスタム キーバリュー ストアです。CRUD 操作は、他の MongoDB コレクションと同様に実行できます。

from langchain_mongodb.docstores import MongoDBDocStore # Replace with your MongoDB connection string and namespaceconnection_string = "<connection-string>"namespace = "<database-name>.<collection-name>" # Initialize the MongoDBDocStoredocstore = MongoDBDocStore.from_connection_string(connection_string, namespace)

MongoDBByteStore は、MongoDB を使用してバイナリデータ、具体的にはバイトで表されるデータを保存および管理するカスタム データストアです。キーが文字列で値がバイト シーケンスであるキーと値のペアを使用して、CRUD 操作を実行できます。

from langchain_community.storage.mongodb import MongoDBByteStore # Instantiate the MongoDBByteStoremongodb_store = MongoDBByteStore( connection_string="<connection-string>", # MongoDB cluster URI db_name="langchain_db", # Name of the database collection_name="byte_store", # Name of the collection) # Set values for keysmongodb_store.mset([("key1", b"hello"), ("key2", b"world")]) # Get values for keysvalues = mongodb_store.mget(["key1", "key2"])print(values) # Iterate over keysfor key in mongodb_store.yield_keys(): print(key) # Delete keysmongodb_store.mdelete(["key1", "key2"])
[b'hello', b'world']key1key2

MongoDBと LgGraph を統合する方法については、「 MongoDBと LgGraph の統合 」を参照してください。

インタラクティブPythonノートについては、 Docs Notes リポジトリ およびジェネレーティブAIが使用するリポジトリ を参照してください。