|
| 1 | +import json |
| 2 | +from dataclasses import dataclass |
| 3 | +from os import getenv |
| 4 | +from typing import Any, Dict, List, Optional, Tuple |
| 5 | + |
| 6 | +from agno.embedder.base import Embedder |
| 7 | +from agno.exceptions import AgnoError, ModelProviderError |
| 8 | +from agno.utils.log import log_error, logger |
| 9 | + |
| 10 | +try: |
| 11 | + from boto3 import client as AwsClient |
| 12 | + from boto3.session import Session |
| 13 | + from botocore.exceptions import ClientError |
| 14 | +except ImportError: |
| 15 | + log_error("`boto3` not installed. Please install it via `pip install boto3`.") |
| 16 | + raise |
| 17 | + |
| 18 | + |
| 19 | +@dataclass |
| 20 | +class AwsBedrockEmbedder(Embedder): |
| 21 | + """ |
| 22 | + AWS Bedrock embedder. |
| 23 | +
|
| 24 | + To use this embedder, you need to either: |
| 25 | + 1. Set the following environment variables: |
| 26 | + - AWS_ACCESS_KEY_ID |
| 27 | + - AWS_SECRET_ACCESS_KEY |
| 28 | + - AWS_REGION |
| 29 | + 2. Or provide a boto3 Session object |
| 30 | +
|
| 31 | + Args: |
| 32 | + id (str): The model ID to use. Default is 'cohere.embed-multilingual-v3'. |
| 33 | + dimensions (Optional[int]): The dimensions of the embeddings. Default is 1024. |
| 34 | + input_type (str): Prepends special tokens to differentiate types. Options: |
| 35 | + 'search_document', 'search_query', 'classification', 'clustering'. Default is 'search_query'. |
| 36 | + truncate (Optional[str]): How to handle inputs longer than the maximum token length. |
| 37 | + Options: 'NONE', 'START', 'END'. Default is 'NONE'. |
| 38 | + embedding_types (Optional[List[str]]): Types of embeddings to return. Options: |
| 39 | + 'float', 'int8', 'uint8', 'binary', 'ubinary'. Default is ['float']. |
| 40 | + aws_region (Optional[str]): The AWS region to use. |
| 41 | + aws_access_key_id (Optional[str]): The AWS access key ID to use. |
| 42 | + aws_secret_access_key (Optional[str]): The AWS secret access key to use. |
| 43 | + session (Optional[Session]): A boto3 Session object to use for authentication. |
| 44 | + request_params (Optional[Dict[str, Any]]): Additional parameters to pass to the API requests. |
| 45 | + client_params (Optional[Dict[str, Any]]): Additional parameters to pass to the boto3 client. |
| 46 | + """ |
| 47 | + |
| 48 | + id: str = "cohere.embed-multilingual-v3" |
| 49 | + dimensions: int = 1024 # Cohere models have 1024 dimensions by default |
| 50 | + input_type: str = "search_query" |
| 51 | + truncate: Optional[str] = None # 'NONE', 'START', or 'END' |
| 52 | + # 'float', 'int8', 'uint8', etc. |
| 53 | + embedding_types: Optional[List[str]] = None |
| 54 | + |
| 55 | + aws_region: Optional[str] = None |
| 56 | + aws_access_key_id: Optional[str] = None |
| 57 | + aws_secret_access_key: Optional[str] = None |
| 58 | + session: Optional[Session] = None |
| 59 | + |
| 60 | + request_params: Optional[Dict[str, Any]] = None |
| 61 | + client_params: Optional[Dict[str, Any]] = None |
| 62 | + client: Optional[AwsClient] = None |
| 63 | + |
| 64 | + def get_client(self) -> AwsClient: |
| 65 | + """ |
| 66 | + Returns an AWS Bedrock client. |
| 67 | +
|
| 68 | + Returns: |
| 69 | + AwsClient: An instance of the AWS Bedrock client. |
| 70 | + """ |
| 71 | + if self.client is not None: |
| 72 | + return self.client |
| 73 | + |
| 74 | + if self.session: |
| 75 | + self.client = self.session.client("bedrock-runtime") |
| 76 | + return self.client |
| 77 | + |
| 78 | + self.aws_access_key_id = self.aws_access_key_id or getenv("AWS_ACCESS_KEY_ID") |
| 79 | + self.aws_secret_access_key = self.aws_secret_access_key or getenv("AWS_SECRET_ACCESS_KEY") |
| 80 | + self.aws_region = self.aws_region or getenv("AWS_REGION") |
| 81 | + |
| 82 | + if not self.aws_access_key_id or not self.aws_secret_access_key: |
| 83 | + raise AgnoError( |
| 84 | + message="AWS credentials not found. Please set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables or provide a boto3 session.", |
| 85 | + status_code=400, |
| 86 | + ) |
| 87 | + |
| 88 | + self.client = AwsClient( |
| 89 | + service_name="bedrock-runtime", |
| 90 | + region_name=self.aws_region, |
| 91 | + aws_access_key_id=self.aws_access_key_id, |
| 92 | + aws_secret_access_key=self.aws_secret_access_key, |
| 93 | + **(self.client_params or {}), |
| 94 | + ) |
| 95 | + return self.client |
| 96 | + |
| 97 | + def _format_request_body(self, text: str) -> str: |
| 98 | + """ |
| 99 | + Format the request body for the embedder. |
| 100 | +
|
| 101 | + Args: |
| 102 | + text (str): The text to embed. |
| 103 | +
|
| 104 | + Returns: |
| 105 | + str: The formatted request body as a JSON string. |
| 106 | + """ |
| 107 | + request_body = { |
| 108 | + "texts": [text], |
| 109 | + "input_type": self.input_type, |
| 110 | + } |
| 111 | + |
| 112 | + if self.truncate: |
| 113 | + request_body["truncate"] = self.truncate |
| 114 | + |
| 115 | + if self.embedding_types: |
| 116 | + request_body["embedding_types"] = self.embedding_types |
| 117 | + |
| 118 | + # Add additional request parameters if provided |
| 119 | + if self.request_params: |
| 120 | + request_body.update(self.request_params) |
| 121 | + |
| 122 | + return json.dumps(request_body) |
| 123 | + |
| 124 | + def response(self, text: str) -> Dict[str, Any]: |
| 125 | + """ |
| 126 | + Get embeddings from AWS Bedrock for the given text. |
| 127 | +
|
| 128 | + Args: |
| 129 | + text (str): The text to embed. |
| 130 | +
|
| 131 | + Returns: |
| 132 | + Dict[str, Any]: The response from the API. |
| 133 | + """ |
| 134 | + try: |
| 135 | + body = self._format_request_body(text) |
| 136 | + response = self.get_client().invoke_model( |
| 137 | + modelId=self.id, |
| 138 | + body=body, |
| 139 | + contentType="application/json", |
| 140 | + accept="application/json", |
| 141 | + ) |
| 142 | + response_body = json.loads(response["body"].read().decode("utf-8")) |
| 143 | + return response_body |
| 144 | + except ClientError as e: |
| 145 | + log_error(f"Unexpected error calling Bedrock API: {str(e)}") |
| 146 | + raise ModelProviderError(message=str(e.response), model_name="AwsBedrockEmbedder", model_id=self.id) from e |
| 147 | + except Exception as e: |
| 148 | + log_error(f"Unexpected error calling Bedrock API: {str(e)}") |
| 149 | + raise ModelProviderError(message=str(e), model_name="AwsBedrockEmbedder", model_id=self.id) from e |
| 150 | + |
| 151 | + def get_embedding(self, text: str) -> List[float]: |
| 152 | + """ |
| 153 | + Get embeddings for the given text. |
| 154 | +
|
| 155 | + Args: |
| 156 | + text (str): The text to embed. |
| 157 | +
|
| 158 | + Returns: |
| 159 | + List[float]: The embedding vector. |
| 160 | + """ |
| 161 | + response = self.response(text=text) |
| 162 | + try: |
| 163 | + # Check if response contains embeddings or embeddings by type |
| 164 | + if "embeddings" in response: |
| 165 | + if isinstance(response["embeddings"], list): |
| 166 | + # Default 'float' embeddings response format |
| 167 | + return response["embeddings"][0] |
| 168 | + elif isinstance(response["embeddings"], dict): |
| 169 | + # If embeddings_types parameter was used, select float embeddings |
| 170 | + if "float" in response["embeddings"]: |
| 171 | + return response["embeddings"]["float"][0] |
| 172 | + # Fallback to the first available embedding type |
| 173 | + for embedding_type in response["embeddings"]: |
| 174 | + return response["embeddings"][embedding_type][0] |
| 175 | + logger.warning("No embeddings found in response") |
| 176 | + return [] |
| 177 | + except Exception as e: |
| 178 | + logger.warning(f"Error extracting embeddings: {e}") |
| 179 | + return [] |
| 180 | + |
| 181 | + def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict[str, Any]]]: |
| 182 | + """ |
| 183 | + Get embeddings and usage information for the given text. |
| 184 | +
|
| 185 | + Args: |
| 186 | + text (str): The text to embed. |
| 187 | +
|
| 188 | + Returns: |
| 189 | + Tuple[List[float], Optional[Dict[str, Any]]]: The embedding vector and usage information. |
| 190 | + """ |
| 191 | + response = self.response(text=text) |
| 192 | + |
| 193 | + embedding: List[float] = [] |
| 194 | + # Extract embeddings |
| 195 | + if "embeddings" in response: |
| 196 | + if isinstance(response["embeddings"], list): |
| 197 | + embedding = response["embeddings"][0] |
| 198 | + elif isinstance(response["embeddings"], dict): |
| 199 | + if "float" in response["embeddings"]: |
| 200 | + embedding = response["embeddings"]["float"][0] |
| 201 | + # Fallback to the first available embedding type |
| 202 | + else: |
| 203 | + for embedding_type in response["embeddings"]: |
| 204 | + embedding = response["embeddings"][embedding_type][0] |
| 205 | + break |
| 206 | + |
| 207 | + # Extract usage metrics if available |
| 208 | + usage = None |
| 209 | + if "usage" in response: |
| 210 | + usage = response["usage"] |
| 211 | + |
| 212 | + return embedding, usage |
0 commit comments