|
| 1 | +from typing import Callable, Dict, List, Optional |
| 2 | + |
| 3 | +from tenacity import retry, stop_after_attempt, wait_random_exponential |
| 4 | +from tenacity.retry import retry_if_not_exception_type |
| 5 | + |
| 6 | +from redisvl.vectorize.base import BaseVectorizer |
| 7 | + |
| 8 | + |
| 9 | +class VertexAITextVectorizer(BaseVectorizer): |
| 10 | + """VertexAI text vectorizer |
| 11 | +
|
| 12 | + This vectorizer uses the VertexAI Palm 2 embedding model API to create embeddings for text. It requires an |
| 13 | + active GCP project, location, and application credentials. |
| 14 | + """ |
| 15 | + |
| 16 | + def __init__( |
| 17 | + self, model: str = "textembedding-gecko", api_config: Optional[Dict] = None |
| 18 | + ): |
| 19 | + """Initialize the VertexAI vectorizer. |
| 20 | +
|
| 21 | + Args: |
| 22 | + model (str): Model to use for embedding. |
| 23 | + api_config (Optional[Dict], optional): Dictionary containing the API key. |
| 24 | + Defaults to None. |
| 25 | +
|
| 26 | + Raises: |
| 27 | + ImportError: If the google-cloud-aiplatform library is not installed. |
| 28 | + ValueError: If the API key is not provided. |
| 29 | + """ |
| 30 | + super().__init__(model) |
| 31 | + |
| 32 | + if ( |
| 33 | + not api_config |
| 34 | + or "project_id" not in api_config |
| 35 | + or "location" not in api_config |
| 36 | + ): |
| 37 | + raise ValueError( |
| 38 | + "GCP project id and valid location are required in the api_config" |
| 39 | + ) |
| 40 | + |
| 41 | + try: |
| 42 | + import vertexai |
| 43 | + from vertexai.preview.language_models import TextEmbeddingModel |
| 44 | + |
| 45 | + vertexai.init( |
| 46 | + project=api_config["project_id"], location=api_config["location"] |
| 47 | + ) |
| 48 | + except ImportError: |
| 49 | + raise ImportError( |
| 50 | + "VertexAI vectorizer requires the google-cloud-aiplatform library." |
| 51 | + "Please install with pip install google-cloud-aiplatform>=1.26" |
| 52 | + ) |
| 53 | + |
| 54 | + self._model_client = TextEmbeddingModel.from_pretrained(model) |
| 55 | + self._dims = self._set_model_dims() |
| 56 | + |
| 57 | + def _set_model_dims(self) -> int: |
| 58 | + try: |
| 59 | + embedding = self._model_client.get_embeddings(["dimension test"])[0].values |
| 60 | + except (KeyError, IndexError) as ke: |
| 61 | + raise ValueError(f"Unexpected response from the VertexAI API: {str(ke)}") |
| 62 | + except Exception as e: # pylint: disable=broad-except |
| 63 | + # fall back (TODO get more specific) |
| 64 | + raise ValueError(f"Error setting embedding model dimensions: {str(e)}") |
| 65 | + return len(embedding) |
| 66 | + |
| 67 | + @retry( |
| 68 | + wait=wait_random_exponential(min=1, max=60), |
| 69 | + stop=stop_after_attempt(6), |
| 70 | + retry=retry_if_not_exception_type(TypeError), |
| 71 | + ) |
| 72 | + def embed_many( |
| 73 | + self, |
| 74 | + texts: List[str], |
| 75 | + preprocess: Optional[Callable] = None, |
| 76 | + batch_size: int = 10, |
| 77 | + as_buffer: bool = False, |
| 78 | + ) -> List[List[float]]: |
| 79 | + """Embed many chunks of texts using the VertexAI API. |
| 80 | +
|
| 81 | + Args: |
| 82 | + texts (List[str]): List of text chunks to embed. |
| 83 | + preprocess (Optional[Callable], optional): Optional preprocessing callable to |
| 84 | + perform before vectorization. Defaults to None. |
| 85 | + batch_size (int, optional): Batch size of texts to use when creating |
| 86 | + embeddings. Defaults to 10. |
| 87 | + as_buffer (bool, optional): Whether to convert the raw embedding |
| 88 | + to a byte string. Defaults to False. |
| 89 | +
|
| 90 | + Returns: |
| 91 | + List[List[float]]: List of embeddings. |
| 92 | +
|
| 93 | + Raises: |
| 94 | + TypeError: If the wrong input type is passed in for the test. |
| 95 | + """ |
| 96 | + if not isinstance(texts, list): |
| 97 | + raise TypeError("Must pass in a list of str values to embed.") |
| 98 | + if len(texts) > 0 and not isinstance(texts[0], str): |
| 99 | + raise TypeError("Must pass in a list of str values to embed.") |
| 100 | + |
| 101 | + embeddings: List = [] |
| 102 | + for batch in self.batchify(texts, batch_size, preprocess): |
| 103 | + response = self._model_client.get_embeddings(batch) |
| 104 | + embeddings += [ |
| 105 | + self._process_embedding(r.values, as_buffer) for r in response |
| 106 | + ] |
| 107 | + return embeddings |
| 108 | + |
| 109 | + @retry( |
| 110 | + wait=wait_random_exponential(min=1, max=60), |
| 111 | + stop=stop_after_attempt(6), |
| 112 | + retry=retry_if_not_exception_type(TypeError), |
| 113 | + ) |
| 114 | + def embed( |
| 115 | + self, |
| 116 | + text: str, |
| 117 | + preprocess: Optional[Callable] = None, |
| 118 | + as_buffer: bool = False, |
| 119 | + ) -> List[float]: |
| 120 | + """Embed a chunk of text using the VertexAI API. |
| 121 | +
|
| 122 | + Args: |
| 123 | + text (str): Chunk of text to embed. |
| 124 | + preprocess (Optional[Callable], optional): Optional preprocessing callable to |
| 125 | + perform before vectorization. Defaults to None. |
| 126 | + as_buffer (bool, optional): Whether to convert the raw embedding |
| 127 | + to a byte string. Defaults to False. |
| 128 | +
|
| 129 | + Returns: |
| 130 | + List[float]: Embedding. |
| 131 | +
|
| 132 | + Raises: |
| 133 | + TypeError: If the wrong input type is passed in for the test. |
| 134 | + """ |
| 135 | + if not isinstance(text, str): |
| 136 | + raise TypeError("Must pass in a str value to embed.") |
| 137 | + |
| 138 | + if preprocess: |
| 139 | + text = preprocess(text) |
| 140 | + result = self._model_client.get_embeddings([text]) |
| 141 | + return self._process_embedding(result[0].values, as_buffer) |
0 commit comments