Skip to content

Commit

Permalink
🎉 New Destination: Qdrant (Vector Database) (#30332)
Browse files Browse the repository at this point in the history
Co-authored-by: Joe Reuter <[email protected]>
Co-authored-by: flash1293 <[email protected]>
  • Loading branch information
3 people authored Sep 19, 2023
1 parent 9081608 commit 9c23a12
Show file tree
Hide file tree
Showing 20 changed files with 945 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*
!Dockerfile
!main.py
!destination_qdrant
!airbyte-cdk
!setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
airbyte-cdk
45 changes: 45 additions & 0 deletions airbyte-integrations/connectors/destination-qdrant/Dockerfile
Original file line number Diff line number Diff line change
@@ -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
123 changes: 123 additions & 0 deletions airbyte-integrations/connectors/destination-qdrant/README.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
plugins {
id 'airbyte-python'
id 'airbyte-docker'
}

airbytePython {
moduleDirectory 'destination_qdrant'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#


from .destination import DestinationQdrant

__all__ = ["DestinationQdrant"]
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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]
)
Loading

0 comments on commit 9c23a12

Please sign in to comment.