pangwangshu commented on code in PR #40881: URL: https://github.com/apache/beam/pull/40881#discussion_r4674053239
########## sdks/python/apache_beam/ml/rag/ingestion/vespa.py: ########## @@ -0,0 +1,336 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Write EmbeddableItems to a Vespa schema. + +Example: + >>> config = VespaWriteConfig( + ... connection_params=VespaConnectionParameters( + ... url="http://localhost", port=8080), + ... schema="doc", + ... sparse_embedding_field="sparse") + >>> items | VectorDatabaseWriteTransform(config) + +The Vespa application package (schema with the target fields) must already be +deployed; this module only feeds documents. +""" + +import logging +import os +from collections.abc import Callable +from dataclasses import dataclass +from dataclasses import field +from typing import Any +from typing import Optional +from typing import Union + +try: + from vespa.application import Vespa + from vespa.io import VespaResponse +except ImportError: + logging.warning("pyvespa is not installed.") + +import apache_beam as beam +from apache_beam.ml.rag.ingestion.base import VectorDatabaseWriteConfig +from apache_beam.ml.rag.types import EmbeddableItem +from apache_beam.utils.secret import Secret + +DEFAULT_WRITE_BATCH_SIZE = 1000 +_SUPPORTED_OPERATIONS = ("put", "update") +_MAX_REPORTED_FAILURES = 5 + + +@dataclass +class VespaConnectionParameters: + """Connection settings for a Vespa container (data plane) endpoint. + + Args: + url: Endpoint URL, e.g. ``http://localhost`` or a Vespa Cloud endpoint. + port: Optional port. Leave unset when ``url`` already includes it. + cert: Path to the mTLS certificate (Vespa Cloud data plane). The file is + opened on the workers, so it must exist there (for example in a custom + container), not only on the machine that submits the job. + key: Path to the mTLS private key. Must be set together with ``cert``. + auth_token: Data-plane token for Vespa Cloud, as a string or a + :class:`~apache_beam.utils.secret.Secret`. A Secret is resolved in + ``setup()`` on each worker, so only the reference is serialized with the + pipeline; a plain string is serialized as is. Mutually exclusive with + ``cert``/``key``. + additional_headers: Extra HTTP headers sent with every request. + """ + url: str + port: Optional[int] = None + cert: Optional[str] = None + key: Optional[str] = None + auth_token: Optional[Union[str, Secret]] = None + additional_headers: dict[str, str] = field(default_factory=dict) + + def __post_init__(self): + if not self.url: + raise ValueError("url must be provided for Vespa") + if bool(self.cert) != bool(self.key): + raise ValueError("cert and key must be provided together") + if self.auth_token and self.cert: + raise ValueError("Use either mTLS (cert/key) or auth_token, not both") + + +@dataclass +class VespaWriteConfig(VectorDatabaseWriteConfig): + """Configuration for writing EmbeddableItems to Vespa. + + Field mapping (unless ``fields_fn`` is given): + - ``EmbeddableItem.id`` -> user part of ``id:<namespace>:<schema>::<id>`` + - dense embedding -> ``dense_embedding_field`` as a JSON array (short form + of an indexed tensor such as ``tensor<float>(x[384])``) + - sparse embedding -> ``sparse_embedding_field`` as ``{"<index>": value}`` + (short form of a mapped tensor such as ``tensor<float>(token{})``) + - ``content_string`` -> ``content_field`` + - metadata -> top-level fields, renamed with ``metadata_fields`` + + Every written field must exist in the deployed schema. Unlike Qdrant + payloads, Vespa rejects unknown fields with HTTP 400, which fails the bundle. + A 400 is not transient, so the runner's retries fail the same way (in + streaming the pipeline keeps retrying). Set ``metadata_fields`` when item + metadata may contain keys the schema does not define. + + Args: + connection_params: VespaConnectionParameters. + schema: Vespa schema (document type) to write to. + namespace: Document id namespace. Defaults to ``schema``. + content_field: Field for the item's content. ``None`` skips content. + dense_embedding_field: Field for the dense embedding. ``None`` skips it. + sparse_embedding_field: Field for the sparse embedding. ``None`` skips it. + metadata_fields: Mapping of metadata key -> Vespa field. Only listed keys + are written. ``None`` writes every metadata key under its own name, so + the schema must define a field for every key that can occur. + fields_fn: Optional function that builds the whole ``fields`` dict from an + item. Overrides all of the field options above. + operation_type: ``"put"`` (replaces the document) or ``"update"`` + (partial update that assigns the written fields, with ``create=true``). + batch_size: Number of documents buffered before a flush. Each flush + (including the one at the end of every bundle) opens a new connection + pool, so very small bundles pay connection setup more often. + max_queue_size, max_workers, max_connections, num_retries_429: + Passed to ``Vespa.feed_iterable``. + """ + connection_params: VespaConnectionParameters + schema: str + namespace: Optional[str] = None + content_field: Optional[str] = "content" + dense_embedding_field: Optional[str] = "embedding" + sparse_embedding_field: Optional[str] = None + metadata_fields: Optional[dict[str, str]] = None + fields_fn: Optional[Callable[[EmbeddableItem], dict[str, Any]]] = None + operation_type: str = "put" + batch_size: int = DEFAULT_WRITE_BATCH_SIZE + max_queue_size: int = 1000 + max_workers: int = 8 + max_connections: int = 16 + num_retries_429: int = 10 + + def __post_init__(self): + if not self.schema: + raise ValueError("schema must be provided") + if self.operation_type not in _SUPPORTED_OPERATIONS: + raise ValueError( + f"operation_type must be one of {_SUPPORTED_OPERATIONS}, " + f"got {self.operation_type!r}") + if self.batch_size <= 0: + raise ValueError("batch_size must be a positive integer") + for name in ("content_field", + "dense_embedding_field", + "sparse_embedding_field"): + value = getattr(self, name) + if value is not None and not value: + raise ValueError(f"{name} must be a non-empty string or None") + if self.fields_fn is None and not (self.dense_embedding_field or + self.sparse_embedding_field): + raise ValueError( + "At least one of dense_embedding_field or sparse_embedding_field " + "must be set (or provide fields_fn)") + reserved = [ + f for f in ( + self.content_field, self.dense_embedding_field, + self.sparse_embedding_field) if f + ] + if len(reserved) != len(set(reserved)): + raise ValueError( + f"content and embedding fields must be distinct, got {reserved}") + + def create_write_transform(self) -> beam.PTransform[EmbeddableItem, Any]: + return _VespaWriteTransform(self) + + def create_converter(self) -> Callable[[EmbeddableItem], dict[str, Any]]: + """Returns a function mapping an EmbeddableItem to a feed_iterable doc.""" + def convert(item: EmbeddableItem) -> dict[str, Any]: + if item.id is None or item.id == "": + raise ValueError("EmbeddableItem.id is required for Vespa") + doc_id = str(item.id) + if self.fields_fn is not None: + custom = self.fields_fn(item) + if not isinstance(custom, dict): + raise TypeError( + f"fields_fn must return a dict, got {type(custom)} " + f"for item {doc_id}") + return {"id": doc_id, "fields": custom} + + fields: dict[str, Any] = {} + wrote_embedding = False + if self.dense_embedding_field and item.dense_embedding is not None: + fields[self.dense_embedding_field] = [ + float(v) for v in item.dense_embedding + ] + wrote_embedding = True + if self.sparse_embedding_field and item.sparse_embedding is not None: + indices, values = item.sparse_embedding + if len(indices) != len(values): + raise ValueError( + f"Sparse embedding of item {doc_id} has {len(indices)} indices " + f"but {len(values)} values") + fields[self.sparse_embedding_field] = { + str(i): float(v) + for i, v in zip(indices, values) + } + wrote_embedding = True + if not wrote_embedding: + raise ValueError( + f"Item {doc_id} has no embedding for the configured fields " + f"(dense={self.dense_embedding_field!r}, " + f"sparse={self.sparse_embedding_field!r})") + if self.content_field: + fields[self.content_field] = item.content_string + + metadata = item.metadata or {} + if self.metadata_fields is None: + mapped = dict(metadata) + else: + mapped = { + vespa_field: metadata[key] + for key, vespa_field in self.metadata_fields.items() + if key in metadata + } + for vespa_field, value in mapped.items(): Review Comment: Good catch. `VespaWriteConfig` now rejects `metadata_fields` that map several keys to the same Vespa field, or to the content/embedding fields, when the config is created (3e4acef). The check is skipped when `fields_fn` is set, since the field options are ignored then. ########## sdks/python/apache_beam/ml/rag/ingestion/vespa_it_test.py: ########## @@ -0,0 +1,252 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import time +import unittest + +import pytest +import requests + +import apache_beam as beam +from apache_beam.ml.rag.types import Content +from apache_beam.ml.rag.types import EmbeddableItem +from apache_beam.ml.rag.types import Embedding +from apache_beam.testing.test_pipeline import TestPipeline + +# pylint: disable=ungrouped-imports +try: + from vespa.application import Vespa + from vespa.package import ApplicationPackage + from vespa.package import Document + from vespa.package import Field + from vespa.package import Schema + + from apache_beam.ml.rag.ingestion.vespa import VespaConnectionParameters + from apache_beam.ml.rag.ingestion.vespa import VespaWriteConfig + VESPA_AVAILABLE = True +except ImportError: + VESPA_AVAILABLE = False + +try: + from testcontainers.core.container import DockerContainer +except ImportError: + DockerContainer = None +# pylint: enable=ungrouped-imports + +VESPA_IMAGE = "vespaengine/vespa:8.763.13" +SCHEMA = "doc" +_CONTAINER_PORT = 8080 +_CONFIG_SERVER_PORT = 19071 +_STARTUP_TIMEOUT_S = 300 + + +def _application_package() -> "ApplicationPackage": + schema = Schema( + name=SCHEMA, + document=Document( + fields=[ + Field("content", "string", indexing=["index", "summary"]), + Field( + "embedding", + "tensor<float>(x[2])", + indexing=["attribute", "summary"]), + Field( + "sparse", + "tensor<float>(token{})", + indexing=["attribute", "summary"]), + Field("source", "string", indexing=["attribute", "summary"]), + ])) + return ApplicationPackage(name="beamtest", schema=[schema]) + + +def _wait_until(predicate, what: str): + deadline = time.time() + _STARTUP_TIMEOUT_S + while time.time() < deadline: + try: + if predicate(): + return + except requests.RequestException: + pass + time.sleep(2) + raise TimeoutError(f"Timed out waiting for {what}") + + +def _item(id, dense=None, sparse=None, metadata=None, text=None): + return EmbeddableItem( + id=id, + content=Content(text=text or f"content of {id}"), + metadata=metadata if metadata is not None else {"source": "test"}, + embedding=Embedding(dense_embedding=dense, sparse_embedding=sparse), + ) + + [email protected](not VESPA_AVAILABLE, "pyvespa not installed.") [email protected](not DockerContainer, "testcontainers not installed.") [email protected]_docker_in_docker Review Comment: Leaving this one as is. The Linux-only skip in `milvus_search_it_test.py` comes from Milvus-specific constraints. `vespaengine/vespa` is a normal Linux image and works through Docker Desktop/colima on macOS (the Vespa IT passes locally there in about 25s), and `qdrant_it_test.py` has no platform check either. `require_docker_in_docker` already keeps it off Beam's self-hosted runners, and the Python ML precommit runs it on `ubuntu-latest`. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
