Skip to content

The agent engineering platform.

Add dashvector self query retriever (#9684)

Xiaoyu Xee9bcfd58580c5
diff --git a/docs/extras/modules/data_connection/retrievers/self_query/dashvector.ipynb b/docs/extras/modules/data_connection/retrievers/self_query/dashvector.ipynb
new file mode 100644
index 0000000000..d1048ee5fa
--- /dev/null
+++ b/docs/extras/modules/data_connection/retrievers/self_query/dashvector.ipynb
@@ -0,0 +1,434 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# DashVector self-querying\n",
+ "\n",
+ "> [DashVector](https://help.aliyun.com/document_detail/2510225.html) is a fully-managed vectorDB service that supports high-dimension dense and sparse vectors, real-time insertion and filtered search. It is built to scale automatically and can adapt to different application requirements.\n",
+ "\n",
+ "In this notebook we'll demo the `SelfQueryRetriever` with a `DashVector` vector store."
+ ],
+ "metadata": {
+ "collapsed": false
+ },
+ "id": "59895c73d1a0f3ca"
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Create DashVector vectorstore\n",
+ "\n",
+ "First we'll want to create a `DashVector` VectorStore and seed it with some data. We've created a small demo set of documents that contain summaries of movies.\n",
+ "\n",
+ "To use DashVector, you have to have `dashvector` package installed, and you must have an API key and an Environment. Here are the [installation instructions](https://help.aliyun.com/document_detail/2510223.html).\n",
+ "\n",
+ "NOTE: The self-query retriever requires you to have `lark` package installed."
+ ],
+ "metadata": {
+ "collapsed": false
+ },
+ "id": "539ae9367e45a178"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "outputs": [],
+ "source": [
+ "# !pip install lark dashvector"
+ ],
+ "metadata": {
+ "collapsed": false
+ },
+ "id": "67df7e1f8dc8cdd0"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import dashvector\n",
+ "\n",
+ "client = dashvector.Client(api_key=os.environ[\"DASHVECTOR_API_KEY\"])"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-08-24T02:58:46.905337Z",
+ "start_time": "2023-08-24T02:58:46.252566Z"
+ }
+ },
+ "id": "ff61eaf13973b5fe"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "outputs": [],
+ "source": [
+ "from langchain.schema import Document\n",
+ "from langchain.embeddings import DashScopeEmbeddings\n",
+ "from langchain.vectorstores import DashVector\n",
+ "\n",
+ "embeddings = DashScopeEmbeddings()\n",
+ "\n",
+ "# create DashVector collection\n",
+ "client.create(\"langchain-self-retriever-demo\", dimension=1536)"
+ ],
+ "metadata": {
+ "collapsed": false
+ },
+ "id": "de5c77957ee42d14"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "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, \"director\": \"Christopher Nolan\", \"rating\": 8.2},\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, \"director\": \"Satoshi Kon\", \"rating\": 8.6},\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, \"director\": \"Greta Gerwig\", \"rating\": 8.3},\n",
+ " ),\n",
+ " Document(\n",
+ " page_content=\"Toys come alive and have a blast doing so\",\n",
+ " metadata={\"year\": 1995, \"genre\": \"animated\"},\n",
+ " ),\n",
+ " Document(\n",
+ " page_content=\"Three men walk into the Zone, three men walk out of the Zone\",\n",
+ " metadata={\n",
+ " \"year\": 1979,\n",
+ " \"director\": \"Andrei Tarkovsky\",\n",
+ " \"genre\": \"science fiction\",\n",
+ " \"rating\": 9.9,\n",
+ " },\n",
+ " ),\n",
+ "]\n",
+ "vectorstore = DashVector.from_documents(\n",
+ " docs, embeddings, collection_name=\"langchain-self-retriever-demo\"\n",
+ ")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-08-24T02:59:08.090031Z",
+ "start_time": "2023-08-24T02:59:05.660295Z"
+ }
+ },
+ "id": "8f40605548a4550"
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Create your self-querying retriever\n",
+ "\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."
+ ],
+ "metadata": {
+ "collapsed": false
+ },
+ "id": "eb1340adafac8993"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "outputs": [],
+ "source": [
+ "from langchain.llms import Tongyi\n",
+ "from langchain.retrievers.self_query.base import SelfQueryRetriever\n",
+ "from langchain.chains.query_constructor.base import AttributeInfo\n",
+ "\n",
+ "metadata_field_info = [\n",
+ " AttributeInfo(\n",
+ " name=\"genre\",\n",
+ " description=\"The genre of the movie\",\n",
+ " type=\"string or list[string]\",\n",
+ " ),\n",
+ " AttributeInfo(\n",
+ " name=\"year\",\n",
+ " description=\"The year the movie was released\",\n",
+ " type=\"integer\",\n",
+ " ),\n",
+ " AttributeInfo(\n",
+ " name=\"director\",\n",
+ " description=\"The name of the movie director\",\n",
+ " type=\"string\",\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\"\n",
+ "llm = Tongyi(temperature=0)\n",
+ "retriever = SelfQueryRetriever.from_llm(\n",
+ " llm, vectorstore, document_content_description, metadata_field_info, verbose=True\n",
+ ")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-08-24T02:59:11.003940Z",
+ "start_time": "2023-08-24T02:59:10.476722Z"
+ }
+ },
+ "id": "d65233dc044f95a7"
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Testing it out\n",
+ "\n",
+ "And now we can try actually using our retriever!"
+ ],
+ "metadata": {
+ "collapsed": false
+ },
+ "id": "a54af0d67b473db6"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "query='dinosaurs' filter=None limit=None\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": "[Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.699999809265137, 'genre': 'action'}),\n Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'}),\n Document(page_content='Leo DiCaprio gets lost in a dream within a dream within a dream within a ...', metadata={'year': 2010, 'director': 'Christopher Nolan', 'rating': 8.199999809265137}),\n Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'year': 2006, 'director': 'Satoshi Kon', 'rating': 8.600000381469727})]"
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# This example only specifies a relevant query\n",
+ "retriever.get_relevant_documents(\"What are some movies about dinosaurs\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-08-24T02:59:28.577901Z",
+ "start_time": "2023-08-24T02:59:26.780184Z"
+ }
+ },
+ "id": "dad9da670a267fe7"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "query=' ' filter=Comparison(comparator=<Comparator.GTE: 'gte'>, attribute='rating', value=8.5) limit=None\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": "[Document(page_content='Three men walk into the Zone, three men walk out of the Zone', metadata={'year': 1979, 'director': 'Andrei Tarkovsky', 'rating': 9.899999618530273, 'genre': 'science fiction'}),\n Document(page_content='A psychologist / detective gets lost in a series of dreams within dreams within dreams and Inception reused the idea', metadata={'year': 2006, 'director': 'Satoshi Kon', 'rating': 8.600000381469727})]"
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# This example only specifies a filter\n",
+ "retriever.get_relevant_documents(\"I want to watch a movie rated higher than 8.5\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-08-24T02:59:32.370774Z",
+ "start_time": "2023-08-24T02:59:30.614252Z"
+ }
+ },
+ "id": "d486a64316153d52"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "query='Greta Gerwig' filter=Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='director', value='Greta Gerwig') limit=None\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": "[Document(page_content='A bunch of normal-sized women are supremely wholesome and some men pine after them', metadata={'year': 2019, 'director': 'Greta Gerwig', 'rating': 8.300000190734863})]"
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# This example specifies a query and a filter\n",
+ "retriever.get_relevant_documents(\"Has Greta Gerwig directed any movies about women\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-08-24T02:59:35.353439Z",
+ "start_time": "2023-08-24T02:59:33.278255Z"
+ }
+ },
+ "id": "e05919cdead7bd4a"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "query='science fiction' filter=Operation(operator=<Operator.AND: 'and'>, arguments=[Comparison(comparator=<Comparator.EQ: 'eq'>, attribute='genre', value='science fiction'), Comparison(comparator=<Comparator.GT: 'gt'>, attribute='rating', value=8.5)]) limit=None\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": "[Document(page_content='Three men walk into the Zone, three men walk out of the Zone', metadata={'year': 1979, 'director': 'Andrei Tarkovsky', 'rating': 9.899999618530273, 'genre': 'science fiction'})]"
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# This example specifies a composite filter\n",
+ "retriever.get_relevant_documents(\"What's a highly rated (above 8.5) science fiction film?\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-08-24T02:59:38.913707Z",
+ "start_time": "2023-08-24T02:59:36.659271Z"
+ }
+ },
+ "id": "ac2c7012379e918e"
+ },
+ {
+ "cell_type": "markdown",
+ "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."
+ ],
+ "metadata": {
+ "collapsed": false
+ },
+ "id": "af6aa93ae44af414"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "outputs": [],
+ "source": [
+ "retriever = SelfQueryRetriever.from_llm(\n",
+ " llm,\n",
+ " vectorstore,\n",
+ " document_content_description,\n",
+ " metadata_field_info,\n",
+ " enable_limit=True,\n",
+ " verbose=True,\n",
+ ")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-08-24T02:59:41.594073Z",
+ "start_time": "2023-08-24T02:59:41.563323Z"
+ }
+ },
+ "id": "a8c8f09bf5702767"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "query='dinosaurs' filter=None limit=2\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": "[Document(page_content='A bunch of scientists bring back dinosaurs and mayhem breaks loose', metadata={'year': 1993, 'rating': 7.699999809265137, 'genre': 'action'}),\n Document(page_content='Toys come alive and have a blast doing so', metadata={'year': 1995, 'genre': 'animated'})]"
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# This example only specifies a relevant query\n",
+ "retriever.get_relevant_documents(\"what are two movies about dinosaurs\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-08-24T02:59:48.450506Z",
+ "start_time": "2023-08-24T02:59:46.252944Z"
+ }
+ },
+ "id": "b1089a6043980b84"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "outputs": [],
+ "source": [],
+ "metadata": {
+ "collapsed": false
+ },
+ "id": "6d2d64e2ebb17d30"
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 2
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython2",
+ "version": "2.7.6"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/libs/langchain/langchain/retrievers/self_query/base.py b/libs/langchain/langchain/retrievers/self_query/base.py
index 806d4e1502..9c64b3c44d 100644
--- a/libs/langchain/langchain/retrievers/self_query/base.py
+++ b/libs/langchain/langchain/retrievers/self_query/base.py
@@ -9,6 +9,7 @@ from langchain.chains.query_constructor.ir import StructuredQuery, Visitor
from langchain.chains.query_constructor.schema import AttributeInfo
from langchain.pydantic_v1 import BaseModel, Field, root_validator
from langchain.retrievers.self_query.chroma import ChromaTranslator
+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.myscale import MyScaleTranslator
@@ -19,6 +20,7 @@ from langchain.schema import BaseRetriever, Document
from langchain.schema.language_model import BaseLanguageModel
from langchain.vectorstores import (
Chroma,
+ DashVector,
DeepLake,
ElasticsearchStore,
MyScale,
@@ -35,6 +37,7 @@ def _get_builtin_translator(vectorstore: VectorStore) -> Visitor:
BUILTIN_TRANSLATORS: Dict[Type[VectorStore], Type[Visitor]] = {
Pinecone: PineconeTranslator,
Chroma: ChromaTranslator,
+ DashVector: DashvectorTranslator,
Weaviate: WeaviateTranslator,
Qdrant: QdrantTranslator,
MyScale: MyScaleTranslator,
diff --git a/libs/langchain/langchain/retrievers/self_query/dashvector.py b/libs/langchain/langchain/retrievers/self_query/dashvector.py
new file mode 100644
index 0000000000..24ae50239a
--- /dev/null
+++ b/libs/langchain/langchain/retrievers/self_query/dashvector.py
@@ -0,0 +1,64 @@
+"""Logic for converting internal query language to a valid DashVector query."""
+from typing import Tuple, Union
+
+from langchain.chains.query_constructor.ir import (
+ Comparator,
+ Comparison,
+ Operation,
+ Operator,
+ StructuredQuery,
+ Visitor,
+)
+
+
+class DashvectorTranslator(Visitor):
+ """Logic for converting internal query language elements to valid filters."""
+
+ allowed_operators = [Operator.AND, Operator.OR]
+ allowed_comparators = [
+ Comparator.EQ,
+ Comparator.GT,
+ Comparator.GTE,
+ Comparator.LT,
+ Comparator.LTE,
+ Comparator.LIKE,
+ ]
+
+ map_dict = {
+ Operator.AND: " AND ",
+ Operator.OR: " OR ",
+ Comparator.EQ: " = ",
+ Comparator.GT: " > ",
+ Comparator.GTE: " >= ",
+ Comparator.LT: " < ",
+ Comparator.LTE: " <= ",
+ Comparator.LIKE: " LIKE ",
+ }
+
+ def _format_func(self, func: Union[Operator, Comparator]) -> str:
+ self._validate_func(func)
+ return self.map_dict[func]
+
+ def visit_operation(self, operation: Operation) -> str:
+ args = [arg.accept(self) for arg in operation.arguments]
+ return self._format_func(operation.operator).join(args)
+
+ def visit_comparison(self, comparison: Comparison) -> str:
+ value = comparison.value
+ if isinstance(value, str):
+ if comparison.comparator == Comparator.LIKE:
+ value = f"'%{value}%'"
+ else:
+ value = f"'{value}'"
+ return (
+ f"{comparison.attribute}{self._format_func(comparison.comparator)}{value}"
+ )
+
+ def visit_structured_query(
+ self, structured_query: StructuredQuery
+ ) -> Tuple[str, dict]:
+ if structured_query.filter is None:
+ kwargs = {}
+ else:
+ kwargs = {"filter": structured_query.filter.accept(self)}
+ return structured_query.query, kwargs
diff --git a/libs/langchain/poetry.lock b/libs/langchain/poetry.lock
index 6a13a8433b..d742e5a896 100644
--- a/libs/langchain/poetry.lock
+++ b/libs/langchain/poetry.lock
@@ -1799,6 +1799,26 @@ files = [
{file = "cssselect-1.2.0.tar.gz", hash = "sha256:666b19839cfaddb9ce9d36bfe4c969132c647b92fc9088c4e23f786b30f1b3dc"},
]
+[[package]]
+name = "dashvector"
+version = "1.0.1"
+description = "DashVector Client Python Sdk Library"
+category = "main"
+optional = true
+python-versions = ">=3.7.0"
+files = [
+ {file = "dashvector-1.0.1-py3-none-any.whl", hash = "sha256:e2fc362c65979d55cf605fb90deca4a292c69e1c2101df22430c80db744591ad"},
+]
+
+[package.dependencies]
+aiohttp = ">=3.1.0"
+grpcio = [
+ {version = ">=1.22.0", markers = "python_version < \"3.11\""},
+ {version = ">=1.49.1", markers = "python_version >= \"3.11\""},
+]
+numpy = "*"
+protobuf = ">=3.8.0,<4.0.0"
+
[[package]]
name = "dataclasses-json"
version = "0.5.9"
@@ -10897,7 +10917,7 @@ clarifai = ["clarifai"]
cohere = ["cohere"]
docarray = ["docarray"]
embeddings = ["sentence-transformers"]
-extended-testing = ["amazon-textract-caller", "assemblyai", "beautifulsoup4", "bibtexparser", "cassio", "chardet", "esprima", "jq", "pdfminer-six", "pgvector", "pypdf", "pymupdf", "pypdfium2", "tqdm", "lxml", "atlassian-python-api", "mwparserfromhell", "mwxml", "pandas", "telethon", "psychicapi", "gql", "requests-toolbelt", "html2text", "py-trello", "scikit-learn", "streamlit", "pyspark", "openai", "sympy", "rapidfuzz", "openai", "rank-bm25", "geopandas", "jinja2", "gitpython", "newspaper3k", "feedparser", "xata", "xmltodict", "faiss-cpu", "openapi-schema-pydantic", "markdownify", "sqlite-vss"]
+extended-testing = ["amazon-textract-caller", "assemblyai", "beautifulsoup4", "bibtexparser", "cassio", "chardet", "esprima", "jq", "pdfminer-six", "pgvector", "pypdf", "pymupdf", "pypdfium2", "tqdm", "lxml", "atlassian-python-api", "mwparserfromhell", "mwxml", "pandas", "telethon", "psychicapi", "gql", "requests-toolbelt", "html2text", "py-trello", "scikit-learn", "streamlit", "pyspark", "openai", "sympy", "rapidfuzz", "openai", "rank-bm25", "geopandas", "jinja2", "gitpython", "newspaper3k", "feedparser", "xata", "xmltodict", "faiss-cpu", "openapi-schema-pydantic", "markdownify", "dashvector", "sqlite-vss"]
javascript = ["esprima"]
llms = ["clarifai", "cohere", "openai", "openlm", "nlpcloud", "huggingface_hub", "manifest-ml", "torch", "transformers"]
openai = ["openai", "tiktoken"]
@@ -10907,4 +10927,4 @@ text-helpers = ["chardet"]
[metadata]
lock-version = "2.0"
python-versions = ">=3.8.1,<4.0"
-content-hash = "47e048f7708139d5e5040c6d56ef4cb66153c3052a9237d6ea42eeb2565ad470"
+content-hash = "b63078268a80c07577b432114302f4f86d47be25b83a245affb0dbc999fb2c1f"
diff --git a/libs/langchain/pyproject.toml b/libs/langchain/pyproject.toml
index 0856f190d8..9fda48eb81 100644
--- a/libs/langchain/pyproject.toml
+++ b/libs/langchain/pyproject.toml
@@ -127,6 +127,7 @@ xata = {version = "^1.0.0a7", optional = true}
xmltodict = {version = "^0.13.0", optional = true}
markdownify = {version = "^0.11.6", optional = true}
assemblyai = {version = "^0.17.0", optional = true}
+dashvector = {version = "^1.0.1", optional = true}
sqlite-vss = {version = "^0.1.2", optional = true}
@@ -342,6 +343,7 @@ extended_testing = [
"faiss-cpu",
"openapi-schema-pydantic",
"markdownify",
+ "dashvector",
"sqlite-vss",
]
diff --git a/libs/langchain/tests/unit_tests/retrievers/self_query/test_dashvector.py b/libs/langchain/tests/unit_tests/retrievers/self_query/test_dashvector.py
new file mode 100644
index 0000000000..137de85fdc
--- /dev/null
+++ b/libs/langchain/tests/unit_tests/retrievers/self_query/test_dashvector.py
@@ -0,0 +1,52 @@
+from typing import Any, Tuple
+
+import pytest
+
+from langchain.chains.query_constructor.ir import (
+ Comparator,
+ Comparison,
+ Operation,
+ Operator,
+)
+from langchain.retrievers.self_query.dashvector import DashvectorTranslator
+
+DEFAULT_TRANSLATOR = DashvectorTranslator()
+
+
+ "triplet",
+ [
+ (Comparator.EQ, 2, "foo = 2"),
+ (Comparator.LT, 2, "foo < 2"),
+ (Comparator.LTE, 2, "foo <= 2"),
+ (Comparator.GT, 2, "foo > 2"),
+ (Comparator.GTE, 2, "foo >= 2"),
+ (Comparator.LIKE, "bar", "foo LIKE '%bar%'"),
+ ],
+)
+def test_visit_comparison(triplet: Tuple[Comparator, Any, str]) -> None:
+ comparator, value, expected = triplet
+ actual = DEFAULT_TRANSLATOR.visit_comparison(
+ Comparison(comparator=comparator, attribute="foo", value=value)
+ )
+ assert expected == actual
+
+
+ "triplet",
+ [
+ (Operator.AND, "foo < 2 AND bar = 'baz'"),
+ (Operator.OR, "foo < 2 OR bar = 'baz'"),
+ ],
+)
+def test_visit_operation(triplet: Tuple[Operator, str]) -> None:
+ operator, expected = triplet
+ op = Operation(
+ operator=operator,
+ arguments=[
+ Comparison(comparator=Comparator.LT, attribute="foo", value=2),
+ Comparison(comparator=Comparator.EQ, attribute="bar", value="baz"),
+ ],
+ )
+ actual = DEFAULT_TRANSLATOR.visit_operation(op)
+ assert expected == actual