

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

# Amazon Titan モデル
<a name="model-parameters-titan"></a>

このセクションでは、Amazon Titan モデルのリクエストパラメータとレスポンスフィールドについて説明します。この情報を使用して、[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) および [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html) (ストリーミング) オペレーションで Amazon Titan モデルへの推論を実行します。このセクションでは、Amazon Titan モデルを呼び出す方法を示す Python コード例も含まれています。推論オペレーションでモデルを使用するには、そのモデルのモデル ID が必要です。モデル ID を取得するには、「[Amazon Bedrock でサポートされている基盤モデル](models-supported.md)」を参照してください。モデルによっては、[Converse API](conversation-inference.md) でも動作します。Converse API が特定の Amazon Titan モデルをサポートしているかどうかを確認するには、「[サポートされているモデルとモデルの機能](conversation-inference-supported-models-features.md)」を参照してください。コード例については、「[AWS SDKsコード例](service_code_examples.md)」を参照してください。

Amazon Bedrock の基盤モデルは、モデルごとに異なる入出力モダリティをサポートしています。Amazon Titan モデルがサポートするモダリティを確認するには、「[Amazon Bedrock でサポートされている基盤モデル](models-supported.md)」を参照してください。Amazon Titan モデルがサポートする Amazon Bedrock 機能を確認するには、「[Amazon Bedrock でサポートされている基盤モデル](models-supported.md)」を参照してください。Amazon Titan モデルが使用可能な AWS リージョンを確認するには、「[Amazon Bedrock でサポートされている基盤モデル](models-supported.md)」を参照してください。

Amazon Titan モデルで推論呼び出しを行う場合は、モデルのプロンプトを含めます。Amazon Bedrock がサポートするモデルのプロンプト作成に関する一般情報については、「[プロンプトエンジニアリングの概念](prompt-engineering-guidelines.md)」を参照してください。

**Topics**
+ [Amazon Titan Text モデル](model-parameters-titan-text.md)
+ [Amazon Titan Image Generator G1 モデル](model-parameters-titan-image.md)
+ [Amazon Titan Embeddings G1 - Text](model-parameters-titan-embed-text.md)
+ [Amazon Titan Multimodal Embeddings G1](model-parameters-titan-embed-mm.md)

# Amazon Titan Text モデル
<a name="model-parameters-titan-text"></a>

Amazon Titan Text モデルでは、以下の推論パラメータをサポートしています。

Titan Text プロンプトエンジニアリングガイドラインの詳細については、「[Titan プロンプトエンジニアリングガイドライン](https://d2eo22ngex1n9g.cloudfront.net/Documentation/User+Guides/Titan/Amazon+Titan+Text+Prompt+Engineering+Guidelines.pdf)」を参照してください。

Titan モデルの詳細については、「[Amazon Titan モデルの概要](titan-models.md)」を参照してください。

**Topics**
+ [リクエストとレスポンス](#model-parameters-titan-request-response)
+ [コードの例](#inference-titan-code)

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

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

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

```
{
    "inputText": string,
    "textGenerationConfig": {
        "temperature": float,  
        "topP": float,
        "maxTokenCount": int,
        "stopSequences": [string]
    }
}
```

以下のパラメータは必須です。
+ **inputText** — レスポンスを生成するためにモデルに提供される入力。会話形式でレスポンスを生成するには、次の形式でプロンプトを送信します。

  ```
  "inputText": "User: <theUserPrompt>\nBot:"
  ```

  この形式は、ユーザーがプロンプトを提供した後に、モデルが新しい行で応答する必要があることを示します。

`textGenerationConfig` はオプションです。次の[推論パラメータ](inference-parameters.md)を使用して設定します。
+ **temperature** – 低い値を指定すると、レスポンスのランダム性が軽減されます。  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-titan-text.html)
+ **topP** – 低い値を指定すると、可能性の低い選択肢が無視され、レスポンスの多様性が低下します。  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-titan-text.html)
+ **maxTokenCount** – レスポンス内で生成するトークンの最大数を指定します。トークン上限は厳密に適用されます。  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-titan-text.html)
+ **stopSequences** – モデルを停止する場所を示す文字シーケンスを指定します。

------
#### [ InvokeModel Response ]

```
{
    "inputTextTokenCount": int,
    "results": [{
        "tokenCount": int,
        "outputText": "\n<response>\n",
        "completionReason": "string"
    }]
}
```

レスポンス本文には次のフィールドが含まれています。
+ **inputTextTokenCount** – プロンプト内のトークン数です。
+ **results** – 1 つの項目の配列。次のフィールドを含むオブジェクトです。
  + **tokenCount** – レスポンス内のトークン数です。
  + **outputText** – レスポンス内のテキストです。
  + **completionReason** – レスポンスの生成が終了した理由です。理由の候補としては、以下があります。
    + FINISHED – レスポンスが完全に生成されました。
    + LENGTH – 設定したレスポンスの長さに基づきレスポンスが切り捨てられました。
    + STOP\$1CRITERIA\$1MET – 停止基準に達したため、レスポンスレスポンスが切り捨てられました。
    + RAG\$1QUERY\$1WHEN\$1RAG\$1DISABLED – この機能は無効になっており、クエリを完了でませんでした。
    + CONTENT\$1FILTERED – 適用されたコンテンツフィルターによってコンテンツがフィルタリングまたは削除されました。

------
#### [ InvokeModelWithResponseStream Response ]

レスポンスストリーム本文内のテキストの各チャンクは以下の形式となります。`bytes` フィールドをデコードする必要があります (例については「[InvokeModel で 1 つのプロンプトを送信する](inference-invoke.md)」を参照)。

```
{
    "chunk": {
        "bytes": b'{
            "index": int,
            "inputTextTokenCount": int,
            "totalOutputTextTokenCount": int,
            "outputText": "<response-chunk>",
            "completionReason": "string"
        }'
    }
}
```
+ **index** – ストリーミングレスポンスのチャンクのインデックスです。
+ **inputTextTokenCount** – プロンプト内のトークン数です。
+ **totalOutputTextTokenCount** – レスポンス内のトークン数です。
+ **outputText** – レスポンス内のテキストです。
+ **completionReason** – レスポンスの生成が終了した理由です。理由の候補としては、以下があります。
  + FINISHED – レスポンスが完全に生成されました。
  + LENGTH – 設定したレスポンスの長さに基づきレスポンスが切り捨てられました。
  + STOP\$1CRITERIA\$1MET – 停止基準に達したため、レスポンスレスポンスが切り捨てられました。
  + RAG\$1QUERY\$1WHEN\$1RAG\$1DISABLED – この機能は無効になっており、クエリを完了でませんでした。
  + CONTENT\$1FILTERED – 適用されたフィルターによってコンテンツがフィルタリングまたは削除されました。

------

## コードの例
<a name="inference-titan-code"></a>

次の例は、Python SDK を使用して Amazon Titan Text Premier モデルで推論を実行する方法を示しています。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to create a list of action items from a meeting transcript
with the Amazon Titan Text model (on demand).
"""
import json
import logging
import boto3

from botocore.exceptions import ClientError


class ImageError(Exception):
    "Custom exception for errors returned by Amazon Titan Text models"

    def __init__(self, message):
        self.message = message


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_text(model_id, body):
    """
    Generate text using Amazon Titan Text models on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        response (json): The response from the model.
    """

    logger.info(
        "Generating text with Amazon Titan 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())

    finish_reason = response_body.get("error")

    if finish_reason is not None:
        raise ImageError(f"Text generation error. Error is {finish_reason}")

    logger.info(
        "Successfully generated text with Amazon Titan Text model %s", model_id)

    return response_body


def main():
    """
    Entrypoint for Amazon Titan Text model example.
    """
    try:
        logging.basicConfig(level=logging.INFO,
                            format="%(levelname)s: %(message)s")

        # You can replace the model_id with any other Titan Text Models
        # Titan Text Model family model_id is as mentioned below:
        # amazon.titan-text-premier-v1:0, amazon.titan-text-express-v1, amazon.titan-text-lite-v1
        model_id = 'amazon.titan-text-premier-v1:0'

        prompt = """Meeting transcript: Miguel: Hi Brant, I want to discuss the workstream  
            for our new product launch Brant: Sure Miguel, is there anything in particular you want
            to discuss? Miguel: Yes, I want to talk about how users enter into the product.
            Brant: Ok, in that case let me add in Namita. Namita: Hey everyone 
            Brant: Hi Namita, Miguel wants to discuss how users enter into the product.
            Miguel: its too complicated and we should remove friction.  
            for example, why do I need to fill out additional forms?  
            I also find it difficult to find where to access the product
            when I first land on the landing page. Brant: I would also add that
            I think there are too many steps. Namita: Ok, I can work on the
            landing page to make the product more discoverable but brant
            can you work on the additonal forms? Brant: Yes but I would need 
            to work with James from another team as he needs to unblock the sign up workflow.
            Miguel can you document any other concerns so that I can discuss with James only once?
            Miguel: Sure.
            From the meeting transcript above, Create a list of action items for each person. """

        body = json.dumps({
            "inputText": prompt,
            "textGenerationConfig": {
                "maxTokenCount": 3072,
                "stopSequences": [],
                "temperature": 0.7,
                "topP": 0.9
            }
        })

        response_body = generate_text(model_id, body)
        print(f"Input token count: {response_body['inputTextTokenCount']}")

        for result in response_body['results']:
            print(f"Token count: {result['tokenCount']}")
            print(f"Output text: {result['outputText']}")
            print(f"Completion reason: {result['completionReason']}")

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))
    except ImageError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(
            f"Finished generating text with the Amazon Titan Text Premier model {model_id}.")


if __name__ == "__main__":
    main()
```

次の例は、Python SDK を使用して Amazon Titan Text G1 - Express モデルで推論を実行する方法を示しています。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to create a list of action items from a meeting transcript
with the Amazon &titan-text-express; model (on demand).
"""
import json
import logging
import boto3

from botocore.exceptions import ClientError


class ImageError(Exception):
    "Custom exception for errors returned by Amazon &titan-text-express; model"

    def __init__(self, message):
        self.message = message


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_text(model_id, body):
    """
    Generate text using Amazon &titan-text-express; model on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        response (json): The response from the model.
    """

    logger.info(
        "Generating text with Amazon &titan-text-express; 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())

    finish_reason = response_body.get("error")

    if finish_reason is not None:
        raise ImageError(f"Text generation error. Error is {finish_reason}")

    logger.info(
        "Successfully generated text with Amazon &titan-text-express; model %s", model_id)

    return response_body


def main():
    """
    Entrypoint for Amazon &titan-text-express; example.
    """
    try:
        logging.basicConfig(level=logging.INFO,
                            format="%(levelname)s: %(message)s")

        model_id = 'amazon.titan-text-express-v1'

        prompt = """Meeting transcript: Miguel: Hi Brant, I want to discuss the workstream  
            for our new product launch Brant: Sure Miguel, is there anything in particular you want
            to discuss? Miguel: Yes, I want to talk about how users enter into the product.
            Brant: Ok, in that case let me add in Namita. Namita: Hey everyone 
            Brant: Hi Namita, Miguel wants to discuss how users enter into the product.
            Miguel: its too complicated and we should remove friction.  
            for example, why do I need to fill out additional forms?  
            I also find it difficult to find where to access the product
            when I first land on the landing page. Brant: I would also add that
            I think there are too many steps. Namita: Ok, I can work on the
            landing page to make the product more discoverable but brant
            can you work on the additonal forms? Brant: Yes but I would need 
            to work with James from another team as he needs to unblock the sign up workflow.
            Miguel can you document any other concerns so that I can discuss with James only once?
            Miguel: Sure.
            From the meeting transcript above, Create a list of action items for each person. """

        body = json.dumps({
            "inputText": prompt,
            "textGenerationConfig": {
                "maxTokenCount": 4096,
                "stopSequences": [],
                "temperature": 0,
                "topP": 1
            }
        })

        response_body = generate_text(model_id, body)
        print(f"Input token count: {response_body['inputTextTokenCount']}")

        for result in response_body['results']:
            print(f"Token count: {result['tokenCount']}")
            print(f"Output text: {result['outputText']}")
            print(f"Completion reason: {result['completionReason']}")

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))
    except ImageError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(
            f"Finished generating text with the Amazon &titan-text-express; model {model_id}.")


if __name__ == "__main__":
    main()
```

# Amazon Titan Image Generator G1 モデル
<a name="model-parameters-titan-image"></a>

Amazon Titan Image Generator G1 V1 および Titan Image Generator G1 V2 モデルは、モデル推論を実行する際に、次の推論パラメータとモデルレスポンスをサポートします。

**Topics**
+ [推論パラメータ](#model-parameters-titan-image-api)
+ [例](#model-parameters-titan-image-code-examples)

## 推論パラメータ
<a name="model-parameters-titan-image-api"></a>

Amazon Titan Image Generator モデルを使用して、[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) を呼び出す場合は、リクエストの `body` フィールドをユースケースに合った形式に置き換えます。すべてのタスクは `imageGenerationConfig` オブジェクトを共有しますが、各タスクにはそのタスク固有のパラメータオブジェクトがあります。次のユースケースがサポートされています。


****  

| taskType | タスクパラメータフィールド | タスクの種類 | 定義 | 
| --- | --- | --- | --- | 
| TEXT\$1IMAGE | textToImageParams | Generation |  テキストプロンプトを使用して画像を生成します。  | 
| TEXT\$1IMAGE | textToImageParams | Generation |  (Image conditioning-V2 のみ) 追加の入力条件イメージとテキストプロンプトを指定し、条件イメージのレイアウトと構造に従ったイメージを生成します。  | 
| INPAINTING | inPaintingParams | 編集 |  **周囲の背景に合わせてマスクの内側を変更して画像を変更します。  | 
| OUTPAINTING | outPaintingParams | 編集 | マスクで定義された領域をシームレスに拡張して画像を変更します。 | 
| IMAGE\$1VARIATION | imageVariationParams | 編集 | 元の画像のバリエーションを作成して画像を変更します。 | 
| COLOR\$1GUIDED\$1GENERATION (V2 only) | colorGuidedGenerationParams | Generation | 16 進色コードのリストとテキストプロンプトを指定して、カラーパレットに従ったイメージを生成します。 | 
| BACKGROUND\$1REMOVAL (V2 only) | backgroundRemovalParams | 編集 | 複数のオブジェクトを識別して背景を削除し、透明な背景でイメージを出力して、イメージを変更します。 | 

編集タスクでは、入力時に `image` フィールドを指定する必要があります。このフィールドは、画像内のピクセルを定義する文字列で構成されます。各ピクセルは 0～255 の範囲の 3 つの RGB チャンネルで定義されます (例えば、(255 255 0) は黄色を表します)。これらのチャンネルは Base64 でエンコードされます。

使用する画像は、JPEG または PNG 形式である必要があります。

インペインティングやアウトペインティングを行う場合は*マスク*、つまり修正する画像の一部を定義する 1 つまたは複数の領域も定義します。次の 2 つの方法のいずれかでマスクを定義できます。
+ `maskPrompt` — 画像のマスク対象部分を説明するテキストプロンプトを記述します。
+ `maskImage` — 入力画像内の各ピクセルに (0 0 0) または (255 255 255) とマークして、マスクされた領域を定義する、Base64 でエンコードされた文字列を入力します。
  + (0 0 0) と定義されたピクセルは、マスクの内側のピクセルです。
  + (255 255 255) と定義されたピクセルは、マスクの外側のピクセルです。

  写真編集ツールを使用すると、マスクを描画できます。その後、出力された JPEG または PNG 画像を Base64 エンコーディングに変換して、このフィールドに入力できます。それ以外の場合は、代わりに `maskPrompt` フィールドを使用してモデルにマスクの推測を許可します。

以下のタブを選択して、さまざまな画像生成のユースケースの API リクエスト本文とフィールドの説明を確認してください。

------
#### [ Text-to-image generation (Request) ]

イメージを生成するテキストプロンプトは 512 文字以下である必要があります。解像度の長辺は 1,408 以下です。negativeText (オプション) – 512 文字以下のイメージに含めない内容を定義するテキストプロンプト。すべての解像度のリストは、以下の表を参照してください。

```
{
    "taskType": "TEXT_IMAGE",
    "textToImageParams": {
        "text": "string",      
        "negativeText": "string"
    },
    "imageGenerationConfig": {
        "quality": "standard" | "premium",
        "numberOfImages": int,
        "height": int,
        "width": int,
        "cfgScale": float,
        "seed": int
    }
}
```

`textToImageParams` フィールドについて以下に説明します。
+ **text** (必須) — 画像を生成するためのテキストプロンプト。
+ **negativeText** (オプション) — 画像に含めない内容を定義するテキストプロンプト。
**注記**  
`negativeText` プロンプトには否定語を使わないでください。例えば、画像に鏡を含めない場合は、`negativeText` プロンプトに「**mirrors**」と入力します。**no mirrors** とは入力しないでください。

------
#### [ Inpainting (Request) ]

text (オプション) — マスクの内側の変更内容を定義するテキストプロンプト。このフィールドを含めないと、モデルはマスク領域全体の背景への置き換えを試行します。512 文字以下である必要があります。negativeText (オプション) – イメージに含めない内容を定義するテキストプロンプト。512 文字以下である必要があります。入力イメージと入力マスクのサイズ制限は、イメージの長辺では 1,408 以下です。出力サイズは入力サイズと同じです。

```
{
    "taskType": "INPAINTING",
    "inPaintingParams": {
        "image": "base64-encoded string",                         
        "text": "string",
        "negativeText": "string",        
        "maskPrompt": "string",                      
        "maskImage": "base64-encoded string",   
        "returnMask": boolean # False by default                
    },                                                 
    "imageGenerationConfig": {
        "quality": "standard" | "premium",
        "numberOfImages": int,
        "height": int,
        "width": int,
        "cfgScale": float
    }
}
```

`inPaintingParams` フィールドについて以下に説明します。**マスクは画像の中で修正する部分を定義します。
+ **image** (必須) — 修正対象の JPEG または PNG 画像。ピクセルのシーケンスを指定する文字列としてフォーマットされ、それぞれが RGB 値で定義されて、base64 でエンコードされます。画像を Base64 にエンコードし、Base64 でエンコードされた文字列をデコードして画像に変換する方法の例については、[コード例](#model-parameters-titan-image-code-examples)を参照してください。
+ 定義するには、次のいずれかのフィールド (両方ではない) を定義する必要があります。
  + **maskPrompt** — マスクを定義するテキストプロンプト。
  + **maskImage** — `image` と同じサイズのピクセルのシーケンスを指定してマスクを定義する文字列。各ピクセルは (0 0 0) (マスクの内側のピクセル) または (255 255 255) (マスクの外側のピクセル) の RGB 値に変換されます。画像を Base64 にエンコードし、Base64 でエンコードされた文字列をデコードして画像に変換する方法の例については、[コード例](#model-parameters-titan-image-code-examples)を参照してください。
+ **text** (オプション) — マスクの内側の変更内容を定義するテキストプロンプト。このフィールドを含めないと、モデルはマスク領域全体の背景への置き換えを試行します。
+ **negativeText** (オプション) — 画像に含めない内容を定義するテキストプロンプト。
**注記**  
`negativeText` プロンプトには否定語を使わないでください。例えば、画像に鏡を含めない場合は、`negativeText` プロンプトに「**mirrors**」と入力します。**no mirrors** とは入力しないでください。

------
#### [ Outpainting (Request) ]

text (必須) — マスクの外側の変更内容を定義するテキストプロンプト。512 文字以下である必要があります。negativeText (オプション) – イメージに含めない内容を定義するテキストプロンプト。512 文字以下である必要があります。入力イメージと入力マスクのサイズ制限は、イメージの長辺では 1,408 以下です。出力サイズは入力サイズと同じです。

```
{
    "taskType": "OUTPAINTING",
    "outPaintingParams": {
        "text": "string",
        "negativeText": "string",        
        "image": "base64-encoded string",                         
        "maskPrompt": "string",                      
        "maskImage": "base64-encoded string",    
        "returnMask": boolean, # False by default                                         
        "outPaintingMode": "DEFAULT | PRECISE"                 
    },                                                 
    "imageGenerationConfig": {
        "quality": "standard" | "premium",
        "numberOfImages": int,
        "height": int,
        "width": int,
        "cfgScale": float
    }
}
```

`outPaintingParams` フィールドについて以下に説明します。*マスク*は画像の中で修正しない領域を定義します。生成では、定義する領域がシームレスに拡張されます。
+ **image** (必須) — 修正対象の JPEG または PNG 画像。ピクセルのシーケンスを指定する文字列としてフォーマットされ、それぞれが RGB 値で定義されて、base64 でエンコードされます。画像を Base64 にエンコードし、Base64 でエンコードされた文字列をデコードして画像に変換する方法の例については、[コード例](#model-parameters-titan-image-code-examples)を参照してください。
+ 定義するには、次のいずれかのフィールド (両方ではない) を定義する必要があります。
  + **maskPrompt** — マスクを定義するテキストプロンプト。
  + **maskImage** — `image` と同じサイズのピクセルのシーケンスを指定してマスクを定義する文字列。各ピクセルは (0 0 0) (マスクの内側のピクセル) または (255 255 255) (マスクの外側のピクセル) の RGB 値に変換されます。画像を Base64 にエンコードし、Base64 でエンコードされた文字列をデコードして画像に変換する方法の例については、[コード例](#model-parameters-titan-image-code-examples)を参照してください。
+ **text** (必須) — マスクの外側の変更内容を定義するテキストプロンプト。
+ **negativeText** (オプション) — 画像に含めない内容を定義するテキストプロンプト。
**注記**  
`negativeText` プロンプトには否定語を使わないでください。例えば、画像に鏡を含めない場合は、`negativeText` プロンプトに「**mirrors**」と入力します。**no mirrors** とは入力しないでください。
+ **outPaintingMode** — マスクの内側のピクセルの変更を許可するかどうかを指定します。以下の値を指定できます。
  + DEFAULT — このオプションを使用すると、再構成された背景との一貫性を保つために、マスクの内側の画像を変更できます。
  + PRECISE — このオプションを使用すると、マスクの内側の画像は変更されません。

------
#### [ Image variation (Request) ]

イメージバリエーションを使用すると、パラメータ値に基づいて、元イメージのバリエーションを作成できます。入力イメージのサイズ制限は、イメージの長辺では 1,408 以下です。すべての解像度のリストは、以下の表を参照してください。
+ text (オプション) — 画像の内側の保存する内容と変更する内容を定義できるテキストプロンプト。512 文字以下である必要があります。
+ negativeText (オプション) — 画像に含めない内容を定義するテキストプロンプト。512 文字以下である必要があります。
+ text (オプション) — 画像の内側の保存する内容と変更する内容を定義できるテキストプロンプト。512 文字以下である必要があります。
+ similarityStrength (オプション) – 生成されたイメージを入力イメージにどの程度類似させるかを指定します (小さい値を使用して生成にランダム性を追加します)。許容範囲は 0.2～1.0 (両方を含む) ですが、このパラメータがリクエストにない場合、デフォルトの 0.7 が使用されます。

```
{
     "taskType": "IMAGE_VARIATION",
     "imageVariationParams": {
         "text": "string",
         "negativeText": "string",
         "images": ["base64-encoded string"],
         "similarityStrength": 0.7,  # Range: 0.2 to 1.0
     },
     "imageGenerationConfig": {
         "quality": "standard" | "premium",
         "numberOfImages": int,
         "height": int,
         "width": int,
         "cfgScale": float
     }
}
```

`imageVariationParams` フィールドについて以下に説明します。
+ **images** (必須) — バリエーションを生成する画像のリスト。1～5 個の画像を含めることができます。イメージは base64 でエンコードされたイメージ文字列として定義されます。イメージを Base64 にエンコードし、Base64 でエンコードされた文字列をデコードしてイメージに変換する方法の例については、「[コード例](#model-parameters-titan-image-code-examples)」を参照してください。
+ **text** (オプション) — 画像の内側の保存する内容と変更する内容を定義できるテキストプロンプト。
+ **similarityStrength** (オプション) – 生成された画像を入力画像 (複数可) にどの程度類似させるかを指定します。許容範囲は 0.2～1.0 です。低い値を使用するとランダム性が強くなります。
+ **negativeText** (オプション) — 画像に含めない内容を定義するテキストプロンプト。
**注記**  
`negativeText` プロンプトには否定語を使わないでください。例えば、画像に鏡を含めない場合は、`negativeText` プロンプトに「**mirrors**」と入力します。**no mirrors** とは入力しないでください。

------
#### [ Conditioned Image Generation (Request) V2 only ]

条件付きイメージ生成タスクタイプを使用すると、「条件付きイメージ」を指定してテキストからイメージへの生成を強化し、生成されたイメージをよりきめ細かく制御できます。
+ Canny エッジ検出
+ セグメンテーションマップ

イメージを生成するテキストプロンプトは 512 文字以下である必要があります。解像度の長辺は 1,408 以下です。negativeText (オプション) – 512 文字以下のイメージに含めない内容を定義するテキストプロンプト。すべての解像度のリストは、以下の表を参照してください。

```
{
    "taskType": "TEXT_IMAGE",
    "textToImageParams": {
        "text": "string",      
        "negativeText": "string",
        "conditionImage": "base64-encoded string", # [OPTIONAL] base64 encoded image
        "controlMode": "string", # [OPTIONAL] CANNY_EDGE | SEGMENTATION. DEFAULT: CANNY_EDGE
        "controlStrength": float # [OPTIONAL] weight given to the condition image. DEFAULT: 0.7
    },
    "imageGenerationConfig": {
        "quality": "standard" | "premium",
        "numberOfImages": int,
        "height": int,
        "width": int,
        "cfgScale": float,
        "seed": int
    }
}
```
+ **text** (必須) — 画像を生成するためのテキストプロンプト。
+ **negativeText** (オプション) — 画像に含めない内容を定義するテキストプロンプト。
**注記**  
`negativeText` プロンプトには否定語を使わないでください。例えば、画像に鏡を含めない場合は、`negativeText` プロンプトに「**mirrors**」と入力します。**no mirrors** とは入力しないでください。
+ **conditionImage** (Optional-V2 のみ) – 生成された画像のレイアウトと構成をガイドする単一の入力条件イメージ。イメージは base64 でエンコードされたイメージ文字列として定義されます。イメージを Base64 にエンコードし、Base64 でエンコードされた文字列をデコードして画像に変換する方法の例。
+ **controlMode** (Optional-V2 のみ) — コンディショニングモードのタイプを使用するかどうかを指定します。CANNY\$1EDGE と SEGMENTATION の 2 種類のコンディショニングモードがサポートされています。デフォルト値は CANNY\$1EDGE です。
+ **controlStrength** (Optional-V2 のみ) – 生成されたイメージのレイアウトと構成を conditioningImage とどの程度類似させるかを指定します。許容範囲は 0～1.0 です。低い値を使用するとランダム性が強くなります。デフォルト値は 0.7 です。

**注記**  
controlMode または controlStrength が指定されている場合は、conditionImage も指定する必要があります。

------
#### [ Color Guided Content (Request) V2 only ]

16 進色コードのリストとテキストプロンプトを指定して、カラーパレットに従ったイメージを生成します。イメージを生成するテキストプロンプトは 512 文字以下である必要があります。最大解像度は、長辺で 1,408 です。生成されたイメージに色を指定するには 1～10 の 16 進色コードのリストが必要です。何をイメージに含めないかを定義する negativeText Optional A テキストプロンプトは、512 文字以下にする必要があります。referenceImage optional は、生成イメージ内のカラーパレットをガイドする追加のリファレンスイメージです。ユーザーがアップロードした RGB リファレンスイメージのサイズ制限は、長辺で 1,408 以下です。

```
{
    "taskType": "COLOR_GUIDED_GENERATION",
    "colorGuidedGenerationParams": {
        "text": "string",      
        "negativeText": "string",
        "referenceImage" "base64-encoded string", # [OPTIONAL]
        "colors": ["string"] # list of color hex codes
    },
    "imageGenerationConfig": {
        "quality": "standard" | "premium",
        "numberOfImages": int,
        "height": int,
        "width": int,
        "cfgScale": float,
        "seed": int
    }
}
```

次に、colorGuidedGenerationParams フィールドについて説明します。このパラメータは V2 専用であることに注意してください。
+ **text** (必須) — 画像を生成するためのテキストプロンプト。
+ **colors** (必須) – 生成されたイメージの色を指定する最大 10 の 16 進色コードのリスト。
+ **negativeText** (オプション) — 画像に含めない内容を定義するテキストプロンプト。
**注記**  
`negativeText` プロンプトには否定語を使わないでください。例えば、画像に鏡を含めない場合は、`negativeText` プロンプトに「**mirrors**」と入力します。**no mirrors** とは入力しないでください。
+ **referenceImage** (オプション) – 生成されたイメージのカラーパレットをガイドする単一の入力リファレンスイメージ。イメージは base64 でエンコードされたイメージ文字列として定義されます。

------
#### [ Background Removal (Request) ]

バックグラウンド削除タスクタイプは、入力イメージ内の複数のオブジェクトを自動的に識別し、バックグラウンドを削除します。出力画像の背景は透明です。

**リクエストの形式**

```
{
    "taskType": "BACKGROUND_REMOVAL",
    "backgroundRemovalParams": {
        "image": "base64-encoded string"
    }
}
```

**レスポンスの形式**

```
{
  "images": [
    "base64-encoded string", 
    ...
  ],
  "error": "string" 
}
```

次に、backgroundRemovalParams フィールドについて説明します。
+ **image** (必須) — 修正対象の JPEG または PNG 画像。ピクセルのシーケンスを指定する文字列としてフォーマットされ、それぞれが RGB 値で定義されて、base64 でエンコードされます。

------
#### [ Response body ]

```
{
  "images": [
    "base64-encoded string", 
    ...
  ],
  "error": "string" 
}
```

レスポンスの本文は、以下のフィールドのいずれかを含むストリーミングオブジェクトです。
+ `images` — リクエストが正常に終了すると、それぞれが生成画像を定義する base64 エンコード後の文字列のリストであるこのフィールドが返されます。各画像は、ピクセルのシーケンスを指定する文字列としてフォーマットされ、それぞれが RGB 値で定義され、base64 でエンコードされます。画像を Base64 にエンコードし、Base64 でエンコードされた文字列をデコードして画像に変換する方法の例については、[コード例](#model-parameters-titan-image-code-examples)を参照してください。
+ `error` — 以下の状況のいずれかでリクエストがコンテンツモデレーションポリシーに違反すると、このフィールドにメッセージが返されます。
  + 入力テキスト、画像、またはマスク画像がコンテンツモデレーションポリシーによってフラグ付けされている場合。
  + 少なくとも 1 つの出力画像がコンテンツモデレーションポリシーによってフラグ付けされている場合

------

共有およびオプションの `imageGenerationConfig` には、次のフィールドが含まれています。このオブジェクトを含めない場合は、デフォルト設定が使用されます。
+ **quality** – ・画像の品質。デフォルト値は `standard` です。料金の詳細については、「[Amazon Bedrock の料金](https://aws.amazon.com/bedrock/pricing/)」を参照してください。
+ **numberOfImages** (オプション) — 生成する画像の数。  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-titan-image.html)
+ **cfgScale** (オプション) — 生成された画像がプロンプトに従う程度を指定します。低い値を使用すると、生成時のランダム性が高くなります。  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-titan-image.html)
+ 以下のパラメータは、出力画像に必要なサイズを定義します。画像サイズ別の料金の詳細については、「[Amazon Bedrock の料金](https://aws.amazon.com/bedrock/pricing/)」を参照してください。
  + **height** (オプション) - 画像の高さ (ピクセル単位)。デフォルト値は 1408 です。
  + **width** (オプション) - 画像の幅 (ピクセル単位)。デフォルト値は 1408 です。

  以下のサイズが許容されます。  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-titan-image.html)
+ **seed** (オプション) — 結果の制御と再現に使用します。初期ノイズ設定を指定します。前回の実行と同じシードと設定を使用して推論を行えば、類似の画像を作成できます。  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/bedrock/latest/userguide/model-parameters-titan-image.html)

## 例
<a name="model-parameters-titan-image-code-examples"></a>

以下の例は、Python SDK でオンデマンドスループットの Amazon Titan Image Generator モデルを呼び出す方法を示しています。各ユースケースの例を表示するには、タブを選択してください。各例の最後に画像が表示されます。

------
#### [ Text-to-image generation ]

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate an image from a text prompt with the Amazon Titan Image Generator G1 model (on demand).
"""
import base64
import io
import json
import logging
import boto3
from PIL import Image

from botocore.exceptions import ClientError


class ImageError(Exception):
    "Custom exception for errors returned by Amazon Titan Image Generator G1"

    def __init__(self, message):
        self.message = message


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_image(model_id, body):
    """
    Generate an image using Amazon Titan Image Generator G1 model on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        image_bytes (bytes): The image generated by the model.
    """

    logger.info(
        "Generating image with Amazon Titan Image Generator G1 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())

    base64_image = response_body.get("images")[0]
    base64_bytes = base64_image.encode('ascii')
    image_bytes = base64.b64decode(base64_bytes)

    finish_reason = response_body.get("error")

    if finish_reason is not None:
        raise ImageError(f"Image generation error. Error is {finish_reason}")

    logger.info(
        "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id)

    return image_bytes


def main():
    """
    Entrypoint for Amazon Titan Image Generator G1 example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    model_id = 'amazon.titan-image-generator-v1'

    prompt = """A photograph of a cup of coffee from the side."""

    body = json.dumps({
        "taskType": "TEXT_IMAGE",
        "textToImageParams": {
            "text": prompt
        },
        "imageGenerationConfig": {
            "numberOfImages": 1,
            "height": 1024,
            "width": 1024,
            "cfgScale": 8.0,
            "seed": 0
        }
    })

    try:
        image_bytes = generate_image(model_id=model_id,
                                     body=body)
        image = Image.open(io.BytesIO(image_bytes))
        image.show()

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))
    except ImageError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(
            f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.")


if __name__ == "__main__":
    main()
```

------
#### [ Inpainting ]

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to use inpainting to generate an image from a source image with 
the Amazon Titan Image Generator G1 model (on demand).
The example uses a mask prompt to specify the area to inpaint.
"""
import base64
import io
import json
import logging
import boto3
from PIL import Image

from botocore.exceptions import ClientError


class ImageError(Exception):
    "Custom exception for errors returned by Amazon Titan Image Generator G1"

    def __init__(self, message):
        self.message = message


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_image(model_id, body):
    """
    Generate an image using Amazon Titan Image Generator G1 model on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        image_bytes (bytes): The image generated by the model.
    """

    logger.info(
        "Generating image with Amazon Titan Image Generator G1 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())

    base64_image = response_body.get("images")[0]
    base64_bytes = base64_image.encode('ascii')
    image_bytes = base64.b64decode(base64_bytes)

    finish_reason = response_body.get("error")

    if finish_reason is not None:
        raise ImageError(f"Image generation error. Error is {finish_reason}")

    logger.info(
        "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id)

    return image_bytes


def main():
    """
    Entrypoint for Amazon Titan Image Generator G1 example.
    """
    try:
        logging.basicConfig(level=logging.INFO,
                            format="%(levelname)s: %(message)s")

        model_id = 'amazon.titan-image-generator-v1'

        # Read image from file and encode it as base64 string.
        with open("/path/to/image", "rb") as image_file:
            input_image = base64.b64encode(image_file.read()).decode('utf8')

        body = json.dumps({
            "taskType": "INPAINTING",
            "inPaintingParams": {
                "text": "Modernize the windows of the house",
                "negativeText": "bad quality, low res",
                "image": input_image,
                "maskPrompt": "windows"
            },
            "imageGenerationConfig": {
                "numberOfImages": 1,
                "height": 512,
                "width": 512,
                "cfgScale": 8.0
            }
        })

        image_bytes = generate_image(model_id=model_id,
                                     body=body)
        image = Image.open(io.BytesIO(image_bytes))
        image.show()

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))
    except ImageError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(
            f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.")


if __name__ == "__main__":
    main()
```

------
#### [ Outpainting ]

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to use outpainting to generate an image from a source image with 
the Amazon Titan Image Generator G1 model (on demand).
The example uses a mask image to outpaint the original image.
"""
import base64
import io
import json
import logging
import boto3
from PIL import Image

from botocore.exceptions import ClientError


class ImageError(Exception):
    "Custom exception for errors returned by Amazon Titan Image Generator G1"

    def __init__(self, message):
        self.message = message


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_image(model_id, body):
    """
    Generate an image using Amazon Titan Image Generator G1 model on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        image_bytes (bytes): The image generated by the model.
    """

    logger.info(
        "Generating image with Amazon Titan Image Generator G1 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())

    base64_image = response_body.get("images")[0]
    base64_bytes = base64_image.encode('ascii')
    image_bytes = base64.b64decode(base64_bytes)

    finish_reason = response_body.get("error")

    if finish_reason is not None:
        raise ImageError(f"Image generation error. Error is {finish_reason}")

    logger.info(
        "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id)

    return image_bytes


def main():
    """
    Entrypoint for Amazon Titan Image Generator G1 example.
    """
    try:
        logging.basicConfig(level=logging.INFO,
                            format="%(levelname)s: %(message)s")

        model_id = 'amazon.titan-image-generator-v1'

        # Read image and mask image from file and encode as base64 strings.
        with open("/path/to/image", "rb") as image_file:
            input_image = base64.b64encode(image_file.read()).decode('utf8')
        with open("/path/to/mask_image", "rb") as mask_image_file:
            input_mask_image = base64.b64encode(
                mask_image_file.read()).decode('utf8')

        body = json.dumps({
            "taskType": "OUTPAINTING",
            "outPaintingParams": {
                "text": "Draw a chocolate chip cookie",
                "negativeText": "bad quality, low res",
                "image": input_image,
                "maskImage": input_mask_image,
                "outPaintingMode": "DEFAULT"
            },
            "imageGenerationConfig": {
                "numberOfImages": 1,
                "height": 512,
                "width": 512,
                "cfgScale": 8.0
            }
        }
        )

        image_bytes = generate_image(model_id=model_id,
                                     body=body)
        image = Image.open(io.BytesIO(image_bytes))
        image.show()

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))
    except ImageError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(
            f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.")


if __name__ == "__main__":
    main()
```

------
#### [ Image variation ]

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate an image variation from a source image with the
Amazon Titan Image Generator G1 model (on demand).
"""
import base64
import io
import json
import logging
import boto3
from PIL import Image

from botocore.exceptions import ClientError


class ImageError(Exception):
    "Custom exception for errors returned by Amazon Titan Image Generator G1"

    def __init__(self, message):
        self.message = message


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_image(model_id, body):
    """
    Generate an image using Amazon Titan Image Generator G1 model on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        image_bytes (bytes): The image generated by the model.
    """

    logger.info(
        "Generating image with Amazon Titan Image Generator G1 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())

    base64_image = response_body.get("images")[0]
    base64_bytes = base64_image.encode('ascii')
    image_bytes = base64.b64decode(base64_bytes)

    finish_reason = response_body.get("error")

    if finish_reason is not None:
        raise ImageError(f"Image generation error. Error is {finish_reason}")

    logger.info(
        "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id)

    return image_bytes


def main():
    """
    Entrypoint for Amazon Titan Image Generator G1 example.
    """
    try:
        logging.basicConfig(level=logging.INFO,
                            format="%(levelname)s: %(message)s")

        model_id = 'amazon.titan-image-generator-v1'

        # Read image from file and encode it as base64 string.
        with open("/path/to/image", "rb") as image_file:
            input_image = base64.b64encode(image_file.read()).decode('utf8')

        body = json.dumps({
            "taskType": "IMAGE_VARIATION",
            "imageVariationParams": {
                "text": "Modernize the house, photo-realistic, 8k, hdr",
                "negativeText": "bad quality, low resolution, cartoon",
                "images": [input_image],
		"similarityStrength": 0.7,  # Range: 0.2 to 1.0
            },
            "imageGenerationConfig": {
                "numberOfImages": 1,
                "height": 512,
                "width": 512,
                "cfgScale": 8.0
            }
        })

        image_bytes = generate_image(model_id=model_id,
                                     body=body)
        image = Image.open(io.BytesIO(image_bytes))
        image.show()

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))
    except ImageError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(
            f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.")


if __name__ == "__main__":
    main()
```

------
#### [ Image conditioning (V2 only) ]

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate image conditioning from a source image with the
Amazon Titan Image Generator G1 V2 model (on demand).
"""
import base64
import io
import json
import logging
import boto3
from PIL import Image

from botocore.exceptions import ClientError


class ImageError(Exception):
    "Custom exception for errors returned by Amazon Titan Image Generator V2"

    def __init__(self, message):
        self.message = message


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_image(model_id, body):
    """
    Generate an image using Amazon Titan Image Generator V2 model on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        image_bytes (bytes): The image generated by the model.
    """

    logger.info(
        "Generating image with Amazon Titan Image Generator 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())

    base64_image = response_body.get("images")[0]
    base64_bytes = base64_image.encode('ascii')
    image_bytes = base64.b64decode(base64_bytes)

    finish_reason = response_body.get("error")

    if finish_reason is not None:
        raise ImageError(f"Image generation error. Error is {finish_reason}")

    logger.info(
        "Successfully generated image with Amazon Titan Image Generator V2 model %s", model_id)

    return image_bytes


def main():
    """
    Entrypoint for Amazon Titan Image Generator V2 example.
    """
    try:
        logging.basicConfig(level=logging.INFO,
                            format="%(levelname)s: %(message)s")

        model_id = 'amazon.titan-image-generator-v2:0'

        # Read image from file and encode it as base64 string.
        with open("/path/to/image", "rb") as image_file:
            input_image = base64.b64encode(image_file.read()).decode('utf8')

        body = json.dumps({
            "taskType": "TEXT_IMAGE",
            "textToImageParams": {
                "text": "A robot playing soccer, anime cartoon style",
                "negativeText": "bad quality, low res",
                "conditionImage": input_image,
                "controlMode": "CANNY_EDGE"
            },
            "imageGenerationConfig": {
                "numberOfImages": 1,
                "height": 512,
                "width": 512,
                "cfgScale": 8.0
            }
        })

        image_bytes = generate_image(model_id=model_id,
                                     body=body)
        image = Image.open(io.BytesIO(image_bytes))
        image.show()

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))
    except ImageError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(
            f"Finished generating image with Amazon Titan Image Generator V2 model {model_id}.")


if __name__ == "__main__":
    main()
```

------
#### [ Color guided content (V2 only) ]

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate an image from a source image color palette with the
Amazon Titan Image Generator G1 V2 model (on demand).
"""
import base64
import io
import json
import logging
import boto3
from PIL import Image

from botocore.exceptions import ClientError


class ImageError(Exception):
    "Custom exception for errors returned by Amazon Titan Image Generator V2"

    def __init__(self, message):
        self.message = message


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_image(model_id, body):
    """
    Generate an image using Amazon Titan Image Generator V2 model on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        image_bytes (bytes): The image generated by the model.
    """

    logger.info(
        "Generating image with Amazon Titan Image Generator 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())

    base64_image = response_body.get("images")[0]
    base64_bytes = base64_image.encode('ascii')
    image_bytes = base64.b64decode(base64_bytes)

    finish_reason = response_body.get("error")

    if finish_reason is not None:
        raise ImageError(f"Image generation error. Error is {finish_reason}")

    logger.info(
        "Successfully generated image with Amazon Titan Image Generator V2 model %s", model_id)

    return image_bytes


def main():
    """
    Entrypoint for Amazon Titan Image Generator V2 example.
    """
    try:
        logging.basicConfig(level=logging.INFO,
                            format="%(levelname)s: %(message)s")

        model_id = 'amazon.titan-image-generator-v2:0'

        # Read image from file and encode it as base64 string.
        with open("/path/to/image", "rb") as image_file:
            input_image = base64.b64encode(image_file.read()).decode('utf8')

        body = json.dumps({
            "taskType": "COLOR_GUIDED_GENERATION",
            "colorGuidedGenerationParams": {
                "text": "digital painting of a girl, dreamy and ethereal, pink eyes, peaceful expression, ornate frilly dress, fantasy, intricate, elegant, rainbow bubbles, highly detailed, digital painting, artstation, concept art, smooth, sharp focus, illustration",
                "negativeText": "bad quality, low res",
                "referenceImage": input_image,
                "colors": ["#ff8080", "#ffb280", "#ffe680", "#ffe680"]
            },
            "imageGenerationConfig": {
                "numberOfImages": 1,
                "height": 512,
                "width": 512,
                "cfgScale": 8.0
            }
        })

        image_bytes = generate_image(model_id=model_id,
                                     body=body)
        image = Image.open(io.BytesIO(image_bytes))
        image.show()

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))
    except ImageError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(
            f"Finished generating image with Amazon Titan Image Generator V2 model {model_id}.")


if __name__ == "__main__":
    main()
```

------
#### [ Background removal (V2 only) ]

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate an image with background removal with the
Amazon Titan Image Generator G1 V2 model (on demand).
"""
import base64
import io
import json
import logging
import boto3
from PIL import Image

from botocore.exceptions import ClientError


class ImageError(Exception):
    "Custom exception for errors returned by Amazon Titan Image Generator V2"

    def __init__(self, message):
        self.message = message


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_image(model_id, body):
    """
    Generate an image using Amazon Titan Image Generator V2 model on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        image_bytes (bytes): The image generated by the model.
    """

    logger.info(
        "Generating image with Amazon Titan Image Generator 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())

    base64_image = response_body.get("images")[0]
    base64_bytes = base64_image.encode('ascii')
    image_bytes = base64.b64decode(base64_bytes)

    finish_reason = response_body.get("error")

    if finish_reason is not None:
        raise ImageError(f"Image generation error. Error is {finish_reason}")

    logger.info(
        "Successfully generated image with Amazon Titan Image Generator V2 model %s", model_id)

    return image_bytes


def main():
    """
    Entrypoint for Amazon Titan Image Generator V2 example.
    """
    try:
        logging.basicConfig(level=logging.INFO,
                            format="%(levelname)s: %(message)s")

        model_id = 'amazon.titan-image-generator-v2:0'

        # Read image from file and encode it as base64 string.
        with open("/path/to/image", "rb") as image_file:
            input_image = base64.b64encode(image_file.read()).decode('utf8')

        body = json.dumps({
            "taskType": "BACKGROUND_REMOVAL",
            "backgroundRemovalParams": {
                "image": input_image,
            }
        })

        image_bytes = generate_image(model_id=model_id,
                                     body=body)
        image = Image.open(io.BytesIO(image_bytes))
        image.show()

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))
    except ImageError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(
            f"Finished generating image with Amazon Titan Image Generator V2 model {model_id}.")


if __name__ == "__main__":
    main()
```

------

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

------

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

このセクションでは、Amazon Titan Multimodal Embeddings G1 を使用するためのリクエスト本文とレスポンス本文の形式とコード例を示します。

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

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

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

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

Amazon Titan Multimodal Embeddings G1 リクエスト本文には、次のフィールドが含まれます。

```
{
    "inputText": string,
    "inputImage": base64-encoded string,
    "embeddingConfig": {
        "outputEmbeddingLength": 256 | 384 | 1024
    }
}
```

次のフィールドの少なくとも 1 つが必要です。両方を含めて、結果のテキスト埋め込みと画像埋め込みベクトルを平均化する埋め込みベクトルを生成します。
+ **inputText** – 埋め込みに変換するテキストを入力します。
+ **inputImage** – base64 で埋め込みに変換するイメージをエンコードし、このフィールドに文字列を入力します。イメージを Base64 にエンコードし、Base64 でエンコードされた文字列をデコードしてイメージに変換する方法の例については、「[コード例](#api-inference-examples-titan-embed-mm)」を参照してください。

次のフィールドはオプションです。
+ **embeddingConfig** – 出力埋め込みベクトルに次のいずれかの長さを指定する `outputEmbeddingLength` フィールドが含まれます。
  + 256
  + 384
  + 1024 (デフォルト値)

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

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

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

各フィールドについて以下に説明します。
+ **embedding** – 指定した入力の埋め込みベクトルを表す配列です。
+ **inputTextTokenCount** – テキスト入力内のトークン数です。
+ **message** – 生成中に発生したエラーを指定します。

------

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

以下の例は、Python SDK でオンデマンドスループットの Amazon Titan Multimodal Embeddings G1 モデルを呼び出す方法を示しています。各ユースケースの例を表示するには、タブを選択してください。

------
#### [ Text embeddings ]

この例では、Amazon Titan Multimodal Embeddings G1 モデルを呼び出してテキスト埋め込みを生成する方法を示しています。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate embeddings from text with the Amazon Titan Multimodal Embeddings G1 model (on demand).
"""

import json
import logging
import boto3


from botocore.exceptions import ClientError

class EmbedError(Exception):
    "Custom exception for errors returned by Amazon Titan Multimodal Embeddings G1"

    def __init__(self, message):
        self.message = message

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_embeddings(model_id, body):
    """
    Generate a vector of embeddings for a text input using Amazon Titan Multimodal Embeddings G1 on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        response (JSON): The embeddings that the model generated, token information, and the
        reason the model stopped generating embeddings.
    """

    logger.info("Generating embeddings with Amazon Titan Multimodal Embeddings G1 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())

    finish_reason = response_body.get("message")

    if finish_reason is not None:
        raise EmbedError(f"Embeddings generation error: {finish_reason}")

    return response_body


def main():
    """
    Entrypoint for Amazon Titan Multimodal Embeddings G1 example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    model_id = "amazon.titan-embed-image-v1"
    input_text = "What are the different services that you offer?"
    output_embedding_length = 256

    # Create request body.
    body = json.dumps({
        "inputText": input_text,
        "embeddingConfig": {
            "outputEmbeddingLength": output_embedding_length
        }
    })


    try:

        response = generate_embeddings(model_id, body)

        print(f"Generated text embeddings of length {output_embedding_length}: {response['embedding']}")
        print(f"Input text 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))
        
    except EmbedError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(f"Finished generating text embeddings with Amazon Titan Multimodal Embeddings G1 model {model_id}.")


if __name__ == "__main__":
    main()
```

------
#### [ Image embeddings ]

この例では、Amazon Titan Multimodal Embeddings G1 モデルを呼び出してイメージ埋め込みを生成する方法を示しています。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate embeddings from an image with the Amazon Titan Multimodal Embeddings G1 model (on demand).
"""

import base64
import json
import logging
import boto3

from botocore.exceptions import ClientError

class EmbedError(Exception):
    "Custom exception for errors returned by Amazon Titan Multimodal Embeddings G1"

    def __init__(self, message):
        self.message = message

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_embeddings(model_id, body):
    """
    Generate a vector of embeddings for an image input using Amazon Titan Multimodal Embeddings G1 on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        response (JSON): The embeddings that the model generated, token information, and the
        reason the model stopped generating embeddings.
    """

    logger.info("Generating embeddings with Amazon Titan Multimodal Embeddings G1 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())

    finish_reason = response_body.get("message")

    if finish_reason is not None:
        raise EmbedError(f"Embeddings generation error: {finish_reason}")

    return response_body


def main():
    """
    Entrypoint for Amazon Titan Multimodal Embeddings G1 example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    # Read image from file and encode it as base64 string.
    with open("/path/to/image", "rb") as image_file:
        input_image = base64.b64encode(image_file.read()).decode('utf8')

    model_id = 'amazon.titan-embed-image-v1'
    output_embedding_length = 256

    # Create request body.
    body = json.dumps({
        "inputImage": input_image,
        "embeddingConfig": {
            "outputEmbeddingLength": output_embedding_length
        }
    })


    try:

        response = generate_embeddings(model_id, body)

        print(f"Generated image embeddings of length {output_embedding_length}: {response['embedding']}")

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))
        
    except EmbedError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(f"Finished generating image embeddings with Amazon Titan Multimodal Embeddings G1 model {model_id}.")


if __name__ == "__main__":
    main()
```

------
#### [ Text and image embeddings ]

この例では、Amazon Titan Multimodal Embeddings G1 モデルを呼び出して、テキストとイメージを組み合わせた入力から埋め込みを生成する方法を示しています。結果のベクトルは、生成されたテキスト埋め込みベクトルとイメージ埋め込みベクトルの平均です。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate embeddings from an image and accompanying text with the Amazon Titan Multimodal Embeddings G1 model (on demand).
"""

import base64
import json
import logging
import boto3

from botocore.exceptions import ClientError

class EmbedError(Exception):
    "Custom exception for errors returned by Amazon Titan Multimodal Embeddings G1"

    def __init__(self, message):
        self.message = message

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_embeddings(model_id, body):
    """
    Generate a vector of embeddings for a combined text and image input using Amazon Titan Multimodal Embeddings G1 on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        response (JSON): The embeddings that the model generated, token information, and the
        reason the model stopped generating embeddings.
    """

    logger.info("Generating embeddings with Amazon Titan Multimodal Embeddings G1 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())

    finish_reason = response_body.get("message")

    if finish_reason is not None:
        raise EmbedError(f"Embeddings generation error: {finish_reason}")

    return response_body


def main():
    """
    Entrypoint for Amazon Titan Multimodal Embeddings G1 example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    model_id = "amazon.titan-embed-image-v1"
    input_text = "A family eating dinner"
    # Read image from file and encode it as base64 string.
    with open("/path/to/image", "rb") as image_file:
        input_image = base64.b64encode(image_file.read()).decode('utf8')
    output_embedding_length = 256

    # Create request body.
    body = json.dumps({
        "inputText": input_text,
        "inputImage": input_image,
        "embeddingConfig": {
            "outputEmbeddingLength": output_embedding_length
        }
    })


    try:

        response = generate_embeddings(model_id, body)

        print(f"Generated embeddings of length {output_embedding_length}: {response['embedding']}")
        print(f"Input text 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))
        
    except EmbedError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(f"Finished generating embeddings with Amazon Titan Multimodal Embeddings G1 model {model_id}.")


if __name__ == "__main__":
    main()
```

------