

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

# カスタムモデルを作成する (AWS SDKs)
<a name="create-custom-model-sdks"></a>

Amazon S3 に保存されている SageMaker AI でトレーニングされた Amazon Nova モデルからカスタムモデルを作成するには、[CreateCustomModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_CreateCustomModel.html) API オペレーションを使用します。SDK for Python (Boto3) でカスタムモデルを作成するには、以下のコードを使用できます。このコードはカスタムモデルを作成し、モデルが `ACTIVE` になって使用可能になるまでそのステータスをチェックします。

このコードを使用するには、以下のパラメータを更新します。コードサンプルには、べき等性のための `clientRequestToken` やリソースのタグ付けのための `modelTags` などのオプションのパラメータも含まれています。
+ **modelName** – モデルに一意の名前を付けます。
+ **s3Uri** – モデルアーティファクトを保存する Amazon マネージド Amazon S3 バケットへのパスを指定します。このバケットは、最初の SageMaker AI トレーニングジョブを実行するときに SageMaker AI によって作成されます。
+ **roleArn** – Amazon Bedrock がユーザーに代わってタスクを実行するために引き受ける IAM サービスロールの Amazon リソースネーム (ARN) を指定します。このロールの作成に関する詳細については、「[事前トレーニングしたモデルをインポートするサービスロールを作成する](model-import-iam-role.md)」をご参照ください。
+ **modelKmsKeyArn** (オプション) – Amazon Bedrock でモデルを暗号化する AWS KMS キーを指定します。 AWS KMS キーを指定しない場合、Amazon Bedrock は AWSマネージド AWS KMS キーを使用してモデルを暗号化します。暗号化の詳細については、「[インポートされたカスタムモデルの暗号化](encryption-import-model.md)」を参照してください。

カスタムモデルを作成すると、そのモデルが [ListCustomModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListCustomModels.html) レスポンスに表示されます。`customizationType` は `imported` として表示されます。新しいモデルのステータスを追跡するには、[GetCustomModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_GetCustomModel.html) API オペレーションを使用します。

```
import boto3
import uuid
from botocore.exceptions import ClientError
import time

def create_custom_model(bedrock_client):
    """
    Creates a custom model in Amazon Bedrock from a SageMaker AI-trained Amazon Nova model stored in Amazon S3.
    Args:
        bedrock_client: The Amazon Bedrock client instance
    Returns:
        dict: Response from the CreateCustomModel API call
    """
    try:
        # Create a unique client request token for idempotency
        client_request_token = str(uuid.uuid4())

        # Define the model source configuration
        model_source_config = {
            's3DataSource': {
                's3Uri': '{{s3://amzn-s3-demo-bucket/folder/}}',
            }
        }

        # Create the custom model
        response = bedrock_client.create_custom_model(
            # Required parameters
            modelName='{{modelName}}',
            roleArn='{{serviceRoleArn}}',
            modelSourceConfig=model_source_config,

            # Optional parameters
            clientRequestToken=client_request_token,
            modelKmsKeyArn='{{keyArn}}',
            modelTags=[
                {
                    'key': 'Environment',
                    'value': 'Production'
                },
                {
                    'key': 'Project',
                    'value': 'AIInference'
                }
            ]
        )

        print(f"Custom model creation initiated. Model ARN: {response['modelArn']}")

        return response

    except ClientError as e:
        print(f"Error creating custom model: {e}")
        raise

def list_custom_models(bedrock_client):
    """
    Lists all custom models in Amazon Bedrock.

    Args:
        bedrock_client: An Amazon Bedrock client.

    Returns:
        dict: Response from the ListCustomModels API call

    """

    try:
        response = bedrock_client.list_custom_models()
        print(f"Total number of custom models: {len(response['modelSummaries'])}")

        for model in response['modelSummaries']:
            print("ARN: " + model['modelArn'])
            print("Name: " + model['modelName'])
            print("Status: " + model['modelStatus'])
            print("Customization type: " + model['customizationType'])
            print("------------------------------------------------------")

        return response

    except ClientError as e:
        print(f"Error listing custom models: {e}")
        raise

def check_model_status(bedrock_client, model_arn):
    """
    Checks the status of a custom model creation.

    Args:
        model_arn (str): The ARN of the custom model
        bedrock_client: An Amazon Bedrock client.

    Returns:
        dict: Response from the GetCustomModel API call

    """

    try:
        max_time = time.time() + 60 * 60  # 1 hour

        while time.time() < max_time:
            response = bedrock_client.get_custom_model(modelIdentifier=model_arn)
            status = response.get('modelStatus')
            print(f"Job status: {status}")
            if status == 'Failed':
                print(f"Failure reason: {response.get('failureMessage')}")
                break
            if status == 'Active':
                print("Model is ready for use.")
                break
            time.sleep(60)

    except ClientError as e:
        print(f"Error checking model status: {e}")
        raise


def main():
    bedrock_client = boto3.client(service_name='bedrock', region_name='{{REGION}}')
    
    # Create the custom model
    model_arn = create_custom_model(bedrock_client)["modelArn"]

    # Check the status of the model
    if model_arn:
        check_model_status(bedrock_client, model_arn)

    # View all custom models
    list_custom_models(bedrock_client)


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