

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

# Amazon SageMaker AI 노트북을 사용하여 예제 Amazon Bedrock API 요청 실행
<a name="getting-started-api-ex-sm"></a>

이 섹션에서는 Amazon SageMaker AI 노트북으로 Amazon Bedrock에서 몇 가지 일반적인 작업을 시도하여 Amazon Bedrock 역할 권한이 제대로 설정되었는지 테스트하는 방법을 안내합니다. 다음 예제를 실행하기 전에 다음과 같은 사전 조건을 충족하는지 확인해야 합니다.

**사전 조건**
+ 가 AWS 계정 있고 Amazon Bedrock에 필요한 권한이 있는 역할에 액세스할 수 있는 권한이 있습니다. 그렇지 않은 경우 [빠른 시작](getting-started.md)의 단계를 따르세요.
+ 다음 단계를 수행하여 SageMaker AI에 대한 IAM 권한을 설정하고 노트북을 만듭니다.

  1. [콘솔](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-console.html#roles-managingrole_edit-trust-policy), [CLI](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-cli.html#roles-managingrole_edit-trust-policy-cli) 또는 [API](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-api.html#roles-managingrole_edit-trust-policy-api)를 통해 [빠른 시작](getting-started.md)에서 설정한 Amazon Bedrock 역할의 [신뢰 정책](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#term_trust-policy)을 수정합니다. Amazon Bedrock 및 SageMaker AI 서비스 모두가 Amazon Bedrock 역할을 수임할 수 있도록 다음 신뢰 정책을 역할에 연결합니다.

------
#### [ JSON ]

****  

     ```
     {
         "Version":"2012-10-17",		 	 	 
         "Statement": [
             {
                 "Sid": "BedrockTrust",
                 "Effect": "Allow",
                 "Principal": {
                     "Service": "bedrock.amazonaws.com"
                 },
                 "Action": "sts:AssumeRole"
             },
             {
                 "Sid": "SagemakerTrust",
                 "Effect": "Allow",
                 "Principal": {
                     "Service": "sagemaker.amazonaws.com"
                 },
                 "Action": "sts:AssumeRole"
             }
         ]
     }
     ```

------

  1. 방금 신뢰 정책을 수정한 Amazon Bedrock 역할에 로그인합니다.

  1. [자습서용 Amazon SageMaker AI 노트북 인스턴스 생성](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-setup-working-env.html)의 단계를 따르고 SageMaker AI 노트북 인스턴스를 만들기 위해 생성한 Amazon Bedrock 역할의 ARN을 지정합니다.

  1. 노트북 인스턴스의 **상태**가 **InService** 인 경우 인스턴스를 선택한 다음 **JupyterLab 열기**를 선택합니다.

SageMaker AI 노트북을 연 후 다음 예제를 시도해 볼 수 있습니다.

**Topics**
+ [Amazon Bedrock이 제공해야 하는 파운데이션 모델 나열](#getting-started-api-ex-sm-listfm)
+ [모델에 텍스트 프롬프트를 제출하고 응답 생성](#getting-started-api-ex-sm-converse)

## Amazon Bedrock이 제공해야 하는 파운데이션 모델 나열
<a name="getting-started-api-ex-sm-listfm"></a>

다음 예제에서는 Amazon Bedrock 클라이언트를 사용하여 [ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html) 작업을 실행합니다. `ListFoundationModels`는 리전의 Amazon Bedrock에서 사용할 수 있는 파운데이션 모델(FM)을 나열합니다. 다음 SDK for Python 스크립트를 실행하여 Amazon Bedrock 클라이언트를 만들고 [ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html) 작업을 테스트합니다.

```
"""
Lists the available Amazon Bedrock models in an &AWS-Region;.
"""
import logging
import json
import boto3


from botocore.exceptions import ClientError


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


def list_foundation_models(bedrock_client):
    """
    Gets a list of available Amazon Bedrock foundation models.

    :return: The list of available bedrock foundation models.
    """

    try:
        response = bedrock_client.list_foundation_models()
        models = response["modelSummaries"]
        logger.info("Got %s foundation models.", len(models))
        return models

    except ClientError:
        logger.error("Couldn't list foundation models.")
        raise


def main():
    """Entry point for the example. Change aws_region to the &AWS-Region;
    that you want to use."""
   
    aws_region = "us-east-1"

    bedrock_client = boto3.client(service_name="bedrock", region_name=aws_region)
    
    fm_models = list_foundation_models(bedrock_client)
    for model in fm_models:
        print(f"Model: {model["modelName"]}")
        print(json.dumps(model, indent=2))
        print("---------------------------\n")
    
    logger.info("Done.")

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

스크립트가 성공하면 응답은 Amazon Bedrock에서 사용할 수 있는 파운데이션 모델 목록을 반환합니다.

## 모델에 텍스트 프롬프트를 제출하고 응답 생성
<a name="getting-started-api-ex-sm-converse"></a>

다음 예제에서는 Amazon Bedrock 클라이언트를 사용하여 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 작업을 실행합니다. `Converse`를 사용하면 프롬프트를 제출하여 모델 응답을 생성할 수 있습니다. 다음 SDK for Python 스크립트를 실행하여 Amazon Bedrock 런타임 클라이언트를 만들고 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 작업을 테스트합니다.

```
# Use the Conversation API to send a text message to Amazon Nova Micro.

import boto3
from botocore.exceptions import ClientError

# Create an Amazon Bedrock Runtime client.
brt = boto3.client("bedrock-runtime")

# Set the model ID, e.g., Amazon Nova Micro.
model_id = "amazon.nova-micro-v1:0"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = brt.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```

명령이 성공하면 응답은 프롬프트에 대한 응답으로 모델에서 생성된 텍스트를 반환합니다.