

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 匯入 SageMaker AI 訓練的 Amazon Nova 模型
<a name="import-with-create-custom-model"></a>

**注意**  
若要將開放原始碼模型匯入 Amazon Bedrock，請使用模型匯入任務。如需詳細資訊，請參閱[使用自訂模型匯入，將自訂的開放原始碼模型匯入 Amazon Bedrock](model-customization-import-model.md)。

 若要匯入您使用 SageMaker AI 自訂的 Amazon Nova 模型，您可以在 Amazon Bedrock 中為其建立新的自訂模型。例如，如果您使用 SageMaker AI 微調 Amazon Nova Pro 模型以改善其針對特定使用案例的效能，您可以將經微調的模型匯入 Amazon Bedrock 做為自訂模型，並使用它來執行推論。

 在 Amazon Bedrock 中建立及使用 SageMaker AI 訓練的 Amazon Nova 模型，運作方式如下：

1. **在 SageMaker AI 中自訂模型** – 透過使用 SageMaker AI 訓練任務的預先建置基礎配方來自訂 Amazon Nova 模型。如需詳細資訊，請參閱《*Amazon SageMaker AI 開發人員指南*》中的[自訂 Amazon Nova 模型](https://docs.aws.amazon.com/sagemaker/latest/dg/nova-model.html)。

1. **在 Amazon Bedrock 中建立自訂模型** – 使用 [CreateCustomModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_CreateCustomModel.html) API 操作建立自訂模型。當您建立自訂模型時，Amazon Bedrock 會驗證模型成品，然後從 Amazon 受管的 Amazon S3 儲存貯體匯入模型成品。當您執行第一個 SageMaker AI 訓練任務時，SageMaker AI 會建立此儲存貯體。如需程式碼範例，請參閱 [建立自訂模型AWS SDKs)](create-custom-model-sdks.md)。

1.  **設定自訂模型的推論** – 匯入程序完成後，您可以設定模型的推論。如需詳細資訊，請參閱[為自訂模型設定推論](model-customization-use.md)。您可以透過模型自訂來管理自訂模型，就像在 Amazon Bedrock 中建立的模型一樣。如需詳細資訊，請參閱[自訂模型，以改善其針對使用案例的效能](custom-models.md)。

您可以從下列區域中的 Amazon Nova 模型建立自訂模型 (如需 Amazon Bedrock 支援區域的詳細資訊，請參閱 [Amazon Bedrock 端點和配額](https://docs.aws.amazon.com/general/latest/gr/bedrock.html))：
+ 美國東部 (維吉尼亞北部)

**Topics**
+ [準則和要求](#create-custom-model-considerations)
+ [建立自訂模型AWS SDKs)](create-custom-model-sdks.md)

## 準則和要求
<a name="create-custom-model-considerations"></a>

匯入 Amazon Nova 模型之前，請注意下列事項：
+ 您必須使用美國東部 (維吉尼亞北部) 區域。
+ 在 SageMaker AI 中自訂模型時，您必須使用下列其中一個 Amazon Nova 模型：
  + Amazon Nova Lite
  + Amazon Nova Micro
  + Amazon Nova Pro
+ 當您在 SageMaker AI 中自訂模型時，必須使用 SageMaker AI Amazon Nova 配方。如需詳細資訊，請參閱《Amazon SageMaker AI 開發人員指南》中的 [Amazon Nova 配方](https://docs.aws.amazon.com/sagemaker/latest/dg/nova-model-recipes.html)。
+ 您的 SageMaker AI 訓練的 Amazon Nova 模型必須存放在 Amazon 受管的 Amazon S3 儲存貯體中。當您執行第一個 SageMaker AI 訓練任務時，SageMaker AI 會建立此儲存貯體。
+ 您的 Amazon Bedrock 服務角色必須具有存取 Amazon 受管 Amazon S3 儲存貯體的許可，如果指定，則為您的 AWS KMS 金鑰。如需建立角色的詳細資訊，請參閱 [建立用於匯入預先訓練模型的服務角色](model-import-iam-role.md)。如需授予角色許可以使用您的 AWS KMS 金鑰的詳細資訊，請參閱 [加密匯入的自訂模型](encryption-import-model.md)。
+ 您只能使用 Amazon Bedrock API，從現有的 SageMaker AI 訓練的 Amazon Nova 模型建立自訂模型。您無法使用 Amazon Bedrock 主控台。

# 建立自訂模型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 Resource Name (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) 回應中，並顯示 `imported` 的 `customizationType`。若要追蹤新模型的狀態，您可以使用 [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()
```