

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

# API 시작하기
<a name="getting-started-api"></a>

이 섹션에서는 AWS API를 통해 Amazon Bedrock을 요청하도록 환경을 설정하는 방법을 설명합니다.는 경험을 간소화하기 위해 다음 도구를 AWS 제공합니다.
+ AWS Command Line Interface (AWS CLI)
+ AWS SDKs
+ Amazon SageMaker AI 노트북 사용

API를 시작하려면 프로그래밍 방식 액세스 권한을 부여하기 위한 자격 증명이 필요합니다. 다음 섹션이 해당되는 경우 해당 섹션을 확장하고 지침을 따르세요. 그렇지 않으면 나머지 섹션을 진행합니다.

## 를 처음 사용하는 경우 AWS
<a name="gs-api-new-to-aws"></a>

이 없는 경우 다음 단계를 AWS 계정완료하여 생성합니다.

**에 가입하려면 AWS 계정**

1. [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup)을 엽니다.

1. 온라인 지시 사항을 따르세요.

   등록 절차 중 전화 또는 텍스트 메시지를 받고 전화 키패드로 확인 코드를 입력하는 과정이 있습니다.

   에 가입하면 AWS 계정*AWS 계정 루트 사용자*이 생성됩니다. 루트 사용자에게는 계정의 모든 AWS 서비스 및 리소스에 액세스할 권한이 있습니다. 보안 모범 사례는 사용자에게 관리 액세스 권한을 할당하고, 루트 사용자만 사용하여 [루트 사용자 액세스 권한이 필요한 작업](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks)을 수행하는 것입니다.

AWS 는 가입 프로세스가 완료된 후 확인 이메일을 보냅니다. 언제든지 [https://aws.amazon.com/](https://aws.amazon.com/)으로 이동하고 **내 계정**을 선택하여 현재 계정 활동을 확인하고 계정을 관리할 수 있습니다.

**보안 AWS 계정 루트 사용자**

1.  **루트 사용자를** 선택하고 AWS 계정 이메일 주소를 입력하여 계정 소유자[AWS Management Console](https://console.aws.amazon.com/)로에 로그인합니다. 다음 페이지에서 비밀번호를 입력합니다.

   루트 사용자를 사용하여 로그인하는 데 도움이 필요하면 *AWS Sign-In 사용 설명서*의 [루트 사용자로 로그인](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial)을 참조하세요.

1. 루트 사용자의 다중 인증(MFA)을 활성화합니다.

   지침은 *IAM 사용 설명서*의 [AWS 계정 루트 사용자(콘솔)에 대한 가상 MFA 디바이스 활성화를 참조하세요](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html).

## AWS CLI 또는 AWS SDK를 설치해야 합니다.
<a name="gs-api-cli-sdk-install"></a>

를 설치하려면 설치의 단계를 AWS CLI따르[거나의 최신 버전으로 업데이트합니다 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).

 AWS SDK를 설치하려면 [Tools to Build on AWS](https://aws.amazon.com/developer/tools/)에서 사용하려는 프로그래밍 언어에 해당하는 탭을 선택합니다. AWS 소프트웨어 개발 키트(SDKs)는 널리 사용되는 여러 프로그래밍 언어에 사용할 수 있습니다. 각 SDK는 개발자가 선호하는 언어로 애플리케이션을 쉽게 구축할 수 있도록 하는 API, 코드 예제 및 설명서를 제공합니다. SDK는 다음과 같은 유용한 작업을 자동으로 수행합니다.
+ 서비스 요청에 대한 암호화 서명
+ 요청 재시도
+ 오류 응답 처리

## 프로그래밍 방식 액세스 권한을 부여하는 자격 증명 가져오기
<a name="gs-grant-program-access"></a>

사용자는 AWS 외부에서와 상호 작용하려는 경우 프로그래밍 방식의 액세스가 필요합니다 AWS Management Console.는 보안 문제에 따라 여러 옵션을 AWS 제공합니다.

**참고**  
Amazon Bedrock API에 빠르게 액세스하는 데 사용할 수 있는 API 키를 생성하는 단계별 지침은 [Amazon Bedrock API 키 시작하기: 30일 키를 생성하고 첫 API 직접 호출 수행](getting-started-api-keys.md) 섹션을 참조하세요.  
보안 요구 사항의 수준이 더 높은 경우, 이 섹션을 계속 진행합니다.

프로그래밍 방식 액세스를 부여하는 방법은에 액세스하는 사용자 유형에 따라 다릅니다 AWS.

사용자에게 프로그래밍 방식의 액세스 권한을 부여하려면 다음 옵션 중 하나를 선택합니다.


****  

| 프로그래밍 방식 액세스가 필요한 위탁자는 누구인가요? | 목적 | 방법 | 
| --- | --- | --- | 
| IAM 사용자 | 장기 자격 증명의 기간을 제한하여 AWS CLI, AWS SDKs 또는 AWS APIs. |  사용하고자 하는 인터페이스에 대한 지침을 따릅니다. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/getting-started-api.html)  | 
| IAM 역할 | 임시 자격 증명을 사용하여 AWS CLI, AWS SDKs 또는 AWS APIs. | IAM 사용 설명서의 [AWS 리소스에서 임시 자격 증명 사용](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html)의 지침을 따릅니다. | 
|  작업 인력 ID (IAM Identity Center에서 관리되는 사용자)  | 임시 자격 증명을 사용하여 AWS CLI, AWS SDKs 또는 AWS APIs. |  사용하고자 하는 인터페이스에 대한 지침을 따릅니다. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/getting-started-api.html)  | 

## IAM 사용자의 액세스 키를 구성하는 방법
<a name="create-user-time-bound"></a>

IAM 사용자에 액세스 키를 사용하기로 결정한 경우 에서는 제한적인 인라인 정책을 포함하여 IAM 사용자에 대한 만료를 설정하는 것이 AWS 좋습니다.

**중요**  
다음 경고에 주의하세요.  
계정의 루트 자격 증명을 사용하여 AWS 리소스에 액세스**하지 마십시오**. 이 보안 인증은 계정 액세스에 제한이 없고 취소하기 어렵습니다.
**금지 사항.** 애플리케이션 파일에 리터럴 액세스 키나 보안 인증 정보를 넣으면 안 됩니다. 이를 어기는 경우, 예를 들어 프로젝트를 퍼블릭 리포지토리에 업로드하면 뜻하지 않게 보안 인증이 노출될 위험이 있습니다.
**금지 사항.** 프로젝트 영역에 보안 인증이 포함된 파일을 포함하지 마세요.
액세스 키를 안전하게 관리하세요. [계정 식별자를 찾는 데](https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html) 도움이 되더라도 액세스 키를 권한 없는 당사자에게 제공하지 마세요. 이렇게 하면 다른 사람에게 계정에 대한 영구 액세스 권한을 부여할 수 있습니다.
공유 자격 증명 파일에 저장된 모든 AWS 자격 증명은 일반 텍스트로 저장됩니다.

자세한 내용은의 [AWS 액세스 키 관리 모범 사례를](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) 참조하세요 AWS 일반 참조.

**IAM 사용자를 생성합니다.**

1.  AWS Management Console 홈 페이지에서 IAM 서비스를 선택하거나 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) IAM 콘솔로 이동합니다.

1. 탐색 창에서 **사용자**와 **사용자 생성**을 차례로 선택합니다.

1. IAM 콘솔의 지침에 따라 프로그래밍 방식 사용자(에 대한 액세스 권한 없음 AWS Management Console)와 권한 없음을 설정합니다.

**제한된 기간으로 사용자 액세스 제한**

생성하는 모든 IAM 사용자 액세스 키는 장기 자격 증명입니다. 이러한 자격 증명이 잘못 처리된 경우 만료되도록 하려면 키가 더 이상 유효하지 않은 날짜를 지정하는 인라인 정책을 생성하여 자격 증명에 시간 제한을 적용할 수 있습니다.

1. 방금 생성한 IAM 사용자를 엽니다. **권한** 탭에서 **권한 추가**, **인라인 정책 생성**을 차례로 선택합니다.

1. JSON 편집기에서 다음 권한을 지정합니다. 이 정책을 사용하려면 예제 정책의 `aws:CurrentTime` 타임스탬프 값 값을 자체 종료 날짜로 바꿉니다.
**참고**  
IAM은 액세스 키를 12시간으로 제한할 것을 권장합니다.

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Deny",
         "Action": "*",
         "Resource": "*",
         "Condition": {
           "DateGreaterThan": {
             "aws:CurrentTime": "2024-01-01T00:00:000"
           }
         }
       }
     ]
   }
   ```

------

**액세스 키 생성**

1. **사용자 세부 정보** 페이지에서 **보안 자격 증명** 탭을 선택합니다. **액세스 키** 섹션에서 **액세스 키 생성**을 선택합니다.

1. 이러한 액세스 키를 **기타**로 사용할 계획임을 표시하고 **액세스 키 생성**을 선택합니다.

1. **Retrieve access key page**(액세스 키 검색) 페이지에서 **Show**(표시)를 선택하여 사용자의 비밀 액세스 키 값을 표시합니다. 자격 증명을 복사하거나 .csv 파일을 다운로드할 수 있습니다.

**중요**  
이 IAM 사용자가 더 이상 필요하지 않은 경우 이를 제거하고 [AWS 보안 모범 사례에](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials) 따라 액세스 시 인간 사용자에게 [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html)를 통해 임시 자격 증명을 사용하도록 요구하는 것이 좋습니다 AWS.

## 사용자 또는 역할에 Amazon Bedrock 권한 연결
<a name="gs-api-br-permissions"></a>

프로그래밍 방식 액세스를 위한 자격 증명을 설정한 후에는 사용자 또는 IAM 역할이 Amazon Bedrock 관련 작업 세트에 액세스할 수 있도록 권한을 구성해야 합니다. 이러한 권한을 설정하려면 다음을 수행하세요.

1.  AWS Management Console 홈 페이지에서 IAM 서비스를 선택하거나 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) IAM 콘솔로 이동합니다.

1. **사용자** 또는 **역할**을 선택한 다음 사용자나 역할을 선택합니다.

1. **권한** 탭에서 **권한 추가**를 선택한 다음 ** AWS 관리형 정책 추가**를 선택합니다. [AmazonBedrockFullAccess]() AWS 관리형 정책을 선택합니다.

1. 사용자 또는 역할이 모델을 구독하도록 허용하려면 **인라인 정책 생성**을 선택하고 JSON 편집기에서 다음 권한을 지정합니다.

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
         {
             "Sid": "MarketplaceBedrock",
             "Effect": "Allow",
             "Action": [
                 "aws-marketplace:ViewSubscriptions",
                 "aws-marketplace:Unsubscribe",
                 "aws-marketplace:Subscribe"
             ],
             "Resource": "*"
         }
     ]
   }
   ```

------

## Amazon Bedrock에 대한 API 직접 호출 수행해 보기
<a name="gs-try-bedrock"></a>

모든 사전 조건을 충족한 후에는 다음 주제 중 하나를 선택하여 Amazon Bedrock 모델을 사용하여 모델 간접 호출 요청을 테스트해 봅니다.

**Topics**
+ [프로그래밍 방식 액세스 권한을 부여하는 자격 증명 가져오기](#gs-grant-program-access)
+ [사용자 또는 역할에 Amazon Bedrock 권한 연결](#gs-api-br-permissions)
+ [Amazon Bedrock에 대한 API 직접 호출 수행해 보기](#gs-try-bedrock)
+ [Amazon Bedrock API 키 시작하기: 30일 키를 생성하고 첫 API 직접 호출 수행](getting-started-api-keys.md)
+ [를 사용하여 예제 Amazon Bedrock API 요청 실행 AWS Command Line Interface](getting-started-api-ex-cli.md)
+ [AWS SDK for Python(Boto3)을 통해 예제 Amazon Bedrock API 요청 실행](getting-started-api-ex-python.md)
+ [Amazon SageMaker AI 노트북을 사용하여 예제 Amazon Bedrock API 요청 실행](getting-started-api-ex-sm.md)

# Amazon Bedrock API 키 시작하기: 30일 키를 생성하고 첫 API 직접 호출 수행
<a name="getting-started-api-keys"></a>

이 자습서는 30일 후에 만료되는 장기 Amazon Bedrock API 키를 생성하고 이를 사용하여 Python으로 간단한 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) API 직접 호출을 수행하는 방법을 안내합니다. 복잡한 AWS 자격 증명을 설정하지 않고 Amazon Bedrock으로 실험을 시작하는 가장 빠른 방법입니다.

**주의**  
장기 API 키는 Amazon Bedrock의 탐색 및 개발에만 권장됩니다. 프로덕션 애플리케이션의 경우 IAM 역할 또는 임시 자격 증명과 같은 [장기 액세스 키의 대체 항목](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)을 사용합니다.

다음 단계에 따라 30일 후에 만료되는 장기 Amazon Bedrock API 키를 생성합니다.

1. Amazon Bedrock 콘솔을 사용할 권한이 있는 IAM 자격 증명 AWS Management Console 으로에 로그인합니다. 그 다음 [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock)에서 Amazon Bedrock 콘솔을 엽니다.

1. 왼쪽 탐색 창에서 **API 키**를 선택합니다.

1. **장기 API 키** 탭에서 **장기 API 키 생성**을 선택합니다.

1. **API 키 만료** 섹션에서 **30일**을 선택합니다.

1. **생성**을 선택합니다. 생성하는 키는 연결된 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) 정책에 정의된 대로 핵심 Amazon Bedrock 작업을 수행할 수 있는 권한을 제공합니다.

1. 생성된 API 키를 복사하여 안전하게 저장합니다. 다음 단계에서 이 키를 사용합니다.
**중요**  
API 키는 한 번만 표시됩니다. 대화 상자를 닫기 전에 복사하여 저장해 두어야 합니다. API 키는 30일 후에 만료된다는 사실을 기억하세요. 동일한 단계에 따라 새로 생성하거나 지속적인 사용을 위해 더 안전한 인증 방법으로 전환하는 것이 좋습니다.

1. *\$1\$1api-key\$1*를 생성된 API 키 값으로 대체하여 API 키를 환경 변수로 설정하고 이를 사용하여 선택한 방법에서 응답을 생성합니다.

------
#### [ Python ]

   ```
   import boto3
   import os
   
   # Set the API key as an environment variable
   os.environ['AWS_BEARER_TOKEN_BEDROCK'] = "${api-key}"
   
   # Create the Bedrock client
   client = boto3.client(
       service_name="bedrock-runtime",
       region_name="us-east-1"
   )
   
   # Define the model and message
   model_id = "us.anthropic.claude-3-5-haiku-20241022-v1:0"
   messages = [{"role": "user", "content": [{"text": "Hello! Can you tell me about Amazon Bedrock?"}]}]
   
   # Make the API call
   response = client.converse(
       modelId=model_id,
       messages=messages,
   )
   
   # Print the response
   print(response['output']['message']['content'][0]['text'])
   ```

------
#### [ HTTP client using Python ]

   ```
   import requests
   
   url = "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse"
   
   payload = {
       "messages": [
           {
               "role": "user",
               "content": [{"text": "Hello"}]
           }
       ]
   }
   
   headers = {
       "Content-Type": "application/json",
       "Authorization": "Bearer ${api-key}"
   }
   
   response = requests.request("POST", url, json=payload, headers=headers)
   
   print(response.text)
   ```

------
#### [ HTTP request using cURL ]

   ```
   curl -X POST "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse" \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer ${api-key}" \
     -d '{
       "messages": [
           {
               "role": "user",
               "content": [{"text": "Hello"}]
           }
       ]
     }'
   ```

------

축하합니다\$1 Amazon Bedrock API 키를 성공적으로 생성하고 Amazon Bedrock 서비스에 대한 첫 API 직접 호출을 수행했습니다. 더 많은 Amazon Bedrock 작업을 탐색한 후에는 단기 Amazon Bedrock API 키 또는 AWS광범위한 임시 자격 증명과 같은 보다 안전한 인증 방법으로 전환해야 합니다. 자세한 내용은 다음 리소스를 참조하세요.
+ **다양한 모델 살펴보기** - [Amazon Bedrock 파운데이션 모델 정보](foundation-models-reference.md)의 Amazon Bedrock에서 사용할 수 있는 다른 파운데이션 모델에 대해 알아보고 코드에서 `model_id`를 변경하여 사용해 보세요.
+ **모델 추론에 대해 알아보기** - [모델 추론을 사용하여 프롬프트 제출 및 응답 생성](inference.md)의 Amazon Bedrock에서 사용할 수 있는 개념과 옵션에 대해 읽고 모델 추론을 사용하여 응답을 생성하는 방법에 대해 알아봅니다.
+ **보다 안전한 인증 방법을 통한 프로덕션 계획** - 빌드 장에서 Amazon Bedrock API 키에 대해 자세히 읽고 보다 안전한 단기 Amazon Bedrock API 키를 생성하는 방법을 알아봅니다. 프로덕션 애플리케이션을 구축할 준비가 되면 [장기 액세스 키에 대한 대안](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)도 검토하여 다른 AWS 서비스에 대한 액세스를 허용하는 보다 안전한 옵션을 찾아야 합니다.

# 를 사용하여 예제 Amazon Bedrock API 요청 실행 AWS Command Line Interface
<a name="getting-started-api-ex-cli"></a>

이 섹션에서는를 사용하여 Amazon Bedrock에서 몇 가지 일반적인 작업을 시도 AWS Command Line Interface 하여 권한 및 인증이 올바르게 설정되었는지 테스트하는 방법을 안내합니다. 다음 예제를 실행하기 전에 다음과 같은 사전 조건을 충족하는지 확인해야 합니다.

**사전 조건**
+  AWS 계정 인증이 설정되고 Amazon Bedrock에 필요한 권한이 있는 및 사용자 또는 역할이 있습니다. 그렇지 않은 경우 [API 시작하기](getting-started-api.md)의 단계를 따르세요.
+  AWS CLI에 대한 인증을 설치하고 설정했습니다. 를 설치하려면 [설치 또는 최신 버전으로 업데이트의 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 단계를 AWS CLI따릅니다. [프로그래밍 방식 액세스 권한을 부여하는 자격 증명 가져오기](getting-started-api.md#gs-grant-program-access)의 단계에 따라 CLI를 사용하도록 자격 증명을 설정했는지 확인합니다.

적절한 권한으로 설정한 사용자 또는 역할을 사용하여 Amazon Bedrock에 대한 권한이 올바르게 설정되었는지 테스트합니다.

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

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

다음 예제에서는를 사용하여 [ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html) 작업을 실행합니다 AWS CLI.는 리전의 Amazon Bedrock에서 사용할 수 있는 파운데이션 모델(FMs)을 `ListFoundationModels` 나열합니다. 터미널에서 다음 명령을 실행합니다.

```
aws bedrock list-foundation-models
```

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

## 모델에 텍스트 프롬프트를 제출하고 InvokeModel을 사용하여 텍스트 응답 생성
<a name="getting-started-api-ex-cli-invoke-text"></a>

다음 예제에서는를 사용하여 [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) 작업을 실행합니다 AWS CLI. `InvokeModel`를 사용하면 프롬프트를 제출하여 모델 응답을 생성할 수 있습니다. 터미널에서 다음 명령을 실행합니다.

```
aws bedrock-runtime invoke-model \
--model-id amazon.titan-text-express-v1 \
--body '{"inputText": "Describe the purpose of a \"hello world\" program in one line.", "textGenerationConfig" : {"maxTokenCount": 512, "temperature": 0.5, "topP": 0.9}}' \
--cli-binary-format raw-in-base64-out \
invoke-model-output-text.txt
```

명령이 성공하면 모델에서 생성된 응답이 `invoke-model-output-text.txt` 파일에 기록됩니다. 텍스트 응답은 함께 제공된 정보와 함께 `outputText` 필드에 반환됩니다.

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

다음 예제에서는를 사용하여 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 작업을 실행합니다 AWS CLI. `Converse`를 사용하면 프롬프트를 제출하여 모델 응답을 생성할 수 있습니다. 지원되는 경우 `InvokeModel`에서 `Converse` 작업을 사용하는 것이 좋습니다. Amazon Bedrock 모델에서 추론 요청을 통합하고 멀티턴 대화 관리를 간소화하기 때문입니다. 터미널에서 다음 명령을 실행합니다.

```
aws bedrock-runtime converse \
--model-id amazon.titan-text-express-v1 \
--messages '[{"role": "user", "content": [{"text": "Describe the purpose of a \"hello world\" program in one line."}]}]' \
--inference-config '{"maxTokens": 512, "temperature": 0.5, "topP": 0.9}'
```

명령이 성공하면 모델에서 생성된 응답이 함께 제공된 정보와 함께 `text` 필드에 반환됩니다.

# AWS SDK for Python(Boto3)을 통해 예제 Amazon Bedrock API 요청 실행
<a name="getting-started-api-ex-python"></a>

이 섹션에서는를 사용하여 AWS Amazon Bedrock에서 몇 가지 일반적인 작업을 시도Python하여 권한 및 인증이 올바르게 설정되었는지 테스트하는 방법을 안내합니다. 다음 예제를 실행하기 전에 다음과 같은 사전 조건을 충족하는지 확인해야 합니다.

**사전 조건**
+  AWS 계정 인증이 설정되고 Amazon Bedrock에 필요한 권한이 있는 및 사용자 또는 역할이 있습니다. 그렇지 않은 경우 [API 시작하기](getting-started-api.md)의 단계를 따르세요.
+  AWS SDK for Python(Boto3)에 대한 인증을 설치하고 설정했습니다. Boto3를 설치하려면 Boto3 설명서의 [빠른 시작](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)에 있는 단계를 따르세요. [프로그래밍 방식 액세스 권한을 부여하는 자격 증명 가져오기](getting-started-api.md#gs-grant-program-access)의 단계에 따라 Boto3를 사용하도록 자격 증명을 설정했는지 확인합니다.

적절한 권한으로 설정한 사용자 또는 역할을 사용하여 Amazon Bedrock에 대한 권한이 올바르게 설정되었는지 테스트합니다.

Amazon Bedrock 설명서에는 다른 프로그래밍 언어에 대한 코드 예제도 포함되어 있습니다. 자세한 내용은 [AWS SDKs를 사용하는 Amazon Bedrock의 코드 예제](service_code_examples.md) 단원을 참조하십시오.

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

## Amazon Bedrock이 제공해야 하는 파운데이션 모델 나열
<a name="getting-started-api-ex-python-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에서 사용할 수 있는 파운데이션 모델 목록을 반환합니다.

## 모델에 텍스트 프롬프트를 제출하고 InvokeModel을 사용하여 텍스트 응답 생성
<a name="getting-started-api-ex-python-invoke-text"></a>

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

```
# Use the native inference API to send a text message to Amazon Titan Text G1 - Express.

import boto3
import json

from botocore.exceptions import ClientError

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

# Set the model ID, e.g., Amazon Titan Text G1 - Express.
model_id = "amazon.titan-text-express-v1"

# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."

# Format the request payload using the model's native structure.
native_request = {
    "inputText": prompt,
    "textGenerationConfig": {
        "maxTokenCount": 512,
        "temperature": 0.5,
        "topP": 0.9
    },
}

# Convert the native request to JSON.
request = json.dumps(native_request)

try:
    # Invoke the model with the request.
    response = brt.invoke_model(modelId=model_id, body=request)

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

# Decode the response body.
model_response = json.loads(response["body"].read())

# Extract and print the response text.
response_text = model_response["results"][0]["outputText"]
print(response_text)
```

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

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

다음 예제에서는 Amazon Bedrock 클라이언트를 사용하여 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 작업을 실행합니다. 지원되는 경우 `InvokeModel`에서 `Converse` 작업을 사용하는 것이 좋습니다. Amazon Bedrock 모델에서 추론 요청을 통합하고 멀티턴 대화 관리를 간소화하기 때문입니다. 다음 SDK for Python 스크립트를 실행하여 Amazon Bedrock 런타임 클라이언트를 만들고 `Converse` 작업으로 텍스트 응답을 생성합니다.

```
# Use the Conversation API to send a text message to Amazon Titan Text G1 - Express.

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 Titan Text G1 - Express.
model_id = "amazon.titan-text-express-v1"

# 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)
```

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

# 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 Titan Text G1 - Express.

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 Titan Text G1 - Express.
model_id = "amazon.titan-text-express-v1"

# 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)
```

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