기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
Amazon SageMaker AI 노트북을 사용하여 예제 Amazon Bedrock API 요청 실행
이 섹션에서는 Amazon SageMaker AI 노트북을 사용하여 Amazon Bedrock에서 몇 가지 일반적인 작업을 시도하여 Amazon Bedrock 역할 권한이 올바르게 설정되었는지 테스트하는 방법을 안내합니다. 다음 예제를 실행하기 전에 다음과 같은 사전 조건을 충족하는지 확인해야 합니다.
사전 조건
-
AWS 계정 Amazon Bedrock에 필요한 권한을 가진 역할에 액세스할 수 있는 및 권한이 있습니다. 그렇지 않은 경우 이미 AWS 계정가 있는 경우의 단계를 따르세요.
-
Amazon Titan Text G1 - Express 모델에 대한 액세스를 요청했습니다. 그렇지 않은 경우 Amazon Bedrock 파운데이션 모델에 대한 액세스 요청의 단계를 따르세요.
-
다음 단계를 수행하여 SageMaker AI에 대한 IAM 권한을 설정하고 노트북을 생성합니다.
-
콘솔, CLI 또는 API를 통해 이미 AWS 계정가 있는 경우에서 설정한 Amazon Bedrock 역할의 신뢰 정책을 수정합니다. Amazon Bedrock 및 SageMaker AI 서비스가 모두 Amazon Bedrock 역할을 수임할 수 있도록 다음 신뢰 정책을 역할에 연결합니다.
{ "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" } ] }
-
방금 신뢰 정책을 수정한 Amazon Bedrock 역할에 로그인합니다.
-
자습서용 Amazon SageMaker AI 노트북 인스턴스 생성의 단계에 따라 SageMaker AI 노트북 인스턴스를 생성하기 위해 생성한 Amazon Bedrock 역할의 ARN을 지정합니다.
-
노트북 인스턴스의 상태가 InService 인 경우 인스턴스를 선택한 다음 JupyterLab 열기를 선택합니다.
-
SageMaker AI 노트북을 연 후 다음 예제를 시도해 볼 수 있습니다.
Amazon Bedrock이 제공해야 하는 파운데이션 모델 나열
다음 예제에서는 Amazon Bedrock 클라이언트를 사용하여 ListFoundationModels 작업을 실행합니다. ListFoundationModels
는 리전의 Amazon Bedrock에서 사용할 수 있는 파운데이션 모델(FM)을 나열합니다. 다음 SDK for Python 스크립트를 실행하여 Amazon Bedrock 클라이언트를 만들고 ListFoundationModels 작업을 테스트합니다.
""" 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에서 사용할 수 있는 파운데이션 모델 목록을 반환합니다.
모델에 텍스트 프롬프트를 제출하고 응답 생성
다음 예제에서는 Amazon Bedrock 클라이언트를 사용하여 Converse 작업을 실행합니다. Converse
를 사용하면 프롬프트를 제출하여 모델 응답을 생성할 수 있습니다. 다음 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)
명령이 성공하면 응답은 프롬프트에 대한 응답으로 모델에서 생성된 텍스트를 반환합니다.