

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
<a name="model-parameters-titan-embed-text"></a>

Titan Embeddings G1 - Text no 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.

**Topics**
+ [Solicitud y respuesta](#model-parameters-titan-embed-text-request-response)
+ [Código de ejemplo](#api-inference-examples-titan-embed-text)

## Solicitud y respuesta
<a name="model-parameters-titan-embed-text-request-response"></a>

El cuerpo de la solicitud se pasa al campo `body` de una solicitud [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html). 

------
#### [ V2 Request ]

El parámetro inputText es obligatorio. Los parámetros de la normalización y las dimensiones son opcionales.
+ inputText: introduzca texto para convertirlo en una incrustación.
+ normalize (opcional): indicador que especifica si se debe normalizar o no la incrustación de salida. El valor predeterminado es true (verdadero).
+ dimensions (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.
+ embedding: matriz que representa el vector de incrustación de la entrada que ha proporcionado. Siempre será del tipo `float`.
+ inputTextTokenCount: número de tokens de la entrada.
+ embeddingsByType: diccionario o 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` y en él 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.
+ **embedding**: matriz que representa el vector de incrustación de la entrada que ha proporcionado.
+ **inputTextTokenCount**: número de tokens de la entrada.

------

## Código de ejemplo
<a name="api-inference-examples-titan-embed-text"></a>

Los siguientes ejemplos muestran cómo llamar a los modelos de incrustación de Amazon Titan 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 si `embeddingTypes` solo contiene `binary`. 

```
# 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()
```

------