Skip to content

The agent engineering platform.

Implemented MongoDB Atlas Self-Query Retriever (#13321)

AthulVincent67c55cb5b042
diff --git a/docs/docs/integrations/retrievers/self_query/mongodb_atlas.ipynb b/docs/docs/integrations/retrievers/self_query/mongodb_atlas.ipynb
new file mode 100644
index 0000000000..3ee3b28c1c
--- /dev/null
+++ b/docs/docs/integrations/retrievers/self_query/mongodb_atlas.ipynb
@@ -0,0 +1,321 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# MongoDB Atlas\n",
+ "\n",
+ "[MongoDB Atlas](https://www.mongodb.com/) is a document database that can be \n",
+ "used as a vector databse.\n",
+ "\n",
+ "In the walkthrough, we'll demo the `SelfQueryRetriever` with a `MongoDB Atlas` vector store."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Creating a MongoDB Atlas vectorstore\n",
+ "First we'll want to create a MongoDB Atlas VectorStore and seed it with some data. We've created a small demo set of documents that contain summaries of movies.\n",
+ "\n",
+ "NOTE: The self-query retriever requires you to have `lark` installed (`pip install lark`). We also need the `pymongo` package."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "#!pip install lark pymongo"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We want to use `OpenAIEmbeddings` so we have to get the OpenAI API Key."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "\n",
+ "OPENAI_API_KEY = \"Use your OpenAI key\"\n",
+ "\n",
+ "os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from langchain.embeddings.openai import OpenAIEmbeddings\n",
+ "from langchain.schema import Document\n",
+ "from langchain.vectorstores import MongoDBAtlasVectorSearch\n",
+ "from pymongo import MongoClient\n",
+ "\n",
+ "CONNECTION_STRING = \"Use your MongoDB Atlas connection string\"\n",
+ "DB_NAME = \"Name of your MongoDB Atlas database\"\n",
+ "COLLECTION_NAME = \"Name of your collection in the database\"\n",
+ "INDEX_NAME = \"Name of a search index defined on the collection\"\n",
+ "\n",
+ "MongoClient = MongoClient(CONNECTION_STRING)\n",
+ "collection = MongoClient[DB_NAME][COLLECTION_NAME]\n",
+ "\n",
+ "embeddings = OpenAIEmbeddings()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "docs = [\n",
+ " Document(\n",
+ " page_content=\"A bunch of scientists bring back dinosaurs and mayhem breaks loose\",\n",
+ " metadata={\"year\": 1993, \"rating\": 7.7, \"genre\": \"action\"},\n",
+ " ),\n",
+ " Document(\n",
+ " page_content=\"Leo DiCaprio gets lost in a dream within a dream within a dream within a ...\",\n",
+ " metadata={\"year\": 2010, \"genre\": \"thriller\", \"rating\": 8.2},\n",
+ " ),\n",
+ " Document(\n",
+ " page_content=\"A bunch of normal-sized women are supremely wholesome and some men pine after them\",\n",
+ " metadata={\"year\": 2019, \"rating\": 8.3, \"genre\": \"drama\"},\n",
+ " ),\n",
+ " Document(\n",
+ " page_content=\"Three men walk into the Zone, three men walk out of the Zone\",\n",
+ " metadata={\"year\": 1979, \"rating\": 9.9, \"genre\": \"science fiction\"},\n",
+ " ),\n",
+ " Document(\n",
+ " page_content=\"A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea\",\n",
+ " metadata={\"year\": 2006, \"genre\": \"thriller\", \"rating\": 9.0},\n",
+ " ),\n",
+ " Document(\n",
+ " page_content=\"Toys come alive and have a blast doing so\",\n",
+ " metadata={\"year\": 1995, \"genre\": \"animated\", \"rating\": 9.3},\n",
+ " ),\n",
+ "]\n",
+ "\n",
+ "vectorstore = MongoDBAtlasVectorSearch.from_documents(\n",
+ " docs,\n",
+ " embeddings,\n",
+ " collection=collection,\n",
+ " index_name=INDEX_NAME,\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now, let's create a vector search index on your cluster. In the below example, `embedding` is the name of the field that contains the embedding vector. Please refer to the [documentation](https://www.mongodb.com/docs/atlas/atlas-search/field-types/knn-vector) to get more details on how to define an Atlas Vector Search index.\n",
+ "You can name the index `{COLLECTION_NAME}` and create the index on the namespace `{DB_NAME}.{COLLECTION_NAME}`. Finally, write the following definition in the JSON editor on MongoDB Atlas:\n",
+ "\n",
+ "```json\n",
+ "{\n",
+ " \"mappings\": {\n",
+ " \"dynamic\": true,\n",
+ " \"fields\": {\n",
+ " \"embedding\": {\n",
+ " \"dimensions\": 1536,\n",
+ " \"similarity\": \"cosine\",\n",
+ " \"type\": \"knnVector\"\n",
+ " },\n",
+ " \"genre\": {\n",
+ " \"type\": \"token\"\n",
+ " },\n",
+ " \"ratings\": {\n",
+ " \"type\": \"number\"\n",
+ " },\n",
+ " \"year\": {\n",
+ " \"type\": \"number\"\n",
+ " }\n",
+ " }\n",
+ " }\n",
+ "}\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Creating our self-querying retriever\n",
+ "Now we can instantiate our retriever. To do this we'll need to provide some information upfront about the metadata fields that our documents support and a short description of the document contents."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from langchain.chains.query_constructor.base import AttributeInfo\n",
+ "from langchain.llms import OpenAI\n",
+ "from langchain.retrievers.self_query.base import SelfQueryRetriever\n",
+ "\n",
+ "metadata_field_info = [\n",
+ " AttributeInfo(\n",
+ " name=\"genre\",\n",
+ " description=\"The genre of the movie\",\n",
+ " type=\"string\",\n",
+ " ),\n",
+ " AttributeInfo(\n",
+ " name=\"year\",\n",
+ " description=\"The year the movie was released\",\n",
+ " type=\"integer\",\n",
+ " ),\n",
+ " AttributeInfo(\n",
+ " name=\"rating\", description=\"A 1-10 rating for the movie\", type=\"float\"\n",
+ " ),\n",
+ "]\n",
+ "document_content_description = \"Brief summary of a movie\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "llm = OpenAI(temperature=0)\n",
+ "retriever = SelfQueryRetriever.from_llm(\n",
+ " llm, vectorstore, document_content_description, metadata_field_info, verbose=True\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Testing it out\n",
+ "And now we can try actually using our retriever!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This example only specifies a relevant query\n",
+ "retriever.get_relevant_documents(\"What are some movies about dinosaurs\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This example specifies a filter\n",
+ "retriever.get_relevant_documents(\"What are some highly rated movies (above 9)?\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This example only specifies a query and a filter\n",
+ "retriever.get_relevant_documents(\n",
+ " \"I want to watch a movie about toys rated higher than 9\"\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This example specifies a composite filter\n",
+ "retriever.get_relevant_documents(\n",
+ " \"What's a highly rated (above or equal 9) thriller film?\"\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This example specifies a query and composite filter\n",
+ "retriever.get_relevant_documents(\n",
+ " \"What's a movie after 1990 but before 2005 that's all about dinosaurs, \\\n",
+ " and preferably has a lot of action\"\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Filter k\n",
+ "\n",
+ "We can also use the self query retriever to specify `k`: the number of documents to fetch.\n",
+ "\n",
+ "We can do this by passing `enable_limit=True` to the constructor."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "retriever = SelfQueryRetriever.from_llm(\n",
+ " llm,\n",
+ " vectorstore,\n",
+ " document_content_description,\n",
+ " metadata_field_info,\n",
+ " verbose=True,\n",
+ " enable_limit=True,\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This example only specifies a relevant query\n",
+ "retriever.get_relevant_documents(\"What are two movies about dinosaurs?\")"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": ".venv",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.11.5"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/libs/langchain/langchain/retrievers/self_query/base.py b/libs/langchain/langchain/retrievers/self_query/base.py
index cb51639622..dc1bf174b8 100644
--- a/libs/langchain/langchain/retrievers/self_query/base.py
+++ b/libs/langchain/langchain/retrievers/self_query/base.py
@@ -21,6 +21,7 @@ from langchain.retrievers.self_query.dashvector import DashvectorTranslator
from langchain.retrievers.self_query.deeplake import DeepLakeTranslator
from langchain.retrievers.self_query.elasticsearch import ElasticsearchTranslator
from langchain.retrievers.self_query.milvus import MilvusTranslator
+from langchain.retrievers.self_query.mongodb_atlas import MongoDBAtlasTranslator
from langchain.retrievers.self_query.myscale import MyScaleTranslator
from langchain.retrievers.self_query.opensearch import OpenSearchTranslator
from langchain.retrievers.self_query.pinecone import PineconeTranslator
@@ -36,6 +37,7 @@ from langchain.vectorstores import (
DeepLake,
ElasticsearchStore,
Milvus,
+ MongoDBAtlasVectorSearch,
MyScale,
OpenSearchVectorSearch,
Pinecone,
@@ -66,6 +68,7 @@ def _get_builtin_translator(vectorstore: VectorStore) -> Visitor:
SupabaseVectorStore: SupabaseVectorTranslator,
TimescaleVector: TimescaleVectorTranslator,
OpenSearchVectorSearch: OpenSearchTranslator,
+ MongoDBAtlasVectorSearch: MongoDBAtlasTranslator,
}
if isinstance(vectorstore, Qdrant):
return QdrantTranslator(metadata_key=vectorstore.metadata_payload_key)
diff --git a/libs/langchain/langchain/retrievers/self_query/mongodb_atlas.py b/libs/langchain/langchain/retrievers/self_query/mongodb_atlas.py
new file mode 100644
index 0000000000..a10e7b58fa
--- /dev/null
+++ b/libs/langchain/langchain/retrievers/self_query/mongodb_atlas.py
@@ -0,0 +1,74 @@
+"""Logic for converting internal query language to a valid MongoDB Atlas query."""
+from typing import Dict, Tuple, Union
+
+from langchain.chains.query_constructor.ir import (
+ Comparator,
+ Comparison,
+ Operation,
+ Operator,
+ StructuredQuery,
+ Visitor,
+)
+
+MULTIPLE_ARITY_COMPARATORS = [Comparator.IN, Comparator.NIN]
+
+
+class MongoDBAtlasTranslator(Visitor):
+ """Translate Mongo internal query language elements to valid filters."""
+
+ """Subset of allowed logical comparators."""
+ allowed_comparators = [
+ Comparator.EQ,
+ Comparator.NE,
+ Comparator.GT,
+ Comparator.GTE,
+ Comparator.LT,
+ Comparator.LTE,
+ Comparator.IN,
+ Comparator.NIN,
+ ]
+
+ """Subset of allowed logical operators."""
+ allowed_operators = [Operator.AND, Operator.OR]
+
+ ## Convert a operator or a comparator to Mongo Query Format
+ def _format_func(self, func: Union[Operator, Comparator]) -> str:
+ self._validate_func(func)
+ map_dict = {
+ Operator.AND: "$and",
+ Operator.OR: "$or",
+ Comparator.EQ: "$eq",
+ Comparator.NE: "$ne",
+ Comparator.GTE: "$gte",
+ Comparator.LTE: "$lte",
+ Comparator.LT: "$lt",
+ Comparator.GT: "$gt",
+ Comparator.IN: "$in",
+ Comparator.NIN: "$nin",
+ }
+ return map_dict[func]
+
+ def visit_operation(self, operation: Operation) -> Dict:
+ args = [arg.accept(self) for arg in operation.arguments]
+ return {self._format_func(operation.operator): args}
+
+ def visit_comparison(self, comparison: Comparison) -> Dict:
+ if comparison.comparator in MULTIPLE_ARITY_COMPARATORS and not isinstance(
+ comparison.value, list
+ ):
+ comparison.value = [comparison.value]
+
+ comparator = self._format_func(comparison.comparator)
+
+ attribute = comparison.attribute
+
+ return {attribute: {comparator: comparison.value}}
+
+ def visit_structured_query(
+ self, structured_query: StructuredQuery
+ ) -> Tuple[str, dict]:
+ if structured_query.filter is None:
+ kwargs = {}
+ else:
+ kwargs = {"pre_filter": structured_query.filter.accept(self)}
+ return structured_query.query, kwargs
diff --git a/libs/langchain/tests/unit_tests/retrievers/self_query/test_mongodb_atlas.py b/libs/langchain/tests/unit_tests/retrievers/self_query/test_mongodb_atlas.py
new file mode 100644
index 0000000000..9eceec6b70
--- /dev/null
+++ b/libs/langchain/tests/unit_tests/retrievers/self_query/test_mongodb_atlas.py
@@ -0,0 +1,131 @@
+from typing import Dict, Tuple
+
+from langchain.chains.query_constructor.ir import (
+ Comparator,
+ Comparison,
+ Operation,
+ Operator,
+ StructuredQuery,
+)
+from langchain.retrievers.self_query.mongodb_atlas import MongoDBAtlasTranslator
+
+DEFAULT_TRANSLATOR = MongoDBAtlasTranslator()
+
+
+def test_visit_comparison_lt() -> None:
+ comp = Comparison(comparator=Comparator.LT, attribute="qty", value=20)
+ expected = {"qty": {"$lt": 20}}
+ actual = DEFAULT_TRANSLATOR.visit_comparison(comp)
+ assert expected == actual
+
+
+def test_visit_comparison_eq() -> None:
+ comp = Comparison(comparator=Comparator.EQ, attribute="qty", value=10)
+ expected = {"qty": {"$eq": 10}}
+ actual = DEFAULT_TRANSLATOR.visit_comparison(comp)
+ assert expected == actual
+
+
+def test_visit_comparison_ne() -> None:
+ comp = Comparison(comparator=Comparator.NE, attribute="name", value="foo")
+ expected = {"name": {"$ne": "foo"}}
+ actual = DEFAULT_TRANSLATOR.visit_comparison(comp)
+ assert expected == actual
+
+
+def test_visit_comparison_in() -> None:
+ comp = Comparison(comparator=Comparator.IN, attribute="name", value="foo")
+ expected = {"name": {"$in": ["foo"]}}
+ actual = DEFAULT_TRANSLATOR.visit_comparison(comp)
+ assert expected == actual
+
+
+def test_visit_comparison_nin() -> None:
+ comp = Comparison(comparator=Comparator.NIN, attribute="name", value="foo")
+ expected = {"name": {"$nin": ["foo"]}}
+ actual = DEFAULT_TRANSLATOR.visit_comparison(comp)
+ assert expected == actual
+
+
+def test_visit_operation() -> None:
+ op = Operation(
+ operator=Operator.AND,
+ arguments=[
+ Comparison(comparator=Comparator.GTE, attribute="qty", value=10),
+ Comparison(comparator=Comparator.LTE, attribute="qty", value=20),
+ Comparison(comparator=Comparator.EQ, attribute="name", value="foo"),
+ ],
+ )
+ expected = {
+ "$and": [
+ {"qty": {"$gte": 10}},
+ {"qty": {"$lte": 20}},
+ {"name": {"$eq": "foo"}},
+ ]
+ }
+ actual = DEFAULT_TRANSLATOR.visit_operation(op)
+ assert expected == actual
+
+
+def test_visit_structured_query_no_filter() -> None:
+ query = "What is the capital of France?"
+ structured_query = StructuredQuery(
+ query=query,
+ filter=None,
+ )
+ expected: Tuple[str, Dict] = (query, {})
+ actual = DEFAULT_TRANSLATOR.visit_structured_query(structured_query)
+ assert expected == actual
+
+
+def test_visit_structured_query_one_attr() -> None:
+ query = "What is the capital of France?"
+ comp = Comparison(comparator=Comparator.IN, attribute="qty", value=[5, 15, 20])
+ structured_query = StructuredQuery(
+ query=query,
+ filter=comp,
+ )
+ expected = (
+ query,
+ {"pre_filter": {"qty": {"$in": [5, 15, 20]}}},
+ )
+ actual = DEFAULT_TRANSLATOR.visit_structured_query(structured_query)
+ assert expected == actual
+
+
+def test_visit_structured_query_deep_nesting() -> None:
+ query = "What is the capital of France?"
+ op = Operation(
+ operator=Operator.AND,
+ arguments=[
+ Comparison(comparator=Comparator.EQ, attribute="name", value="foo"),
+ Operation(
+ operator=Operator.OR,
+ arguments=[
+ Comparison(comparator=Comparator.GT, attribute="qty", value=6),
+ Comparison(
+ comparator=Comparator.NIN,
+ attribute="tags",
+ value=["bar", "foo"],
+ ),
+ ],
+ ),
+ ],
+ )
+ structured_query = StructuredQuery(
+ query=query,
+ filter=op,
+ )
+ expected = (
+ query,
+ {
+ "pre_filter": {
+ "$and": [
+ {"name": {"$eq": "foo"}},
+ {"$or": [{"qty": {"$gt": 6}}, {"tags": {"$nin": ["bar", "foo"]}}]},
+ ]
+ }
+ },
+ )
+ actual = DEFAULT_TRANSLATOR.visit_structured_query(structured_query)
+ assert expected == actual