

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 사용자 지정 모델(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 작업을 사용합니다. 다음 코드로 Python용 SDK(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) 섹션을 참조하세요.

사용자 지정 모델을 생성한 후 모델은 `imported`의 `customizationType`과 함께 [ListCustomModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListCustomModels.html) 응답에 나타납니다. 새 모델의 상태를 추적하려면 [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()
```