

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Amazon Titan Embeddings G1 - Text
<a name="model-parameters-titan-embed-text"></a>

Titan Embeddings G1 - Text は、推論パラメータの使用をサポートしていません。以下のセクションでは、リクエストとレスポンスの形式を詳述し、コード例を示します。

**Topics**
+ [リクエストとレスポンス](#model-parameters-titan-embed-text-request-response)
+ [サンプルのコード](#api-inference-examples-titan-embed-text)

## リクエストとレスポンス
<a name="model-parameters-titan-embed-text-request-response"></a>

リクエスト本文は [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) リクエストの `body` フィールドに渡されます。

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

inputText パラメータは必須です。normalize および dimensions パラメータはオプションです。
+ inputText – 埋め込みに変換するテキストを入力します。
+ normalize – (オプション) 出力埋め込みを正規化するかどうかを示すフラグ。デフォルトは true です。
+ dimensions – (オプション) 出力埋め込みに必要なディメンション数。1024 (デフォルト値)、512、256 の値を使用できます。
+ embeddingTypes – (オプション) 「float」、「binary」、またはその両方を含むリストを承認します。デフォルトは `float` です。

```
{
    "inputText": string,
    "dimensions": int,
    "normalize": boolean,
    "embeddingTypes": list
}
```

------
#### [ V2 Response ]

各フィールドについて以下に説明します。
+ embedding – ユーザーが指定した入力の埋め込みベクトルを表す配列。これは常に、タイプ `float` です。
+ inputTextTokenCount – 入力内のトークン数です。
+ embeddingsByType – 埋め込みリストのディクショナリまたはマップです。入力に応じて、「float」、「binary」、またはその両方を一覧表示します。
  + 例:`"embeddingsByType": {"binary": [int,..], "float": [float,...]}`
  + このフィールドは常に表示されます。入力で `embeddingTypes` を指定しなくても、「float」は表示されます。例:`"embeddingsByType": {"float": [float,...]}`

```
{
    "embedding": [float, float, ...],
    "inputTextTokenCount": int,
    "embeddingsByType": {"binary": [int,..], "float": [float,...]}
}
```

------
#### [ G1 Request ]

使用可能なフィールドは、`inputText` のみで、このフィールドには、埋め込みに変換するテキストを入力します。

```
{
    "inputText": string
}
```

------
#### [ G1 Response ]

レスポンスの `body` には、次のフィールドが含まれます。

```
{
    "embedding": [float, float, ...],
    "inputTextTokenCount": int
}
```

各フィールドについて以下に説明します。
+ **embedding** – ユーザーが指定した入力の埋め込みベクトルを表す配列。
+ inputTextTokenCount – 入力内のトークン数です。

------

## サンプルのコード
<a name="api-inference-examples-titan-embed-text"></a>

次の例は、Amazon Titan Embeddings モデルを呼び出して埋め込みを生成する方法を説明しています。使用しているモデルに対応するタブを選択します。

------
#### [ 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 ]

Titan Text Embeddings V2 を使用する際に、`embeddingTypes` に `binary` が含まれる場合は、`embedding` フィールドはレスポンスに表示されません。

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

------