AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

MongoDB 와 LangChain 통합

MongoDB LangChain과 통합하여 생성형 AI 및 RAG 애플리케이션을 빌드 할 수 있습니다. 이 페이지에서는 LangChain MongoDB Python 통합에 대한 개요와 애플리케이션에서 사용할 수 있는 다양한 구성 요소를 제공합니다.

시작하기

참고

구성 요소 및 메서드의 전체 목록은 API 참조를 참조하세요.

JavaScript 통합에 대해서는 LangChain JS/TS를 참조하세요.

LangChain과 함께 MongoDB Vector Search를 사용하려면 먼저 langchain-mongodb 패키지 설치해야 합니다.

pip install langchain-mongodb

MongoDBAtlasVectorSearch 는 MongoDB 의 컬렉션 에서 벡터 임베딩을 저장 하고 조회 할 수 있는 벡터 저장 입니다. 이 구성 요소를 사용하여 데이터의 임베딩을 저장 하고 MongoDB Vector Search를 사용하여 조회 .

이 구성 요소에는 MongoDB 벡터 검색 인덱스가 필요합니다.

Atlas 두 가지 임베딩 모드를 지원합니다.

  • 수동 임베딩: 지정한 임베딩 모델을 사용하여 클라이언트 측에서 임베딩 벡터를 생성합니다.

  • 자동 임베딩: MongoDB 텍스트를 수동으로 생성할 필요 없이 서버 측에 텍스트를 임베딩합니다. 자세한 학습 은 자동 임베딩을 참조하세요.

벡터 저장 인스턴스화하는 가장 빠른 방법은 MongoDB cluster 또는 로컬 배포서버 에 연결 문자열 사용하는 것입니다.

from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
from langchain_voyageai import VoyageAIEmbeddings
# Instantiate the vector store using your MongoDB connection string
vector_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...
)

자동 임베딩을 사용하려면 AutoEmbeddings 인스턴스 embedding 매개변수에 전달합니다. 이를 통해 MongoDB 임베딩 벡터를 자동으로 생성하고 관리할 수 있습니다.

자동화된 임베딩:

  • 클라이언트 사이드 임베딩 계산이 필요하지 않습니다.

  • 원시 텍스트가 MongoDB 로 직접 전송됩니다.

  • 임베딩 벡터는 서버 측에서 생성됩니다.

  • embedding_key 필드 문서에 저장되지 않았습니다.

from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
from langchain_mongodb.embeddings import AutoEmbeddings
from langchain_core.documents import Document
# Some documents to embed
docs = [
Document(page_content="foo", metadata={"baz": "bar"}),
Document(page_content="thud", metadata={"bar": "baz"}),
]
# Instantiate the vector store with Automated Embedding
vector_store = MongoDBAtlasVectorSearch.from_connection_string(
connection_string="<connection-string>", # MongoDB cluster URI
namespace="<database-name>.<collection-name>", # Database and collection name
embedding=AutoEmbeddings(model="voyage-4"), # Enable Automated Embedding
index_name="vector_index", # Name of the vector search index
# Other optional parameters...
)
# Add documents - text is embedded server-side
vector_store.add_documents(documents=docs)
# Search - queries are embedded server-side
results = vector_store.similarity_search("search query")

통합은 벡터 저장소를 인스턴스화하는 다른 방법도 지원합니다.

  • MongoDB 클라이언트를 사용하여 다음을 수행합니다.

    from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
    from langchain_voyageai import VoyageAIEmbeddings
    from pymongo import MongoClient
    # Connect to your MongoDB cluster
    client = MongoClient("<connection-string>")
    collection = client["<database-name>"]["<collection-name>"]
    # Instantiate the vector store
    vector_store = MongoDBAtlasVectorSearch(
    collection=collection, # Collection to store embeddings
    embedding=VoyageAIEmbeddings(model="voyage-3-large"), # Embedding model to use
    index_name="vector_index", # Name of the vector search index
    # Other optional parameters...
    )
  • 사용자가 만든 문서에서:

    from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
    from langchain_voyageai import VoyageAIEmbeddings
    from langchain_core.documents import Document
    from pymongo import MongoClient
    # Some documents to embed
    document_1 = Document(page_content="foo", metadata={"baz": "bar"})
    document_2 = Document(page_content="thud", metadata={"bar": "baz"})
    docs = [document_1, document_2]
    # Connect to your MongoDB cluster
    client = MongoClient("<connection-string>")
    collection = client["<database-name>"]["<collection-name>"]
    # Create the vector store from documents
    vector_store = MongoDBAtlasVectorSearch.from_documents(
    documents=docs, # List of documents to embed
    embedding=VoyageAIEmbeddings(model="voyage-3-large"), # Embedding model to use
    collection=collection, # Collection to store embeddings
    index_name="vector_index", # Name of the vector search index
    )

다음 매개 변수를 사용하여 벡터 스토어를 구성합니다.

Parameter
필요성
설명

connection_string

필수 사항

MongoDB cluster 에 대한 연결 문자열 지정합니다. 자세한 학습 은 클라이언트 라이브러리 또는 연결 문자열을 통해 클러스터에 연결을 참조하세요.

namespace

필수 사항

벡터 임베딩을 저장할 MongoDB 네임스페이스를 지정합니다.

예를 들어 langchain_db.test입니다.

embedding

필수 사항

사용할 임베딩 모델입니다. 서버 측 자동 임베딩을 위해 LangChain에서 지원되는 임베딩 모델 또는 AutoEmbeddings 인스턴스를 사용할 수 있습니다.

index_name

옵션

MongoDB Vector Search 인덱스 의 이름입니다. 기본값은 vector_index입니다.

text_key

옵션

문서 텍스트 콘텐츠가 포함된 필드 이름입니다. 기본값은 text입니다.

embedding_key

옵션

임베딩 벡터를 저장하는 필드 이름입니다. 기본값은 embedding입니다.

relevance_score_fn

옵션

사용할 유사성 함수입니다. 허용되는 값은 cosine, euclidean 또는 dotProduct입니다. 기본값은 cosine입니다.

dimensions

옵션

벡터 차원의 개수입니다. 이 값을 설정하다 컬렉션 에 벡터 검색 인덱스 없는 경우 MongoDB 인덱스 생성합니다.

auto_create_index

옵션

벡터 인덱스가 존재하지 않을 경우 자동으로 생성할지 여부를 결정하는 플래그입니다. 기본값은 False입니다.

auto_index_timeout

옵션

자동 생성된 벡터 검색 인덱스가 준비될 때까지 대기할 초 단위의 시간 초과입니다.

vector_index_options

옵션

벡터 검색 인덱스 구성하기 위한 추가 옵션의 사전입니다.

**kwargs

옵션

LangChain 전용 매개변수 등 벡터 저장소에 전달할 수 있는 추가 매개변수입니다.

LangChain 리트리버 는 벡터 저장소에서 관련 문서를 가져오는 데 사용하는 구성 요소입니다. LangChain의 내장 리트리버 또는 다음과 같은 MongoDB 리트리버를 사용하여 MongoDB 에서 데이터를 쿼리 하고 조회 수 있습니다.

MongoDB 벡터 저장 로 인스턴스화한 후 벡터 저장 인스턴스 리트리버로 사용하여 MongoDB Vector Search를 사용하여 데이터를 쿼리 수 있습니다.

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(model="voyage-3-large"), # Embedding model to use
index_name="vector_index", # Name of the vector search index
)
# Use the vector store as a retriever
retriever = vector_store.as_retriever()
# Define your query
query = "some search query"
# Print results
documents = retriever.invoke(query)
for doc in documents:
print(doc)

MongoDBAtlasFullTextSearchRetriever MongoDB Search를 사용하여 전체 텍스트 검색 수행하는 리트리버입니다. 구체적으로 Lucene의 표준 BM25 알고리즘 사용합니다.

이 리트리버에는 MongoDB 검색 인덱스가 필요합니다.

from langchain_mongodb.retrievers.full_text_search import (
MongoDBAtlasFullTextSearchRetriever,
)
from pymongo import MongoClient
# Connect to your MongoDB cluster
client = MongoClient("<connection-string>")
collection = client["<database-name>"]["<collection-name>"]
# Initialize the retriever
retriever = 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 query
query = "some search query"
# Print results
documents = retriever.invoke(query)
for doc in documents:
print(doc)

참고

MongoDBAtlasHybridSearchRetriever RRF(Reciprocal Rank Federation) 알고리즘 사용하여 벡터 검색 과 전체 텍스트 검색 결과를 결합하는 리트리버입니다. 자세한 학습 은 하이브리드 검색 수행 방법을 참조하세요.

이 리트리버에는 기존 벡터 저장, MongoDB 벡터 검색 인덱스 및 MongoDB 검색 인덱스가 필요합니다.

from langchain_mongodb.retrievers.hybrid_search import (
MongoDBAtlasHybridSearchRetriever,
)
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(model="voyage-3-large"), # Embedding model to use
index_name="vector_index", # Name of the vector search index
)
# Initialize the retriever
retriever = 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 query
query = "some search query"
# Print results
documents = retriever.invoke(query)
for doc in documents:
print(doc)

MongoDBAtlasParentDocumentRetriever 작은 청크를 먼저 쿼리한 다음 큰 상위 문서를 LLM에 반환하는 검색기입니다. 이러한 유형의 검색을 상위 문서 검색이라고 합니다. 상위 문서 검색은 작은 청크에 대한 더 세분화된 검색을 허용하면서 LLM에 상위 문서의 전체 컨텍스트를 제공함으로써 RAG 에이전트 및 애플리케이션의 응답을 개선할 수 있습니다.

검색기는 상위 및 하위 문서를 단일 MongoDB 컬렉션에 저장하며 하위 문서의 임베딩만 계산하고 인덱싱함으로써 효율적인 검색을 지원합니다.

이 검색기는 내부적으로 다음을 생성합니다.

  • 하위 문서에 대한 벡터 검색 쿼리를 처리하기 위한 MongoDBAtlasVectorSearch의 인스턴스입니다.

  • 상위 문서의 저장 및 검색을 처리하기 위한 MongoDBDocStore의 인스턴스입니다.

벡터 저장 와 상위 문서 저장 문서 텍스트에 동일한 필드 이름을 사용하도록 text_key를 page_content로 설정합니다. 이 매개 변수가 없으면 리트리버가 상위 문서를 한 필드 에 쓰고 다른 필드에서 읽으면 KeyError: 'text' 쿼리가 실패합니다.

from langchain_mongodb.retrievers import MongoDBAtlasParentDocumentRetriever
from langchain_text_splitters import RecursiveCharacterTextSplitter
from 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 query
query = "some search query"
# Print results
documents = retriever.invoke(query)
for doc in documents:
print(doc)

MongoDBAtlasSelfQueryRetriever 자체 쿼리를 수행하는 리트리버입니다. 리트리버는 LLM을 사용하여 검색 쿼리 프로세스 사용 가능한 메타데이터 필터를 식별하고, 필터를 사용하여 구조화된 벡터 검색 쿼리 구성한 다음, 쿼리 실행하여 가장 관련성이 높은 문서를 조회 .

예시 들어 8 이상의 평점이 있는 2010 이후의 스릴러 영화는 무엇인가요?"와 같은 쿼리 사용하여 리트리버는 genre, year 및 rating 필드에서 필터를 식별하고 해당 필터를 사용할 수 있습니다. 필터를 사용하여 쿼리 와 일치하는 문서를 조회 .

이 리트리버에는 기존 벡터 저장 와 MongoDB Vector Search 인덱스가 필요합니다.

from langchain_mongodb.retrievers import MongoDBAtlasSelfQueryRetriever
from langchain_mongodb import MongoDBAtlasVectorSearch
from langchain_classic.chains.query_constructor.schema import AttributeInfo
from langchain_voyageai import VoyageAIEmbeddings
from 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 data
metadata_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 documents
retriever = 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 MongoDBGraphStore
from langchain_openai import ChatOpenAI
from langchain_core.documents import Document
# Initialize the graph store
graph_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 graph
docs = [
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 graph
query = "Who is the CEO of MongoDB?"
answer = graph_store.chat_response(query)
print(answer.content)

캐시는 유사하거나 반복적인 쿼리에 대한 반복적인 응답을 저장하여 재계산을 방지함으로써 LLM 성능을 최적화하는 데 사용됩니다. MongoDB는 LangChain 애플리케이션에 대해 다음과 같은 캐시를 제공합니다.

MongoDBCache MongoDB 컬렉션 에 기본 캐시 저장 수 있습니다.

from langchain_mongodb import MongoDBCache
from 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 Vector Search를 사용하여 캐시된 프롬프트를 조회 하는 시맨틱 캐시 입니다. 이 구성 요소에는 MongoDB Vector Search 인덱스 필요합니다.

from langchain_mongodb import MongoDBAtlasSemanticCache
from langchain_core.globals import set_llm_cache
from 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 침대록 또는 OpenAI)는 임베딩을 계산하고, MongoDB Atlas 청크와 임베딩을 보유하고, MongoFilesystemBackend 클래스는 각 파일 라우팅합니다. 작업을 올바른 핸들러에 전달합니다.

에이전트 가 S3에서 대규모 기존 파일 설정하다 를 검색 해야 할 때 이 패키지 사용합니다. grep는 RRF(Reciprocal Rank Federation) 알고리즘 사용하여 전체 텍스트 및 벡터 검색 결과를 결합하는 단일 MongoDB 집계 으로 실행되므로 모든 파일 에이전트 에 로드하여 하나씩 필터하다 하지 않고도 확장됩니다. glob 및 ls는 파일 이름 및 디렉토리 조회를 직접 처리하다 . 에이전트 read, write, edit, upload_files 또는 download_files을(를) 호출하면 해당 호출은 파일이 있는 S3로 직접 이동합니다. 다른 도구에서 추가한 파일은 백엔드의 감시자에 의해 자동으로 선택되고 인덱싱됩니다.

패키지 설치하기 전에 다음 사항이 있는지 확인하세요.

  • MongoDB Atlas 연결 문자열

  • IAM 정책이 부여하는 AWS 자격 증명 (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION):

    • s3:GetObject, s3:PutObject, s3:ListBucket, s3:DeleteObject를 S3 버킷에 저장합니다.

    • bedrock:InvokeModel AWS_DEFAULT_REGION와 동일한 리전 의 amazon.titan-embed-text-v2:0에서 기본값 기반 기반 제공자 사용하는 경우 필요합니다.

  • 임베딩 제공자 선택: 기반( 기본값, 위의 AWS 자격 증명 사용) 또는 OpenAI( EMBEDDING_PROVIDER=openai를 설정하다 하고 OPENAI_API_KEY 제공)

패키지 설치하려면 MongoDB AWS 기반 또는 OpenAI를 사용하여 검색 임베딩을 생성할지 여부를 결정하고 일치하는 명령을 실행 .

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

S3 버킷 이름과 Atlas 연결 문자열 로 MongoFilesystemBackend을(를) 인스턴스화합니다. 다음 예시 S3에 두 개의 파일을 쓴 다음 각 검색 메서드를 보여줍니다.

  • grep 파일의 내용을 검색합니다.

  • glob 패턴 별로 파일 경로 일치

  • ls 디렉토리의 내용을 나열합니다.

from langchain_mongodb_deepagents_vfs import MongoFilesystemBackend
# Instantiate the backend
backend = 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 extension
backend.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 searchable
result = 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 pattern
result = backend.glob("*.txt", path="mongodb_vfs/docs/")
print("glob matches:", result.matches)
# List the contents of a directory
result = backend.ls("mongodb_vfs/docs/")
print("ls entries:", result.entries)
print("init_errors:", backend.init_errors)

기본값 으로 백엔드 모든 작업을 버킷의 mongodb_vfs/ 접두사로 제한합니다. 이를 변경하려면 다른 s3_prefix 값을 MongoFilesystemBackend에 전달하고, 전체 버킷 액세스 위해서는 s3_prefix=""을 전달합니다.

참고

이 백엔드 딥에이전트 에이전트 에 연결하는 방법을 학습 보려면 딥에이전트 빠른 시작을 참조하세요.

MongoDB Agent 툴킷은 MongoDB 리소스와 상호 작용 수 있도록 LangGraph React Agent에 전달할 수 있는 연장 컬렉션 입니다.

이름
설명

MongoDBDatabaseToolkit

MongoDB database 쿼리하기 위한 도구입니다.

InfoMongoDBDatabaseTool

MongoDB database 에 대한 메타데이터 가져오는 도구입니다.

ListMongoDBDatabaseTool

MongoDB 데이터베이스의 컬렉션 이름을 가져오는 도구입니다.

QueryMongoDBCheckerTool

데이터베이스 쿼리 올바른지 확인하기 위해 LLM을 호출하는 도구입니다.

from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from 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 = 60
events = 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 database 에 저장 하고 관리 할 수 있는 구성 요소입니다. 고유 세션 식별자와 관련된 사용자 및 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를 사용하여 문서를 저장하고 관리하는 맞춤형 키-값 저장소입니다. 다른 MongoDB 컬렉션과 마찬가지로 CRUD 작업을 수행할 수 있습니다.

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

참고

MongoDBByteStore 바이너리 데이터, 특히 바이트로 표시되는 데이터를 MongoDB를 사용하여 저장하고 관리하는 사용자 지정 데이터스토어입니다. 키가 문자열이고 값이 바이트 시퀀스인 키-값 쌍을 사용하여 CRUD 작업을 수행할 수 있습니다.

from langchain_community.storage.mongodb import MongoDBByteStore
# Instantiate the MongoDBByteStore
mongodb_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 keys
mongodb_store.mset([("key1", b"hello"), ("key2", b"world")])
# Get values for keys
values = mongodb_store.mget(["key1", "key2"])
print(values)
# Iterate over keys
for key in mongodb_store.yield_keys():
print(key)
# Delete keys
mongodb_store.mdelete(["key1", "key2"])
[b'hello', b'world']
key1
key2

참고

MongoDB LangGraph와 통합하는 방법을 학습 MongoDB 와 LangGraph 통합하기를 참조하세요.

대화형 Python 노트북에 대해서는 Docs 노트북 리포지토리 및 생성형 AI 사용 사례 리포지토리를 참조하세요.