기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
AWS SDK for Python(Boto3)을 통해 예제 Amazon Bedrock API 요청 실행
이 섹션에서는를 사용하여 AWS Amazon Bedrock에서 몇 가지 일반적인 작업을 시도Python하여 권한 및 인증이 올바르게 설정되었는지 테스트하는 방법을 안내합니다. 다음 예제를 실행하기 전에 다음과 같은 사전 조건을 충족하는지 확인해야 합니다.
사전 조건
-
인증이 설정된 AWS 계정 및 사용자 또는 역할과 Amazon Bedrock에 필요한 권한이 있습니다. 그렇지 않은 경우 API 시작하기의 단계를 따르세요.
-
Amazon Titan Text G1 - Express 모델에 대한 액세스를 요청했습니다. 그렇지 않은 경우 Amazon Bedrock 파운데이션 모델에 대한 액세스 요청의 단계를 따르세요.
-
AWS SDK for Python(Boto3)에 대한 인증을 설치하고 설정했습니다. Boto3를 설치하려면 Boto3 설명서의 Quickstart
의 단계를 따릅니다. 의 단계에 따라 Boto3를 사용하도록 자격 증명을 설정했는지 확인합니다프로그래밍 방식 액세스 권한을 부여하는 자격 증명 가져오기.
적절한 권한으로 설정한 사용자 또는 역할을 사용하여 Amazon Bedrock에 대한 권한이 올바르게 설정되었는지 테스트합니다.
Amazon Bedrock 설명서에는 다른 프로그래밍 언어에 대한 코드 예제도 포함되어 있습니다. 자세한 내용은 AWS SDKs를 사용하는 Amazon Bedrock의 코드 예제 단원을 참조하십시오.
주제
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에서 사용할 수 있는 파운데이션 모델 목록을 반환합니다.
모델에 텍스트 프롬프트를 제출하고 InvokeModel을 사용하여 텍스트 응답 생성
다음 예제에서는 Amazon Bedrock 클라이언트를 사용하여 InvokeModel 작업을 실행합니다. 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를 사용하여 텍스트 응답 생성
다음 예제에서는 Amazon Bedrock 클라이언트를 사용하여 Converse 작업을 실행합니다. 지원되는 경우 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)
명령이 성공하면 응답은 프롬프트에 대한 응답으로 모델에서 생성된 텍스트를 반환합니다.