From 9c23a121e5ced9b0ea58281cc689ab48129d2795 Mon Sep 17 00:00:00 2001 From: Tope Folorunso <66448986+topefolorunso@users.noreply.github.com> Date: Tue, 19 Sep 2023 16:18:35 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=89=20New=20Destination:=20Qdrant=20(V?= =?UTF-8?q?ector=20Database)=20(#30332)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Joe Reuter Co-authored-by: flash1293 --- .../destination-qdrant/.dockerignore | 6 + .../connectors/destination-qdrant/.gitignore | 1 + .../connectors/destination-qdrant/Dockerfile | 45 +++++ .../connectors/destination-qdrant/README.md | 123 ++++++++++++ .../destination-qdrant/build.gradle | 8 + .../destination_qdrant/__init__.py | 8 + .../destination_qdrant/config.py | 102 ++++++++++ .../destination_qdrant/destination.py | 62 ++++++ .../destination_qdrant/indexer.py | 136 +++++++++++++ .../examples/configured_catalog.json | 20 ++ .../examples/messages.jsonl | 1 + .../connectors/destination-qdrant/icon.svg | 21 +++ .../connectors/destination-qdrant/main.py | 11 ++ .../destination-qdrant/metadata.yaml | 25 +++ .../destination-qdrant/requirements.txt | 1 + .../connectors/destination-qdrant/setup.py | 23 +++ .../destination-qdrant/unit_tests/__init__.py | 0 .../unit_tests/test_destination.py | 101 ++++++++++ .../unit_tests/test_indexer.py | 178 ++++++++++++++++++ docs/integrations/destinations/qdrant.md | 73 +++++++ 20 files changed, 945 insertions(+) create mode 100644 airbyte-integrations/connectors/destination-qdrant/.dockerignore create mode 100644 airbyte-integrations/connectors/destination-qdrant/.gitignore create mode 100644 airbyte-integrations/connectors/destination-qdrant/Dockerfile create mode 100644 airbyte-integrations/connectors/destination-qdrant/README.md create mode 100644 airbyte-integrations/connectors/destination-qdrant/build.gradle create mode 100644 airbyte-integrations/connectors/destination-qdrant/destination_qdrant/__init__.py create mode 100644 airbyte-integrations/connectors/destination-qdrant/destination_qdrant/config.py create mode 100644 airbyte-integrations/connectors/destination-qdrant/destination_qdrant/destination.py create mode 100644 airbyte-integrations/connectors/destination-qdrant/destination_qdrant/indexer.py create mode 100644 airbyte-integrations/connectors/destination-qdrant/examples/configured_catalog.json create mode 100644 airbyte-integrations/connectors/destination-qdrant/examples/messages.jsonl create mode 100644 airbyte-integrations/connectors/destination-qdrant/icon.svg create mode 100644 airbyte-integrations/connectors/destination-qdrant/main.py create mode 100644 airbyte-integrations/connectors/destination-qdrant/metadata.yaml create mode 100644 airbyte-integrations/connectors/destination-qdrant/requirements.txt create mode 100644 airbyte-integrations/connectors/destination-qdrant/setup.py create mode 100644 airbyte-integrations/connectors/destination-qdrant/unit_tests/__init__.py create mode 100644 airbyte-integrations/connectors/destination-qdrant/unit_tests/test_destination.py create mode 100644 airbyte-integrations/connectors/destination-qdrant/unit_tests/test_indexer.py create mode 100644 docs/integrations/destinations/qdrant.md diff --git a/airbyte-integrations/connectors/destination-qdrant/.dockerignore b/airbyte-integrations/connectors/destination-qdrant/.dockerignore new file mode 100644 index 000000000000..b423c7670a8c --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/.dockerignore @@ -0,0 +1,6 @@ +* +!Dockerfile +!main.py +!destination_qdrant +!airbyte-cdk +!setup.py diff --git a/airbyte-integrations/connectors/destination-qdrant/.gitignore b/airbyte-integrations/connectors/destination-qdrant/.gitignore new file mode 100644 index 000000000000..ef80b1792edf --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/.gitignore @@ -0,0 +1 @@ +airbyte-cdk \ No newline at end of file diff --git a/airbyte-integrations/connectors/destination-qdrant/Dockerfile b/airbyte-integrations/connectors/destination-qdrant/Dockerfile new file mode 100644 index 000000000000..73f9c0e04ec7 --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/Dockerfile @@ -0,0 +1,45 @@ +FROM python:3.10-slim as base + +# build and load all requirements +FROM base as builder +WORKDIR /airbyte/integration_code + +RUN apt-get update \ + && pip install --upgrade pip \ + && apt-get install -y build-essential cmake g++ libffi-dev libstdc++6 + +# upgrade pip to the latest version +COPY setup.py ./ + +RUN pip install --upgrade pip + +# This is required because the current connector dependency is not compatible with the CDK version +# An older CDK version will be used, which depends on pyYAML 5.4, for which we need to pin Cython to <3.0 +# As of today the CDK version that satisfies the main dependency requirements, is 0.1.80 ... +RUN pip install --prefix=/install "Cython<3.0" "pyyaml~=5.4" --no-build-isolation + +# install necessary packages to a temporary folder +RUN pip install --prefix=/install . + +# build a clean environment +FROM base +WORKDIR /airbyte/integration_code + +# copy all loaded and built libraries to a pure basic image +COPY --from=builder /install /usr/local +# add default timezone settings +COPY --from=builder /usr/share/zoneinfo/Etc/UTC /etc/localtime +RUN echo "Etc/UTC" > /etc/timezone + +# bash is installed for more convenient debugging. +RUN apt-get install bash + +# copy payload code only +COPY main.py ./ +COPY destination_qdrant ./destination_qdrant + +ENV AIRBYTE_ENTRYPOINT "python /airbyte/integration_code/main.py" +ENTRYPOINT ["python", "/airbyte/integration_code/main.py"] + +LABEL io.airbyte.version=0.0.1 +LABEL io.airbyte.name=airbyte/destination-qdrant diff --git a/airbyte-integrations/connectors/destination-qdrant/README.md b/airbyte-integrations/connectors/destination-qdrant/README.md new file mode 100644 index 000000000000..7da001d3054f --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/README.md @@ -0,0 +1,123 @@ +# Qdrant Destination + +This is the repository for the Qdrant destination connector, written in Python. +For information about how to use this connector within Airbyte, see [the documentation](https://docs.airbyte.com/integrations/destinations/qdrant). + +## Local development + +### Prerequisites +**To iterate on this connector, make sure to complete this prerequisites section.** + +#### Minimum Python version required `= 3.10.0` + +#### Build & Activate Virtual Environment and install dependencies +From this connector directory, create a virtual environment: +``` +python -m venv .venv +``` + +This will generate a virtualenv for this module in `.venv/`. Make sure this venv is active in your +development environment of choice. To activate it from the terminal, run: +``` +source .venv/bin/activate +pip install -r requirements.txt +``` +If you are in an IDE, follow your IDE's instructions to activate the virtualenv. + +Note that while we are installing dependencies from `requirements.txt`, you should only edit `setup.py` for your dependencies. `requirements.txt` is +used for editable installs (`pip install -e`) to pull in Python dependencies from the monorepo and will call `setup.py`. +If this is mumbo jumbo to you, don't worry about it, just put your deps in `setup.py` but install using `pip install -r requirements.txt` and everything +should work as you expect. + +#### Building via Gradle +From the Airbyte repository root, run: +``` +./gradlew :airbyte-integrations:connectors:destination-qdrant:build +``` + +#### Create credentials +**If you are a community contributor**, follow the instructions in the [documentation](https://docs.airbyte.com/integrations/destinations/qdrant) +to generate the necessary credentials. Then create a file `secrets/config.json` conforming to the `destination_qdrant/spec.json` file. +Note that the `secrets` directory is gitignored by default, so there is no danger of accidentally checking in sensitive information. +See `integration_tests/sample_config.json` for a sample config file. + +**If you are an Airbyte core member**, copy the credentials in Lastpass under the secret name `destination qdrant test creds` +and place them into `secrets/config.json`. + +### Locally running the connector +``` +python main.py spec +python main.py check --config secrets/config.json +python main.py discover --config secrets/config.json +python main.py read --config secrets/config.json --catalog integration_tests/configured_catalog.json +``` + +### Locally running the connector docker image + +#### Build +First, make sure you build the latest Docker image: +``` +docker build . -t airbyte/destination-qdrant:dev +``` + +You can also build the connector image via Gradle: +``` +./gradlew :airbyte-integrations:connectors:destination-qdrant:airbyteDocker +``` +When building via Gradle, the docker image name and tag, respectively, are the values of the `io.airbyte.name` and `io.airbyte.version` `LABEL`s in +the Dockerfile. + +#### Run +Then run any of the connector commands as follows: +``` +docker run --rm airbyte/destination-qdrant:dev spec +docker run --rm -v $(pwd)/secrets:/secrets airbyte/destination-qdrant:dev check --config /secrets/config.json +# messages.jsonl is a file containing line-separated JSON representing AirbyteMessages +cat messages.jsonl | docker run --rm -v $(pwd)/secrets:/secrets -v $(pwd)/integration_tests:/integration_tests airbyte/destination-qdrant:dev write --config /secrets/config.json --catalog /integration_tests/configured_catalog.json +``` +## Testing + Make sure to familiarize yourself with [pytest test discovery](https://docs.pytest.org/en/latest/goodpractices.html#test-discovery) to know how your test files and methods should be named. +First install test dependencies into your virtual environment: +``` +pip install .[tests] +``` +### Unit Tests +To run unit tests locally, from the connector directory run: +``` +python -m pytest unit_tests +``` + +### Integration Tests +There are two types of integration tests: Acceptance Tests (Airbyte's test suite for all destination connectors) and custom integration tests (which are specific to this connector). +#### Custom Integration tests +Place custom tests inside `integration_tests/` folder, then, from the connector root, run +``` +python -m pytest integration_tests +``` +#### Acceptance Tests +Coming soon: + +### Using gradle to run tests +All commands should be run from airbyte project root. +To run unit tests: +``` +./gradlew :airbyte-integrations:connectors:destination-qdrant:unitTest +``` +To run acceptance and custom integration tests: +``` +./gradlew :airbyte-integrations:connectors:destination-qdrant:integrationTest +``` + +## Dependency Management +All of your dependencies should go in `setup.py`, NOT `requirements.txt`. The requirements file is only used to connect internal Airbyte dependencies in the monorepo for local development. +We split dependencies between two groups, dependencies that are: +* required for your connector to work need to go to `MAIN_REQUIREMENTS` list. +* required for the testing need to go to `TEST_REQUIREMENTS` list + +### Publishing a new version of the connector +You've checked out the repo, implemented a million dollar feature, and you're ready to share your changes with the world. Now what? +1. Make sure your changes are passing unit and integration tests. +1. Bump the connector version in `Dockerfile` -- just increment the value of the `LABEL io.airbyte.version` appropriately (we use [SemVer](https://semver.org/)). +1. Create a Pull Request. +1. Pat yourself on the back for being an awesome contributor. +1. Someone from Airbyte will take a look at your PR and iterate with you to merge it into master. \ No newline at end of file diff --git a/airbyte-integrations/connectors/destination-qdrant/build.gradle b/airbyte-integrations/connectors/destination-qdrant/build.gradle new file mode 100644 index 000000000000..c2ac9174fa18 --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/build.gradle @@ -0,0 +1,8 @@ +plugins { + id 'airbyte-python' + id 'airbyte-docker' +} + +airbytePython { + moduleDirectory 'destination_qdrant' +} diff --git a/airbyte-integrations/connectors/destination-qdrant/destination_qdrant/__init__.py b/airbyte-integrations/connectors/destination-qdrant/destination_qdrant/__init__.py new file mode 100644 index 000000000000..b2fe4e95b0e2 --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/destination_qdrant/__init__.py @@ -0,0 +1,8 @@ +# +# Copyright (c) 2023 Airbyte, Inc., all rights reserved. +# + + +from .destination import DestinationQdrant + +__all__ = ["DestinationQdrant"] diff --git a/airbyte-integrations/connectors/destination-qdrant/destination_qdrant/config.py b/airbyte-integrations/connectors/destination-qdrant/destination_qdrant/config.py new file mode 100644 index 000000000000..f9e3f832369f --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/destination_qdrant/config.py @@ -0,0 +1,102 @@ +# +# Copyright (c) 2023 Airbyte, Inc., all rights reserved. +# + + +import json +import re +from typing import Literal, Union + +import dpath.util +from airbyte_cdk.destinations.vector_db_based.config import ( + CohereEmbeddingConfigModel, + FakeEmbeddingConfigModel, + FromFieldEmbeddingConfigModel, + OpenAIEmbeddingConfigModel, + ProcessingConfigModel, +) +from jsonschema import RefResolver +from pydantic import BaseModel, Field + + +class NoAuth(BaseModel): + mode: Literal["no_auth"] = Field("no_auth", const=True) + + +class ApiKeyAuth(BaseModel): + mode: Literal["api_key_auth"] = Field("api_key_auth", const=True) + api_key: str = Field(..., title="API Key", description="API Key for the Qdrant instance", airbyte_secret=True) + + +class QdrantIndexingConfigModel(BaseModel): + url: str = Field(..., title="Public Endpoint", description="Public Endpoint of the Qdrant cluser", order=0) + auth_method: Union[ApiKeyAuth, NoAuth] = Field( + default="api_key_auth", + title="Authentication Method", + description="Method to authenticate with the Qdrant Instance", + discriminator="mode", + type="object", + order=1, + ) + prefer_grpc: bool = Field( + title="Prefer gRPC", description="Whether to prefer gRPC over HTTP. Set to true for Qdrant cloud clusters", default=True + ) + collection: str = Field(..., title="Collection Name", description="The collection to load data into", order=2) + distance_metric: Union[Literal["dot"], Literal["cos"], Literal["euc"]] = Field( + default="cos", + title="Distance Metric", + enum=["dot", "cos", "euc"], + description="The Distance metric used to measure similarities among vectors. This field is only used if the collection defined in the does not exist yet and is created automatically by the connector.", + ) + text_field: str = Field(title="Text Field", description="The field in the payload that contains the embedded text", default="text") + + class Config: + title = "Indexing" + schema_extra = { + "group": "Indexing", + "description": "Indexing configuration", + } + + +class ConfigModel(BaseModel): + processing: ProcessingConfigModel + embedding: Union[ + OpenAIEmbeddingConfigModel, CohereEmbeddingConfigModel, FakeEmbeddingConfigModel, FromFieldEmbeddingConfigModel + ] = Field(..., title="Embedding", description="Embedding configuration", discriminator="mode", group="embedding", type="object") + indexing: QdrantIndexingConfigModel + + class Config: + title = "Qdrant Destination Config" + schema_extra = { + "groups": [ + {"id": "processing", "title": "Processing"}, + {"id": "embedding", "title": "Embedding"}, + {"id": "indexing", "title": "Indexing"}, + ] + } + + @staticmethod + def resolve_refs(schema: dict) -> dict: + # config schemas can't contain references, so inline them + json_schema_ref_resolver = RefResolver.from_schema(schema) + str_schema = json.dumps(schema) + for ref_block in re.findall(r'{"\$ref": "#\/definitions\/.+?(?="})"}', str_schema): + ref = json.loads(ref_block)["$ref"] + str_schema = str_schema.replace(ref_block, json.dumps(json_schema_ref_resolver.resolve(ref)[1])) + pyschema: dict = json.loads(str_schema) + del pyschema["definitions"] + return pyschema + + @staticmethod + def remove_discriminator(schema: dict) -> None: + """pydantic adds "discriminator" to the schema for oneOfs, which is not treated right by the platform as we inline all references""" + dpath.util.delete(schema, "properties/*/discriminator") + dpath.util.delete(schema, "properties/**/discriminator") + + @classmethod + def schema(cls): + """we're overriding the schema classmethod to enable some post-processing""" + schema = super().schema() + schema = cls.resolve_refs(schema) + cls.remove_discriminator(schema) + return schema diff --git a/airbyte-integrations/connectors/destination-qdrant/destination_qdrant/destination.py b/airbyte-integrations/connectors/destination-qdrant/destination_qdrant/destination.py new file mode 100644 index 000000000000..59ea3eddba02 --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/destination_qdrant/destination.py @@ -0,0 +1,62 @@ +# +# Copyright (c) 2023 Airbyte, Inc., all rights reserved. +# + +from typing import Any, Iterable, Mapping + +from airbyte_cdk import AirbyteLogger +from airbyte_cdk.destinations import Destination +from airbyte_cdk.destinations.vector_db_based.embedder import CohereEmbedder, Embedder, FakeEmbedder, FromFieldEmbedder, OpenAIEmbedder +from airbyte_cdk.destinations.vector_db_based.indexer import Indexer +from airbyte_cdk.destinations.vector_db_based.writer import Writer +from airbyte_cdk.models import AirbyteConnectionStatus, AirbyteMessage, ConfiguredAirbyteCatalog, ConnectorSpecification, Status +from airbyte_cdk.models.airbyte_protocol import DestinationSyncMode +from destination_qdrant.config import ConfigModel +from destination_qdrant.indexer import QdrantIndexer + +BATCH_SIZE = 256 + +embedder_map = { + "openai": OpenAIEmbedder, + "cohere": CohereEmbedder, + "fake": FakeEmbedder, + "from_field": FromFieldEmbedder, +} + + +class DestinationQdrant(Destination): + indexer: Indexer + embedder: Embedder + + def _init_indexer(self, config: ConfigModel): + self.embedder = embedder_map[config.embedding.mode](config.embedding) + self.indexer = QdrantIndexer(config.indexing, self.embedder.embedding_dimensions) + + def write( + self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage] + ) -> Iterable[AirbyteMessage]: + + config_model = ConfigModel.parse_obj(config) + self._init_indexer(config_model) + writer = Writer(config_model.processing, self.indexer, self.embedder, batch_size=BATCH_SIZE) + yield from writer.write(configured_catalog, input_messages) + + def check(self, logger: AirbyteLogger, config: Mapping[str, Any]) -> AirbyteConnectionStatus: + + self._init_indexer(ConfigModel.parse_obj(config)) + embedder_error = self.embedder.check() + indexer_error = self.indexer.check() + errors = [error for error in [embedder_error, indexer_error] if error is not None] + if len(errors) > 0: + return AirbyteConnectionStatus(status=Status.FAILED, message="\n".join(errors)) + else: + return AirbyteConnectionStatus(status=Status.SUCCEEDED) + + def spec(self, *args: Any, **kwargs: Any) -> ConnectorSpecification: + + return ConnectorSpecification( + documentationUrl="https://docs.airbyte.com/integrations/destinations/qdrant", + supportsIncremental=True, + supported_destination_sync_modes=[DestinationSyncMode.overwrite, DestinationSyncMode.append, DestinationSyncMode.append_dedup], + connectionSpecification=ConfigModel.schema(), # type: ignore[attr-defined] + ) diff --git a/airbyte-integrations/connectors/destination-qdrant/destination_qdrant/indexer.py b/airbyte-integrations/connectors/destination-qdrant/destination_qdrant/indexer.py new file mode 100644 index 000000000000..74a8c60dceec --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/destination_qdrant/indexer.py @@ -0,0 +1,136 @@ +# +# Copyright (c) 2023 Airbyte, Inc., all rights reserved. +# + + +import uuid +from typing import List, Optional + +from airbyte_cdk.destinations.vector_db_based.document_processor import METADATA_RECORD_ID_FIELD, METADATA_STREAM_FIELD, Chunk +from airbyte_cdk.destinations.vector_db_based.indexer import Indexer +from airbyte_cdk.destinations.vector_db_based.utils import format_exception +from airbyte_cdk.models import AirbyteLogMessage, AirbyteMessage, ConfiguredAirbyteCatalog, Level, Type +from airbyte_cdk.models.airbyte_protocol import DestinationSyncMode +from destination_qdrant.config import QdrantIndexingConfigModel +from qdrant_client import QdrantClient, models +from qdrant_client.conversions.common_types import PointsSelector +from qdrant_client.models import Distance, PayloadSchemaType, VectorParams + +DISTANCE_METRIC_MAP = { + "dot": Distance.DOT, + "cos": Distance.COSINE, + "euc": Distance.EUCLID, +} + + +class QdrantIndexer(Indexer): + config: QdrantIndexingConfigModel + + def __init__(self, config: QdrantIndexingConfigModel, embedding_dimensions: int): + super().__init__(config) + self.embedding_dimensions = embedding_dimensions + + def check(self) -> Optional[str]: + auth_method_mode = self.config.auth_method.mode + if auth_method_mode == "api_key_auth" and not self.config.url.startswith("https://"): + return "Host must start with https://" + + try: + self._create_client() + + if not self._client: + return "Qdrant client is not alive." + + available_collections = [collection.name for collection in self._client.get_collections().collections] + distance_metric = DISTANCE_METRIC_MAP[self.config.distance_metric] + + if self.config.collection in available_collections: + collection_info = self._client.get_collection(collection_name=self.config.collection) + assert ( + collection_info.config.params.vectors.size == self.embedding_dimensions + ), "The collection's vector's size must match the embedding dimensions" + assert ( + collection_info.config.params.vectors.distance == distance_metric + ), "The colection's vector's distance metric must match the selected distance metric option" + else: + self._client.recreate_collection( + collection_name=self.config.collection, + vectors_config=VectorParams(size=self.embedding_dimensions, distance=distance_metric), + ) + + except Exception as e: + return format_exception(e) + finally: + if self._client: + self._client.close() + + def pre_sync(self, catalog: ConfiguredAirbyteCatalog) -> None: + self._create_client() + streams_to_overwrite = [ + stream.stream.name for stream in catalog.streams if stream.destination_sync_mode == DestinationSyncMode.overwrite + ] + if streams_to_overwrite: + self._delete_for_filter( + models.FilterSelector( + filter=models.Filter( + should=[ + models.FieldCondition(key=METADATA_STREAM_FIELD, match=models.MatchValue(value=stream)) + for stream in streams_to_overwrite + ] + ) + ) + ) + for field in [METADATA_RECORD_ID_FIELD, METADATA_STREAM_FIELD]: + self._client.create_payload_index( + collection_name=self.config.collection, field_name=field, field_schema=PayloadSchemaType.KEYWORD + ) + + def index(self, document_chunks: List[Chunk], delete_ids: List[str]) -> None: + if len(delete_ids) > 0: + self._delete_for_filter( + models.FilterSelector( + filter=models.Filter( + should=[ + models.FieldCondition(key=METADATA_RECORD_ID_FIELD, match=models.MatchValue(value=_id)) for _id in delete_ids + ] + ) + ) + ) + entities = [] + for i in range(len(document_chunks)): + chunk = document_chunks[i] + payload = chunk.metadata + payload[self.config.text_field] = chunk.page_content + entities.append( + models.Record( + id=str(uuid.uuid4()), + payload=payload, + vector=chunk.embedding, + ) + ) + self._client.upload_records(collection_name=self.config.collection, records=entities) + + def post_sync(self) -> List[AirbyteMessage]: + try: + self._client.close() + return [ + AirbyteMessage( + type=Type.LOG, log=AirbyteLogMessage(level=Level.INFO, message="Qdrant Database Client has been closed successfully") + ) + ] + except Exception as e: + return [AirbyteMessage(type=Type.LOG, log=AirbyteLogMessage(level=Level.ERROR, message=format_exception(e)))] + + def _create_client(self): + auth_method = self.config.auth_method + url = self.config.url + prefer_grpc = self.config.prefer_grpc + + if auth_method.mode == "no_auth": + self._client = QdrantClient(url=url, prefer_grpc=prefer_grpc) + elif auth_method.mode == "api_key_auth": + api_key = auth_method.api_key + self._client = QdrantClient(url=url, prefer_grpc=prefer_grpc, api_key=api_key) + + def _delete_for_filter(self, selector: PointsSelector) -> None: + self._client.delete(collection_name=self.config.collection, points_selector=selector) diff --git a/airbyte-integrations/connectors/destination-qdrant/examples/configured_catalog.json b/airbyte-integrations/connectors/destination-qdrant/examples/configured_catalog.json new file mode 100644 index 000000000000..acb931363d89 --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/examples/configured_catalog.json @@ -0,0 +1,20 @@ +{ + "streams": [ + { + "stream": { + "name": "example_stream", + "json_schema": { + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "properties": {} + }, + "supported_sync_modes": ["full_refresh", "incremental"], + "source_defined_cursor": false, + "default_cursor_field": ["column_name"] + }, + "sync_mode": "full_refresh", + "destination_sync_mode": "append_dedup", + "primary_key": [["pk"]] + } + ] +} diff --git a/airbyte-integrations/connectors/destination-qdrant/examples/messages.jsonl b/airbyte-integrations/connectors/destination-qdrant/examples/messages.jsonl new file mode 100644 index 000000000000..195d260c3ad6 --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/examples/messages.jsonl @@ -0,0 +1 @@ +{"type": "RECORD", "record": {"stream": "example_stream", "data": { "title": "valueZXXXXXXXX1", "field2": "value2", "pk": "1" }, "emitted_at": 1625383200000}} \ No newline at end of file diff --git a/airbyte-integrations/connectors/destination-qdrant/icon.svg b/airbyte-integrations/connectors/destination-qdrant/icon.svg new file mode 100644 index 000000000000..fbbf0f1d49fd --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/icon.svg @@ -0,0 +1,21 @@ + + + qdrant + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/airbyte-integrations/connectors/destination-qdrant/main.py b/airbyte-integrations/connectors/destination-qdrant/main.py new file mode 100644 index 000000000000..42c2e8492e9f --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/main.py @@ -0,0 +1,11 @@ +# +# Copyright (c) 2023 Airbyte, Inc., all rights reserved. +# + + +import sys + +from destination_qdrant import DestinationQdrant + +if __name__ == "__main__": + DestinationQdrant().run(sys.argv[1:]) diff --git a/airbyte-integrations/connectors/destination-qdrant/metadata.yaml b/airbyte-integrations/connectors/destination-qdrant/metadata.yaml new file mode 100644 index 000000000000..4dbfe0c5f87d --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/metadata.yaml @@ -0,0 +1,25 @@ +data: + registries: + cloud: + enabled: true + oss: + enabled: true + connectorSubtype: database + connectorType: destination + definitionId: 6eb1198a-6d38-43e5-aaaa-dccd8f71db2b + dockerImageTag: 0.0.1 + dockerRepository: airbyte/destination-qdrant + githubIssueLabel: destination-qdrant + icon: qdrant.svg + license: MIT + name: Qdrant + releaseDate: 2023-09-22 + releaseStage: alpha + documentationUrl: https://docs.airbyte.com/integrations/destinations/qdrant + tags: + - language:python + ab_internal: + sl: 100 + ql: 100 + supportLevel: community +metadataSpecVersion: "1.0" diff --git a/airbyte-integrations/connectors/destination-qdrant/requirements.txt b/airbyte-integrations/connectors/destination-qdrant/requirements.txt new file mode 100644 index 000000000000..d6e1198b1ab1 --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/requirements.txt @@ -0,0 +1 @@ +-e . diff --git a/airbyte-integrations/connectors/destination-qdrant/setup.py b/airbyte-integrations/connectors/destination-qdrant/setup.py new file mode 100644 index 000000000000..bf795ed43c5c --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/setup.py @@ -0,0 +1,23 @@ +# +# Copyright (c) 2023 Airbyte, Inc., all rights reserved. +# + + +from setuptools import find_packages, setup + +MAIN_REQUIREMENTS = ["airbyte-cdk[vector-db-based]", "qdrant-client", "fastembed"] + +TEST_REQUIREMENTS = ["pytest~=6.2"] + +setup( + name="destination_qdrant", + description="Destination implementation for Qdrant.", + author="Airbyte", + author_email="contact@airbyte.io", + packages=find_packages(), + install_requires=MAIN_REQUIREMENTS, + package_data={"": ["*.json"]}, + extras_require={ + "tests": TEST_REQUIREMENTS, + }, +) diff --git a/airbyte-integrations/connectors/destination-qdrant/unit_tests/__init__.py b/airbyte-integrations/connectors/destination-qdrant/unit_tests/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/airbyte-integrations/connectors/destination-qdrant/unit_tests/test_destination.py b/airbyte-integrations/connectors/destination-qdrant/unit_tests/test_destination.py new file mode 100644 index 000000000000..b47846a4f9fd --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/unit_tests/test_destination.py @@ -0,0 +1,101 @@ +# +# Copyright (c) 2023 Airbyte, Inc., all rights reserved. +# + +import unittest +from unittest.mock import MagicMock, Mock, patch + +from airbyte_cdk import AirbyteLogger +from airbyte_cdk.models import ConnectorSpecification, Status +from destination_qdrant.config import ConfigModel +from destination_qdrant.destination import DestinationQdrant, embedder_map + + +class TestDestinationQdrant(unittest.TestCase): + def setUp(self): + self.config = { + "processing": {"text_fields": ["str_col"], "metadata_fields": [], "chunk_size": 1000}, + "embedding": {"mode": "openai", "openai_key": "mykey"}, + "indexing": { + "url": "localhost:6333", + "auth_method": { + "mode": "no_auth", + }, + "prefer_grpc": False, + "collection": "dummy-collection", + "distance_metric": "dot", + "text_field": "text" + }, + } + self.config_model = ConfigModel.parse_obj(self.config) + self.logger = AirbyteLogger() + + @patch("destination_qdrant.destination.QdrantIndexer") + @patch.dict(embedder_map, openai=MagicMock()) + def test_check(self, MockedQdrantIndexer): + mock_embedder = Mock() + mock_indexer = Mock() + embedder_map["openai"].return_value = mock_embedder + MockedQdrantIndexer.return_value = mock_indexer + + mock_embedder.check.return_value = None + mock_indexer.check.return_value = None + + destination = DestinationQdrant() + result = destination.check(self.logger, self.config) + + self.assertEqual(result.status, Status.SUCCEEDED) + mock_embedder.check.assert_called_once() + mock_indexer.check.assert_called_once() + + @patch("destination_qdrant.destination.QdrantIndexer") + @patch.dict(embedder_map, openai=MagicMock()) + def test_check_with_errors(self, MockedQdrantIndexer): + mock_embedder = Mock() + mock_indexer = Mock() + embedder_map["openai"].return_value = mock_embedder + MockedQdrantIndexer.return_value = mock_indexer + + embedder_error_message = "Embedder Error" + indexer_error_message = "Indexer Error" + + mock_embedder.check.return_value = embedder_error_message + mock_indexer.check.return_value = indexer_error_message + + destination = DestinationQdrant() + result = destination.check(self.logger, self.config) + + self.assertEqual(result.status, Status.FAILED) + self.assertEqual(result.message, f"{embedder_error_message}\n{indexer_error_message}") + + mock_embedder.check.assert_called_once() + mock_indexer.check.assert_called_once() + + @patch("destination_qdrant.destination.Writer") + @patch("destination_qdrant.destination.QdrantIndexer") + @patch.dict(embedder_map, openai=MagicMock()) + def test_write(self, MockedQdrantIndexer, MockedWriter): + mock_embedder = Mock() + mock_indexer = Mock() + mock_writer = Mock() + + embedder_map["openai"].return_value = mock_embedder + MockedQdrantIndexer.return_value = mock_indexer + MockedWriter.return_value = mock_writer + + mock_writer.write.return_value = [] + + configured_catalog = MagicMock() + input_messages = [] + + destination = DestinationQdrant() + list(destination.write(self.config, configured_catalog, input_messages)) + + MockedWriter.assert_called_once_with(self.config_model.processing, mock_indexer, mock_embedder, batch_size=256) + mock_writer.write.assert_called_once_with(configured_catalog, input_messages) + + def test_spec(self): + destination = DestinationQdrant() + result = destination.spec() + + self.assertIsInstance(result, ConnectorSpecification) diff --git a/airbyte-integrations/connectors/destination-qdrant/unit_tests/test_indexer.py b/airbyte-integrations/connectors/destination-qdrant/unit_tests/test_indexer.py new file mode 100644 index 000000000000..48762f877ad9 --- /dev/null +++ b/airbyte-integrations/connectors/destination-qdrant/unit_tests/test_indexer.py @@ -0,0 +1,178 @@ +# +# Copyright (c) 2023 Airbyte, Inc., all rights reserved. +# + +import unittest +from unittest.mock import Mock, call + +from airbyte_cdk.destinations.vector_db_based.utils import format_exception +from airbyte_cdk.models.airbyte_protocol import AirbyteLogMessage, AirbyteMessage, AirbyteStream, DestinationSyncMode, Level, SyncMode, Type +from destination_qdrant.config import QdrantIndexingConfigModel +from destination_qdrant.indexer import QdrantIndexer +from qdrant_client import models + + +class TestQdrantIndexer(unittest.TestCase): + def setUp(self): + self.mock_config = QdrantIndexingConfigModel( + **{ + "url": "https://client-url.io", + "auth_method": { + "mode": "api_key_auth", + "api_key": "api_key" + }, + "prefer_grpc": False, + "collection": "dummy-collection", + "distance_metric": "dot", + "text_field": "text" + } + ) + self.qdrant_indexer = QdrantIndexer(self.mock_config, 100) + self.qdrant_indexer._create_client = Mock() + self.qdrant_indexer._client = Mock() + + def test_check_gets_existing_collection(self): + mock_collections = Mock(collections=[Mock()]) + mock_collections.collections[0].name = "dummy-collection" + self.qdrant_indexer._client.get_collections.return_value = mock_collections + + self.qdrant_indexer._client.get_collection.return_value = Mock(config=Mock(params=Mock(vectors=Mock(size=100, distance=models.Distance.DOT)))) + + check_result = self.qdrant_indexer.check() + + self.assertIsNone(check_result) + + self.qdrant_indexer._create_client.assert_called() + self.qdrant_indexer._client.get_collections.assert_called() + self.qdrant_indexer._client.get_collection.assert_called() + self.qdrant_indexer._client.close.assert_called() + + def test_check_creates_new_collection_if_not_exists(self): + self.qdrant_indexer._client.get_collections.return_value = Mock(collections=[]) + check_result = self.qdrant_indexer.check() + + self.assertIsNone(check_result) + + self.qdrant_indexer._create_client.assert_called() + self.qdrant_indexer._client.get_collections.assert_called() + self.qdrant_indexer._client.recreate_collection.assert_called() + self.qdrant_indexer._client.close.assert_called() + + def test_check_handles_failure_conditions(self): + # Test 1: url starts with https:// + self.qdrant_indexer.config.url = "client-url.io" + result = self.qdrant_indexer.check() + self.assertEqual(result, "Host must start with https://") + + # Test 2: random exception + self.qdrant_indexer.config.url = "https://client-url.io" + self.qdrant_indexer._create_client.side_effect = Exception("Random exception") + result = self.qdrant_indexer.check() + self.assertTrue("Random exception" in result) + + # Test 3: client server is not alive + self.qdrant_indexer._create_client.side_effect = None + self.qdrant_indexer._client = None + result = self.qdrant_indexer.check() + self.assertEqual(result, "Qdrant client is not alive.") + + # Test 4: Test vector size does not match + mock_collections = Mock(collections=[Mock()]) + mock_collections.collections[0].name = "dummy-collection" + + self.qdrant_indexer._client = Mock() + self.qdrant_indexer._client.get_collections.return_value = mock_collections + self.qdrant_indexer._client.get_collection.return_value = Mock(config=Mock(params=Mock(vectors=Mock(size=10, distance=models.Distance.DOT)))) + + result = self.qdrant_indexer.check() + self.assertTrue("The collection's vector's size must match the embedding dimensions" in result) + + # Test 5: Test distance metric does not match + self.qdrant_indexer._client.get_collection.return_value = Mock(config=Mock(params=Mock(vectors=Mock(size=100, distance=models.Distance.COSINE)))) + result = self.qdrant_indexer.check() + self.assertTrue("The colection's vector's distance metric must match the selected distance metric option" in result) + + def test_pre_sync_calls_delete(self): + self.qdrant_indexer.pre_sync( + Mock( + streams=[ + Mock( + destination_sync_mode=DestinationSyncMode.overwrite, + stream=AirbyteStream(name="some_stream", json_schema={}, supported_sync_modes=[SyncMode.full_refresh]), + ), + Mock( + destination_sync_mode=DestinationSyncMode.overwrite, + stream=AirbyteStream(name="another_stream", json_schema={}, supported_sync_modes=[SyncMode.full_refresh]), + ), + Mock( + destination_sync_mode=DestinationSyncMode.append, + stream=AirbyteStream(name="incremental_stream", json_schema={}, supported_sync_modes=[SyncMode.full_refresh]), + ) + ] + ) + ) + + self.qdrant_indexer._client.delete.assert_called_with( + collection_name=self.mock_config.collection, + points_selector=models.FilterSelector( + filter=models.Filter( + should=[ + models.FieldCondition(key="_ab_stream", match=models.MatchValue(value="some_stream")), + models.FieldCondition(key="_ab_stream", match=models.MatchValue(value="another_stream")) + ] + ) + )) + + def test_pre_sync_does_not_call_delete(self): + self.qdrant_indexer.pre_sync( + Mock(streams=[Mock(destination_sync_mode=DestinationSyncMode.append, stream=Mock(name="some_stream"))]) + ) + + self.qdrant_indexer._client.delete.assert_not_called() + + def test_pre_sync_calls_create_payload_index(self): + self.qdrant_indexer.pre_sync(Mock(streams=[])) + + calls = [ + call(collection_name=self.mock_config.collection, field_name="_ab_record_id", field_schema="keyword"), + call(collection_name=self.mock_config.collection, field_name="_ab_stream", field_schema="keyword") + ] + + self.qdrant_indexer._client.create_payload_index.assert_has_calls(calls) + + def test_index_calls_insert(self): + self.qdrant_indexer.index([ + Mock(metadata={"key": "value1"}, page_content="some content", embedding=[1.,2.,3.]), + Mock(metadata={"key": "value2"}, page_content="some other content", embedding=[4.,5.,6.]) + ], + [] + ) + + self.qdrant_indexer._client.upload_records.assert_called_once() + + def test_index_calls_delete(self): + self.qdrant_indexer.index([], ["some_id", "another_id"]) + + self.qdrant_indexer._client.delete.assert_called_with( + collection_name=self.mock_config.collection, + points_selector=models.FilterSelector( + filter=models.Filter( + should=[ + models.FieldCondition(key="_ab_record_id", match=models.MatchValue(value="some_id")), + models.FieldCondition(key="_ab_record_id", match=models.MatchValue(value="another_id")) + ] + ) + )) + + def test_post_sync_calls_close(self): + result = self.qdrant_indexer.post_sync() + self.qdrant_indexer._client.close.assert_called_once() + self.assertEqual(result, [AirbyteMessage(type=Type.LOG, log=AirbyteLogMessage(level=Level.INFO, message="Qdrant Database Client has been closed successfully"))]) + + def test_post_sync_handles_failure(self): + exception = Exception("Random exception") + self.qdrant_indexer._client.close.side_effect = exception + result = self.qdrant_indexer.post_sync() + + self.qdrant_indexer._client.close.assert_called_once() + self.assertEqual(result, [AirbyteMessage(type=Type.LOG, log=AirbyteLogMessage(level=Level.ERROR, message=format_exception(exception)))]) diff --git a/docs/integrations/destinations/qdrant.md b/docs/integrations/destinations/qdrant.md new file mode 100644 index 000000000000..88b731174390 --- /dev/null +++ b/docs/integrations/destinations/qdrant.md @@ -0,0 +1,73 @@ +# Qdrant +This page guides you through the process of setting up the [Qdrant](https://qdrant.tech/documentation/) destination connector. + + + +## Features + +| Feature | Supported?\(Yes/No\) | Notes | +| :----------------------------- | :------------------- | :---- | +| Full Refresh Sync | Yes | | +| Incremental - Append Sync | Yes | | +| Incremental - Append + Deduped | Yes | | + +#### Output Schema + +Only one stream will exist to collect payload and vectors (optional) from all source streams. This will be in a [collection](https://qdrant.tech/documentation/concepts/collections/) in [Qdrant](https://qdrant.tech/documentation/) whose name will be defined by the user. If the collection does not already exist in the Qdrant instance, a new collection with the same name will be created. + +For each [point](https://qdrant.tech/documentation/concepts/points/) in the collection, a UUID string is generated and used as the [point id](https://qdrant.tech/documentation/concepts/points/#point-ids). The embeddings generated as defined or extracted from the source stream will be stored as the point vectors. The point payload will contain primarily the record metadata. The text field will then be stored in a field (as defined in the config) in the point payload. + +## Getting Started + +You can connect to a Qdrant instance either in local mode or cloud mode. + - For the local mode, you will need to set it up using Docker. Check the Qdrant docs [here](https://qdrant.tech/documentation/guides/installation/#docker) for an official guide. After setting up, you would need your host, port and if applicable, your gRPC port. + - To setup to an instance in Qdrant cloud, check out [this official guide](https://qdrant.tech/documentation/cloud/) to get started. After setting up the instance, you would need the instance url and an API key to connect. + +Note that this connector does not support a local persistent mode. To test, use the docker option. + + +#### Requirements + +To use the Qdrant destination, you'll need: +- An account with API access for OpenAI, Cohere (depending on which embedding method you want to use) or neither (if you want to extract the vectors from the source stream) +- A Qdrant db instance (local mode or cloud mode) +- Qdrant API Credentials (for cloud mode) +- Host and Port (for local mode) +- gRPC port (if applicable in local mode) + +#### Configure Network Access + +Make sure your Qdrant database can be accessed by Airbyte. If your database is within a VPC, you may need to allow access from the IP you're using to expose Airbyte. + + +### Setup the Qdrant Destination in Airbyte + +You should now have all the requirements needed to configure Qdrant as a destination in the UI. You'll need the following information to configure the Qdrant destination: + +- (Required) **Text fields to embed** +- (Required) **Fields to store as metadata** +- (Required) **Collection** The name of the collection in Qdrant db to store your data +- (Required) **The field in the payload that contains the embedded text** +- (Required) **Prefer gRPC** Whether to prefer gRPC over HTTP. +- (Required) **Distance Metric** The Distance metrics used to measure similarities among vectors. Select from: + - [Dot product](https://en.wikipedia.org/wiki/Dot_product) + - [Cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity) + - [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance) +- (Required) Authentication method + - For local mode + - **Host** for example localhost + - **Port** for example 8000 + - **gRPC Port** (Optional) + - For cloud mode + - **Url** The url of the cloud Qdrant instance. + - **API Key** The API Key for the cloud Qdrant instance +- (Optional) Embedding + - **OpenAI API key** if using OpenAI for embedding + - **Cohere API key** if using Cohere for embedding + - Embedding **Field name** and **Embedding dimensions** if getting the embeddings from stream records + +## Changelog + +| Version | Date | Pull Request | Subject | +| :------ | :--------- | :--------------------------------------------------------- | :----------------------------------------- | +| 0.0.1 | 2023-09-22 | [#30332](https://github.com/airbytehq/airbyte/pull/30332) | 🎉 New Destination: Qdrant (Vector Database) | \ No newline at end of file