Skip to content

The agent engineering platform.

community[minor]: Add SelfQueryRetriever support to PGVector (#16991)

Junyoung Park1ed73f199230
diff --git a/docs/docs/integrations/retrievers/self_query/pgvector_self_query.ipynb b/docs/docs/integrations/retrievers/self_query/pgvector_self_query.ipynb
new file mode 100644
index 0000000000..b647510936
--- /dev/null
+++ b/docs/docs/integrations/retrievers/self_query/pgvector_self_query.ipynb
@@ -0,0 +1,308 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "13afcae7",
+ "metadata": {},
+ "source": [
+ "# PGVector\n",
+ "\n",
+ ">[PGVector](https://github.com/pgvector/pgvector) is a vector similarity search for Postgres.\n",
+ "\n",
+ "In the notebook, we'll demo the `SelfQueryRetriever` wrapped around a `PGVector` vector store."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "68e75fb9",
+ "metadata": {},
+ "source": [
+ "## Creating a PGVector vector store\n",
+ "First we'll want to create a PGVector vector store 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 `` package."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "63a8af5b",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "%pip install --upgrade --quiet lark pgvector psycopg2-binary"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "83811610-7df3-4ede-b268-68a6a83ba9e2",
+ "metadata": {},
+ "source": [
+ "We want to use `OpenAIEmbeddings` so we have to get the OpenAI API Key."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "dd01b61b-7d32-4a55-85d6-b2d2d4f18840",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "import getpass\n",
+ "import os\n",
+ "\n",
+ "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "cb4a5787",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "from langchain.schema import Document\n",
+ "from langchain_community.vectorstores import PGVector\n",
+ "from langchain_openai import OpenAIEmbeddings\n",
+ "\n",
+ "collection = \"Name of your collection\"\n",
+ "embeddings = OpenAIEmbeddings()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bcbe04d9",
+ "metadata": {
+ "tags": []
+ },
+ "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\": \"science fiction\"},\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 = PGVector.from_documents(\n",
+ " docs,\n",
+ " embeddings,\n",
+ " collection_name=collection,\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5ecaab6d",
+ "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": 6,
+ "id": "86e34dbf",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "from langchain.chains.query_constructor.base import AttributeInfo\n",
+ "from langchain.retrievers.self_query.base import SelfQueryRetriever\n",
+ "from langchain_openai import OpenAI\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 = OpenAI(temperature=0)\n",
+ "retriever = SelfQueryRetriever.from_llm(\n",
+ " llm, vectorstore, document_content_description, metadata_field_info, verbose=True\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ea9df8d4",
+ "metadata": {},
+ "source": [
+ "## Testing it out\n",
+ "And now we can try actually using our retriever!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "38a126e9",
+ "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,
+ "id": "fc3f1e6e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This example only specifies a filter\n",
+ "retriever.get_relevant_documents(\"I want to watch a movie rated higher than 8.5\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b19d4da0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This example specifies a query and a filter\n",
+ "retriever.get_relevant_documents(\"Has Greta Gerwig directed any movies about women\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f900e40e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This example specifies a composite filter\n",
+ "retriever.get_relevant_documents(\n",
+ " \"What's a highly rated (above 8.5) science fiction film?\"\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "12a51522",
+ "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 toys, and preferably is animated\"\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "39bd1de1-b9fe-4a98-89da-58d8a7a6ae51",
+ "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": 7,
+ "id": "bff36b88-b506-4877-9c63-e5a1a8d78e64",
+ "metadata": {
+ "tags": []
+ },
+ "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",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2758d229-4f97-499c-819f-888acaf8ee10",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "# This example only specifies a relevant query\n",
+ "retriever.get_relevant_documents(\"what are two movies about dinosaurs\")"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "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.9.16"
+ }
+ },
+ "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 9c6a584a6e..d54120ccfc 100644
--- a/libs/langchain/langchain/retrievers/self_query/base.py
+++ b/libs/langchain/langchain/retrievers/self_query/base.py
@@ -12,6 +12,7 @@ from langchain_community.vectorstores import (
MongoDBAtlasVectorSearch,
MyScale,
OpenSearchVectorSearch,
+ PGVector,
Pinecone,
Qdrant,
Redis,
@@ -43,6 +44,7 @@ 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.pgvector import PGVectorTranslator
from langchain.retrievers.self_query.pinecone import PineconeTranslator
from langchain.retrievers.self_query.qdrant import QdrantTranslator
from langchain.retrievers.self_query.redis import RedisTranslator
@@ -58,6 +60,7 @@ def _get_builtin_translator(vectorstore: VectorStore) -> Visitor:
"""Get the translator class corresponding to the vector store class."""
BUILTIN_TRANSLATORS: Dict[Type[VectorStore], Type[Visitor]] = {
AstraDB: AstraDBTranslator,
+ PGVector: PGVectorTranslator,
Pinecone: PineconeTranslator,
Chroma: ChromaTranslator,
DashVector: DashvectorTranslator,
diff --git a/libs/langchain/langchain/retrievers/self_query/pgvector.py b/libs/langchain/langchain/retrievers/self_query/pgvector.py
new file mode 100644
index 0000000000..ebe5bf42ff
--- /dev/null
+++ b/libs/langchain/langchain/retrievers/self_query/pgvector.py
@@ -0,0 +1,52 @@
+from typing import Dict, Tuple, Union
+
+from langchain.chains.query_constructor.ir import (
+ Comparator,
+ Comparison,
+ Operation,
+ Operator,
+ StructuredQuery,
+ Visitor,
+)
+
+
+class PGVectorTranslator(Visitor):
+ """Translate `PGVector` internal query language elements to valid filters."""
+
+ allowed_operators = [Operator.AND, Operator.OR]
+ """Subset of allowed logical operators."""
+ allowed_comparators = [
+ Comparator.EQ,
+ Comparator.NE,
+ Comparator.GT,
+ Comparator.LT,
+ Comparator.IN,
+ Comparator.NIN,
+ Comparator.CONTAIN,
+ Comparator.LIKE,
+ ]
+ """Subset of allowed logical comparators."""
+
+ def _format_func(self, func: Union[Operator, Comparator]) -> str:
+ self._validate_func(func)
+ return f"{func.value}"
+
+ 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:
+ return {
+ comparison.attribute: {
+ self._format_func(comparison.comparator): comparison.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/tests/unit_tests/retrievers/self_query/test_pgvector.py b/libs/langchain/tests/unit_tests/retrievers/self_query/test_pgvector.py
new file mode 100644
index 0000000000..451508bdab
--- /dev/null
+++ b/libs/langchain/tests/unit_tests/retrievers/self_query/test_pgvector.py
@@ -0,0 +1,87 @@
+from typing import Dict, Tuple
+
+import pytest as pytest
+
+from langchain.chains.query_constructor.ir import (
+ Comparator,
+ Comparison,
+ Operation,
+ Operator,
+ StructuredQuery,
+)
+from langchain.retrievers.self_query.pgvector import PGVectorTranslator
+
+DEFAULT_TRANSLATOR = PGVectorTranslator()
+
+
+def test_visit_comparison() -> None:
+ comp = Comparison(comparator=Comparator.LT, attribute="foo", value=1)
+ expected = {"foo": {"lt": 1}}
+ actual = DEFAULT_TRANSLATOR.visit_comparison(comp)
+ assert expected == actual
+
+
[email protected]("Not implemented")
+def test_visit_operation() -> None:
+ op = Operation(
+ operator=Operator.AND,
+ arguments=[
+ Comparison(comparator=Comparator.LT, attribute="foo", value=2),
+ Comparison(comparator=Comparator.EQ, attribute="bar", value="baz"),
+ Comparison(comparator=Comparator.GT, attribute="abc", value=2.0),
+ ],
+ )
+ expected = {
+ "foo": {"lt": 2},
+ "bar": {"eq": "baz"},
+ "abc": {"gt": 2.0},
+ }
+ actual = DEFAULT_TRANSLATOR.visit_operation(op)
+ assert expected == actual
+
+
+def test_visit_structured_query() -> 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
+
+ comp = Comparison(comparator=Comparator.LT, attribute="foo", value=1)
+ structured_query = StructuredQuery(
+ query=query,
+ filter=comp,
+ )
+ expected = (query, {"filter": {"foo": {"lt": 1}}})
+ actual = DEFAULT_TRANSLATOR.visit_structured_query(structured_query)
+ assert expected == actual
+
+ op = Operation(
+ operator=Operator.AND,
+ arguments=[
+ Comparison(comparator=Comparator.LT, attribute="foo", value=2),
+ Comparison(comparator=Comparator.EQ, attribute="bar", value="baz"),
+ Comparison(comparator=Comparator.GT, attribute="abc", value=2.0),
+ ],
+ )
+ structured_query = StructuredQuery(
+ query=query,
+ filter=op,
+ )
+ expected = (
+ query,
+ {
+ "filter": {
+ "and": [
+ {"foo": {"lt": 2}},
+ {"bar": {"eq": "baz"}},
+ {"abc": {"gt": 2.0}},
+ ]
+ }
+ },
+ )
+ actual = DEFAULT_TRANSLATOR.visit_structured_query(structured_query)
+ assert expected == actual