|
| 1 | +import json |
| 2 | +import os |
| 3 | +from typing import Any, Callable, Dict, List, Optional |
| 4 | + |
| 5 | +from pydantic.v1 import PrivateAttr |
| 6 | +from tenacity import retry, stop_after_attempt, wait_random_exponential |
| 7 | +from tenacity.retry import retry_if_not_exception_type |
| 8 | + |
| 9 | +from redisvl.utils.vectorize.base import BaseVectorizer |
| 10 | + |
| 11 | + |
| 12 | +class BedrockTextVectorizer(BaseVectorizer): |
| 13 | + """The AmazonBedrockTextVectorizer class utilizes Amazon Bedrock's API to generate |
| 14 | + embeddings for text data. |
| 15 | +
|
| 16 | + This vectorizer is designed to interact with Amazon Bedrock API, |
| 17 | + requiring AWS credentials for authentication. The credentials can be provided |
| 18 | + directly in the `api_config` dictionary or through environment variables: |
| 19 | + - AWS_ACCESS_KEY_ID |
| 20 | + - AWS_SECRET_ACCESS_KEY |
| 21 | + - AWS_REGION (defaults to us-east-1) |
| 22 | +
|
| 23 | + The vectorizer supports synchronous operations with batch processing and |
| 24 | + preprocessing capabilities. |
| 25 | +
|
| 26 | + .. code-block:: python |
| 27 | +
|
| 28 | + # Initialize with explicit credentials |
| 29 | + vectorizer = AmazonBedrockTextVectorizer( |
| 30 | + model="amazon.titan-embed-text-v2:0", |
| 31 | + api_config={ |
| 32 | + "aws_access_key_id": "your_access_key", |
| 33 | + "aws_secret_access_key": "your_secret_key", |
| 34 | + "aws_region": "us-east-1" |
| 35 | + } |
| 36 | + ) |
| 37 | +
|
| 38 | + # Initialize using environment variables |
| 39 | + vectorizer = AmazonBedrockTextVectorizer() |
| 40 | +
|
| 41 | + # Generate embeddings |
| 42 | + embedding = vectorizer.embed("Hello, world!") |
| 43 | + embeddings = vectorizer.embed_many(["Hello", "World"], batch_size=2) |
| 44 | + """ |
| 45 | + |
| 46 | + _client: Any = PrivateAttr() |
| 47 | + |
| 48 | + def __init__( |
| 49 | + self, |
| 50 | + model: str = "amazon.titan-embed-text-v2:0", |
| 51 | + api_config: Optional[Dict[str, str]] = None, |
| 52 | + ) -> None: |
| 53 | + """Initialize the AWS Bedrock Vectorizer. |
| 54 | +
|
| 55 | + Args: |
| 56 | + model (str): The Bedrock model ID to use. Defaults to amazon.titan-embed-text-v2:0 |
| 57 | + api_config (Optional[Dict[str, str]]): AWS credentials and config. |
| 58 | + Can include: aws_access_key_id, aws_secret_access_key, aws_region |
| 59 | + If not provided, will use environment variables. |
| 60 | +
|
| 61 | + Raises: |
| 62 | + ValueError: If credentials are not provided in config or environment. |
| 63 | + ImportError: If boto3 is not installed. |
| 64 | + """ |
| 65 | + try: |
| 66 | + import boto3 # type: ignore |
| 67 | + except ImportError: |
| 68 | + raise ImportError( |
| 69 | + "Amazon Bedrock vectorizer requires boto3. " |
| 70 | + "Please install with `pip install boto3`" |
| 71 | + ) |
| 72 | + |
| 73 | + if api_config is None: |
| 74 | + api_config = {} |
| 75 | + |
| 76 | + aws_access_key_id = api_config.get( |
| 77 | + "aws_access_key_id", os.getenv("AWS_ACCESS_KEY_ID") |
| 78 | + ) |
| 79 | + aws_secret_access_key = api_config.get( |
| 80 | + "aws_secret_access_key", os.getenv("AWS_SECRET_ACCESS_KEY") |
| 81 | + ) |
| 82 | + aws_region = api_config.get("aws_region", os.getenv("AWS_REGION", "us-east-1")) |
| 83 | + |
| 84 | + if not aws_access_key_id or not aws_secret_access_key: |
| 85 | + raise ValueError( |
| 86 | + "AWS credentials required. Provide via api_config or environment variables " |
| 87 | + "AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY" |
| 88 | + ) |
| 89 | + |
| 90 | + self._client = boto3.client( |
| 91 | + "bedrock-runtime", |
| 92 | + aws_access_key_id=aws_access_key_id, |
| 93 | + aws_secret_access_key=aws_secret_access_key, |
| 94 | + region_name=aws_region, |
| 95 | + ) |
| 96 | + |
| 97 | + super().__init__(model=model, dims=self._set_model_dims(model)) |
| 98 | + |
| 99 | + def _set_model_dims(self, model: str) -> int: |
| 100 | + """Initialize model and determine embedding dimensions.""" |
| 101 | + try: |
| 102 | + response = self._client.invoke_model( |
| 103 | + modelId=model, body=json.dumps({"inputText": "dimension test"}) |
| 104 | + ) |
| 105 | + response_body = json.loads(response["body"].read()) |
| 106 | + embedding = response_body["embedding"] |
| 107 | + return len(embedding) |
| 108 | + except Exception as e: |
| 109 | + raise ValueError(f"Error initializing Bedrock model: {str(e)}") |
| 110 | + |
| 111 | + @retry( |
| 112 | + wait=wait_random_exponential(min=1, max=60), |
| 113 | + stop=stop_after_attempt(6), |
| 114 | + retry=retry_if_not_exception_type(TypeError), |
| 115 | + ) |
| 116 | + def embed( |
| 117 | + self, |
| 118 | + text: str, |
| 119 | + preprocess: Optional[Callable] = None, |
| 120 | + as_buffer: bool = False, |
| 121 | + **kwargs, |
| 122 | + ) -> List[float]: |
| 123 | + """Embed a chunk of text using Amazon Bedrock. |
| 124 | +
|
| 125 | + Args: |
| 126 | + text (str): Text to embed. |
| 127 | + preprocess (Optional[Callable]): Optional preprocessing function. |
| 128 | + as_buffer (bool): Whether to return as byte buffer. |
| 129 | +
|
| 130 | + Returns: |
| 131 | + List[float]: The embedding vector. |
| 132 | +
|
| 133 | + Raises: |
| 134 | + TypeError: If text is not a string. |
| 135 | + """ |
| 136 | + if not isinstance(text, str): |
| 137 | + raise TypeError("Text must be a string") |
| 138 | + |
| 139 | + if preprocess: |
| 140 | + text = preprocess(text) |
| 141 | + |
| 142 | + response = self._client.invoke_model( |
| 143 | + modelId=self.model, body=json.dumps({"inputText": text}) |
| 144 | + ) |
| 145 | + response_body = json.loads(response["body"].read()) |
| 146 | + embedding = response_body["embedding"] |
| 147 | + |
| 148 | + dtype = kwargs.pop("dtype", None) |
| 149 | + return self._process_embedding(embedding, as_buffer, dtype) |
| 150 | + |
| 151 | + @retry( |
| 152 | + wait=wait_random_exponential(min=1, max=60), |
| 153 | + stop=stop_after_attempt(6), |
| 154 | + retry=retry_if_not_exception_type(TypeError), |
| 155 | + ) |
| 156 | + def embed_many( |
| 157 | + self, |
| 158 | + texts: List[str], |
| 159 | + preprocess: Optional[Callable] = None, |
| 160 | + batch_size: int = 10, |
| 161 | + as_buffer: bool = False, |
| 162 | + **kwargs, |
| 163 | + ) -> List[List[float]]: |
| 164 | + """Embed multiple texts using Amazon Bedrock. |
| 165 | +
|
| 166 | + Args: |
| 167 | + texts (List[str]): List of texts to embed. |
| 168 | + preprocess (Optional[Callable]): Optional preprocessing function. |
| 169 | + batch_size (int): Size of batches for processing. |
| 170 | + as_buffer (bool): Whether to return as byte buffers. |
| 171 | +
|
| 172 | + Returns: |
| 173 | + List[List[float]]: List of embedding vectors. |
| 174 | +
|
| 175 | + Raises: |
| 176 | + TypeError: If texts is not a list of strings. |
| 177 | + """ |
| 178 | + if not isinstance(texts, list): |
| 179 | + raise TypeError("Texts must be a list of strings") |
| 180 | + if texts and not isinstance(texts[0], str): |
| 181 | + raise TypeError("Texts must be a list of strings") |
| 182 | + |
| 183 | + embeddings: List[List[float]] = [] |
| 184 | + dtype = kwargs.pop("dtype", None) |
| 185 | + |
| 186 | + for batch in self.batchify(texts, batch_size, preprocess): |
| 187 | + # Process each text in the batch individually since Bedrock |
| 188 | + # doesn't support batch embedding |
| 189 | + batch_embeddings = [] |
| 190 | + for text in batch: |
| 191 | + response = self._client.invoke_model( |
| 192 | + modelId=self.model, body=json.dumps({"inputText": text}) |
| 193 | + ) |
| 194 | + response_body = json.loads(response["body"].read()) |
| 195 | + batch_embeddings.append(response_body["embedding"]) |
| 196 | + |
| 197 | + embeddings.extend( |
| 198 | + [ |
| 199 | + self._process_embedding(embedding, as_buffer, dtype) |
| 200 | + for embedding in batch_embeddings |
| 201 | + ] |
| 202 | + ) |
| 203 | + |
| 204 | + return embeddings |
| 205 | + |
| 206 | + @property |
| 207 | + def type(self) -> str: |
| 208 | + return "bedrock" |
0 commit comments