Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.
Amazon Titan Embeddings G1 - Text
Titan Embeddings G1 - Textno admite el uso de parámetros de inferencia. En las siguientes secciones se detallan los formatos de solicitud y respuesta y se proporciona un ejemplo de código.
Solicitud y respuesta
El cuerpo de la solicitud se pasa al body
campo de una InvokeModelsolicitud.
- V2 Request
-
El parámetro inputText es obligatorio. Los parámetros de la normalización y las dimensiones son opcionales.
-
InputText: introduzca el texto para convertirlo en una incrustación.
-
normalize: (opcional) indicador que indica si se debe normalizar o no la incrustación de salida. El valor predeterminado es true (verdadero).
-
dimensiones: (opcional) el número de dimensiones que debe tener la incrustación de salida. Se aceptan los siguientes valores: 1024 (predeterminado), 512, 256.
-
embeddingTypes: (opcional) acepta una lista que contenga “float”, “binary” o ambos. El valor predeterminado es
float
.
{ "inputText": string, "dimensions": int, "normalize": boolean, "embeddingTypes": list }
-
- V2 Response
-
Los campos se describen a continuación.
-
incrustación: matriz que representa el vector de incrustación de la entrada que ha proporcionado. Siempre será del tipo
float
. -
inputTextTokenRecuento: el número de fichas de la entrada.
-
embeddingsByType — Un diccionario o un mapa de la lista de incrustaciones. Según la entrada, muestra “float”, “binary” o ambos.
-
Ejemplo:
"embeddingsByType": {"binary": [int,..], "float": [float,...]}
-
Este campo aparecerá siempre. Incluso si no especifica
embeddingTypes
en la entrada, seguirá apareciendo “float”. Ejemplo:"embeddingsByType": {"float": [float,...]}
-
{ "embedding": [float, float, ...], "inputTextTokenCount": int, "embeddingsByType": {"binary": [int,..], "float": [float,...]} }
-
- G1 Request
-
El único campo disponible es
inputText
el siguiente: en el que se puede incluir texto para convertirlo en una incrustación.{ "inputText": string }
- G1 Response
-
El
body
de la respuesta contiene los siguientes campos.{ "embedding": [float, float, ...], "inputTextTokenCount": int }
Los campos se describen a continuación.
-
incrustación: matriz que representa el vector de incrustación de la entrada que ha proporcionado.
-
inputTextTokenRecuento: el número de fichas de la entrada.
-
Código de ejemplo
Los siguientes ejemplos muestran cómo llamar a los modelos Amazon Titan Embeddings para generar incrustaciones. Seleccione la pestaña correspondiente al modelo que esté utilizando:
- Amazon Titan Embeddings G1 - Text
-
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate an embedding with the Amazon Titan Embeddings G1 - Text model (on demand). """ import json import logging import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_embedding(model_id, body): """ Generate an embedding with the vector representation of a text input using Amazon Titan Embeddings G1 - Text on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: response (JSON): The embedding created by the model and the number of input tokens. """ logger.info("Generating an embedding with Amazon Titan Embeddings G1 - Text model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get('body').read()) return response_body def main(): """ Entrypoint for Amazon Titan Embeddings G1 - Text example. """ logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = "amazon.titan-embed-text-v1" input_text = "What are the different services that you offer?" # Create request body. body = json.dumps({ "inputText": input_text, }) try: response = generate_embedding(model_id, body) print(f"Generated an embedding: {response['embedding']}") print(f"Input Token count: {response['inputTextTokenCount']}") except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) else: print(f"Finished generating an embedding with Amazon Titan Embeddings G1 - Text model {model_id}.") if __name__ == "__main__": main()
- Amazon Titan Text Embeddings V2
-
Cuando se usa Titan Text Embeddings V2, el campo
embedding
no está en la respuesta siembeddingTypes
solo contienebinary
.# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate an embedding with the Amazon Titan Text Embeddings V2 Model """ import json import logging import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_embedding(model_id, body): """ Generate an embedding with the vector representation of a text input using Amazon Titan Text Embeddings G1 on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: response (JSON): The embedding created by the model and the number of input tokens. """ logger.info("Generating an embedding with Amazon Titan Text Embeddings V2 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get('body').read()) return response_body def main(): """ Entrypoint for Amazon Titan Embeddings V2 - Text example. """ logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = "amazon.titan-embed-text-v2:0" input_text = "What are the different services that you offer?" # Create request body. body = json.dumps({ "inputText": input_text, "embeddingTypes": ["binary"] }) try: response = generate_embedding(model_id, body) print(f"Generated an embedding: {response['embeddingsByType']['binary']}") # returns binary embedding print(f"Input text: {input_text}") print(f"Input Token count: {response['inputTextTokenCount']}") except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) else: print(f"Finished generating an embedding with Amazon Titan Text Embeddings V2 model {model_id}.") if __name__ == "__main__": main()