@Eeap
velog
@Eeap
전체 방문자
오늘
어제
  • 전체 (168)
    • osam (1)
    • Cloud (21)
      • Docker (2)
      • AWS (13)
    • AI & Data (7)
    • Algorithm (76)
      • Baekjoon (75)
      • Codeforces (1)
    • Language (18)
      • Java (18)
    • Back-end (17)
      • Spring (3)
      • JSP & Servlet (12)
      • Go (2)
    • 일상 (4)
    • 기타 (8)
    • git (1)
    • Infra (9)
      • Apache Kafka (5)
      • Kubernetes (4)
      • 기타 (0)

블로그 메뉴

  • 홈
  • 태그

공지사항

인기 글

태그

  • Agent
  • SageMaker
  • java
  • 티스토리챌린지
  • flink
  • sagemaker unified studio
  • bedrock agent
  • 오블완
  • converse api
  • Python
  • AWS CodeCatalyst
  • invokemodel api
  • CLASS
  • bedrock api
  • 심폴릭링크
  • AWS CodeStar
  • AWS CodeArtifact
  • 인터페이스
  • bedrock
  • knowledge bases

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
@Eeap

velog

Cloud/AWS

Basic Bedrock API

2024. 12. 22. 15:51
반응형

오늘 Amazon Bedrock의 API에 대해 살펴보고 실제로 어떻게 활용하는지 알아보고자 한다.

https://docs.aws.amazon.com/ko_kr/bedrock/latest/APIReference/welcome.html

 

Amazon Bedrock API Reference - Amazon Bedrock

Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better.

docs.aws.amazon.com

Bedrock 서비스에서는 현재 총 네 종류의 Service Endpoint를 제공해주고 있다. 오늘은 각각의 Endpoint 들에 대해 간단히 살펴보고 실제로 많이 쓰는 예제 코드를 작성해보고자 한다. 예제 코드의 경우 CLI를 사용하는 방법도 있지만 오늘은 Python SDK인 boto3를 이용해서 작성해보고자 한다.

Bedrock API

해당 Endpoint Actions에는 모델을 배포하고 관리하며, 훈련 작업을 할 수 있는 다양한 작업들을 포함하고 있다. AWS console에서 CloudTrail을 확인해보면 우리는 Bedrock에서 모델을 Custom하는 Job을 실행시키거나 학습시키는 등의 작업을 할때 주로 해당 Endpoint에 해당하는 Actions들을 호출하는 것을 확인할 수 있다.

간단하게 해당 리전에 포함되는 Foundation Model을 호출해 어떻게 활용하는지 알아보자. ListFoundationModels API는 호출에 필요한 다양한 파라미터를 포함하고 있으며 아래 코드를 통해서는 us-east-1 버지니아 리전에 포함된 Anthropic 제공자로 공급이 되는 Foundation Model을 확인할 수 있다.

import boto3

# Bedrock client
bedrock = boto3.client('bedrock',region_name="us-east-1",)

bedrock.list_foundation_models(byProvider="Anthropic",byOutputModality="TEXT")

https://boto3.amazonaws.com/v1/documentation/api/1.35.6/reference/services/bedrock/client/list_foundation_models.html

 

list_foundation_models - Boto3 1.35.6 documentation

Previous list_evaluation_jobs

boto3.amazonaws.com

Bedrock Runtime API

다음으로 Bedrock Runtime Endpoint에 대해 알아보자. 이전 Bedrock API가 많은 Actions들을 포함했다면 Bedrock Runtime API에는 많은 Actions들이 존재하지 않으며 이름 그대로 주로 Bedrock 모델을 호출하거나 그런 용도의 API들이 포함되어 있다. 주로 우리는 모델을 호출하기 위해 InvokeModel, Converse API를 사용하게 된다. 두 API의 차이는 InvokeModel은 단일 프롬프트를 통해 원하는 추론 결과를 얻고자 할때 주로 사용하게 되며 Converse API는 2024년 새로 추가된 API로 InvokeModel이 각각의 모델 공급자에 맞게 Inference 파라미터를 수정했다면 Converse API는 하나의 코드 작성으로 여러 모델을 사용할 수 있으며 지속적인 대화형 챗봇 구현이 용이하다. 

https://aws.amazon.com/about-aws/whats-new/2024/05/amazon-bedrock-new-converse-api/?source=post_page-----001c341347ca--------------------------------

 

Amazon Bedrock의 신규 Converse API 발표 - AWS

오늘 Amazon Bedrock의 신규 Converse API가 발표되었습니다. Converse API를 사용하는 개발자는 Amazon Bedrock 모델을 일관된 방식으로 호출할 수 있으므로 추론 파라미터 등을 모델별 차이점에 따라 조정하

aws.amazon.com

 

다음 예제를 통해 어떻게 사용하는지 살펴보자. 먼저, InvokeModel API는 다음과 같이 사용할 수 있다.

import boto3
import json
brt = boto3.client(service_name='bedrock-runtime')

body = json.dumps({
    "prompt": "\n\nHuman: what is AWS ? \n\nAssistant:",
    "max_tokens_to_sample": 300,
    "temperature": 0.1,
    "top_p": 0.9,
})

modelId = 'anthropic.claude-v2'
accept = 'application/json'
contentType = 'application/json'

response = brt.invoke_model(body=body, modelId=modelId, accept=accept, contentType=contentType)

response_body = json.loads(response.get('body').read())

print(response_body.get('completion'))

이때, 주의해야 할 점은 앞서 말한 것처럼 각각의 모델마다 Inference 파라미터가 다르기 때문에 모델에 맞는 파라미터를 참고해서 작성해야한다.

https://docs.aws.amazon.com/ko_kr/bedrock/latest/userguide/model-parameters.html

 

파운데이션 모델의 추론 요청 파라미터 및 응답 필드 - Amazon Bedrock

이 페이지에 작업이 필요하다는 점을 알려 주셔서 감사합니다. 실망시켜 드려 죄송합니다. 잠깐 시간을 내어 설명서를 향상시킬 수 있는 방법에 대해 말씀해 주십시오.

docs.aws.amazon.com

해당 리전에서 지원되는 모델의 경우 해당 링크를 통해 확인할 수 있다.

Converse API는 다음과 같이 사용할 수 있으며 이미지, 문서 등 다양한 type들을 사용할 수 있다. 더 자세한 코드는 해당 링크에서 확인할 수 있다.

import logging
import boto3


from botocore.exceptions import ClientError


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


def generate_message(bedrock_client,
                     model_id,
                     input_text,
                     input_document):
    # Message to send.

    message = {
        "role": "user",
        "content": [
            {
                "text": input_text
            },
            {
                "document": {
                    "name": "MyDocument",
                    "format": "pdf",
                    "source": {
                        "bytes": input_document
                    }
                }
            }
        ]
    }

    messages = [message]

    # Send the message.
    response = bedrock_client.converse(
        modelId=model_id,
        messages=messages
    )

    return response

def pdf_to_bytes(file_path):
    try:
        with open(file_path, 'rb') as file:
            pdf_bytes = file.read()
        return pdf_bytes
    except IOError as e:
        print(f"파일을 읽는 중 오류가 발생했습니다: {e}")
        return None

def main():
    model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
    input_text = "What's in this document?"
    input_document = pdf_to_bytes("bedrock.pdf")
    
    try:
        bedrock_client = boto3.client(service_name="bedrock-runtime")
        response = generate_message(
            bedrock_client, model_id, input_text, input_document)

        output_message = response['output']['message']

        print(f"Role: {output_message['role']}")

        for content in output_message['content']:
            print(f"Text: {content['text']}")

        token_usage = response['usage']
        print(f"Input tokens:  {token_usage['inputTokens']}")
        print(f"Output tokens:  {token_usage['outputTokens']}")
        print(f"Total tokens:  {token_usage['totalTokens']}")
        print(f"Stop reason: {response['stopReason']}")
    finally:
        print("end")

if __name__ == "__main__":
    main()

 

Converse API를 활용한다면 InvokeModel을 쓸때처럼 각각의 모델 공급자에 맞게 Inference 파라미터를 수정할 필요가 없고 이미지나 문서 첨부 등을 간단하게 프롬프트에 활용할 수 있다. 다만 해당 API도 모든 모델에 지원이 되는 것이 아니기 때문에 해당 문서를 참고하면 좋을 것 같다.

https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference-supported-models-features.html

 

Supported models and model features - Amazon Bedrock

Cohere Command (Text) and AI21 Labs Jurassic-2 (Text) don't support chat with the Converse API. The models can only handle one user message at a time and can't maintain the history of a conversation. You get an error if you attempt to pass more than one me

docs.aws.amazon.com

 

오늘은 이렇게 간단하게 Bedrock API에 대해 알아보았고 다음에는 Knowledge Base를 만들고 호출하는 Bedrock Agent API에 대해 알아보고자 한다.

반응형
저작자표시 비영리 (새창열림)

'Cloud > AWS' 카테고리의 다른 글

SageMaker Unified Studio (preview) Introduction - (1)  (0) 2025.02.02
Bedrock Agent API  (1) 2025.01.04
Amazon Bedrock  (1) 2024.11.09
Amazon SageMaker 개발 환경  (1) 2024.10.20
AWS Code Series를 이용한 자동화 구성하기  (0) 2024.04.15
    'Cloud/AWS' 카테고리의 다른 글
    • SageMaker Unified Studio (preview) Introduction - (1)
    • Bedrock Agent API
    • Amazon Bedrock
    • Amazon SageMaker 개발 환경
    @Eeap
    @Eeap

    티스토리툴바