Amazon Titan Multimodal Embeddings G1 - Amazon Bedrock

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

Amazon Titan Multimodal Embeddings G1

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

リクエストとレスポンス

リクエスト本文は、InvokeModelリクエストの bodyフィールドに渡されます。

Request

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

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

次のフィールドの少なくとも 1 つが必要です。両方を含めて、結果として生じるテキスト埋め込みと画像埋め込みベクトルを平均する埋め込みベクトルを生成します。

  • inputText – 埋め込みに変換するテキストを入力します。

  • inputImage – base64 の埋め込みに変換するイメージをエンコードし、このフィールドに文字列を入力します。画像を Base64 にエンコードし、Base64 でエンコードされた文字列をデコードして画像に変換する方法の例については、コード例を参照してください。

次のフィールドはオプションです。

  • embeddingConfig – 出力埋め込みベクトルに次のいずれかの長さを指定する outputEmbeddingLengthフィールドが含まれます。

    • 256

    • 384

    • 1024 (デフォルト)

Response

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

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

フィールドについて以下に説明します。

  • embedding – 指定した入力の埋め込みベクトルを表す配列。

  • inputTextTokenカウント — テキスト入力内のトークンの数。

  • message – 生成中に発生するエラーを指定します。

サンプルのコード

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

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