AnthropicClaude메시지 API - Amazon Bedrock

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

AnthropicClaude메시지 API

이 섹션에서는 Anthropic Claude 메시지 API 사용을 위한 추론 파라미터와 코드 예제를 제공합니다.

AnthropicClaude메시지 API 개요

메시지 API를 사용하여 채팅 봇 또는 가상 어시스턴트 애플리케이션을 만들 수 있습니다. API는 사용자와 Anthropic Claude 모델 (어시스턴트) 간의 대화 교환을 관리합니다.

AnthropicClaude 모델이 사용자와 어시스턴트의 대화 방향을 번갈아 가며 작동하도록 학습시킵니다. 새 메시지를 생성할 때는 messages 파라미터를 사용하여 이전 대화 순서를 지정합니다. 그러면 모델이 대화에서 다음 메시지를 생성합니다.

각 입력 메시지는 역할과 내용이 있는 개체여야 합니다. 단일 사용자 역할 메시지를 지정하거나 여러 사용자 및 도우미 메시지를 포함할 수 있습니다. 첫 번째 메시지는 항상 사용자 역할을 사용해야 합니다.

응답을 미리 채우는 기법 Claude (최종 조수 역할 메시지를 사용하여 Claude의 응답 시작 부분을 채우는 방법) 을 사용하는 경우, Claude 중단한 부분부터 다시 시작하여 응답합니다. 이 방법을 Claude 사용해도 여전히 어시스턴트 역할을 가진 응답을 반환합니다.

최종 메시지가 도우미 역할을 사용하는 경우 응답 콘텐츠는 해당 메시지의 콘텐츠에서 즉시 계속됩니다. 이를 사용하여 모델 응답의 일부를 제한할 수 있습니다.

단일 사용자 메시지를 사용한 예:

[{"role": "user", "content": "Hello, Claude"}]

대화식 차례가 여러 번 나오는 예:

[ {"role": "user", "content": "Hello there."}, {"role": "assistant", "content": "Hi, I'm Claude. How can I help you?"}, {"role": "user", "content": "Can you explain LLMs in plain English?"}, ]

Claude의 응답이 부분적으로 채워진 예:

[ {"role": "user", "content": "Please describe yourself using only JSON"}, {"role": "assistant", "content": "Here is my JSON description:\n{"}, ]

각 입력 메시지 콘텐츠는 단일 문자열이거나 콘텐츠 블록 배열일 수 있으며, 각 블록에는 특정 유형이 있습니다. “text” 유형의 콘텐츠 블록 하나로 구성된 배열의 줄임말로 문자열을 사용하는 것입니다. 다음 입력 메시지는 동일합니다.

{"role": "user", "content": "Hello, Claude"}
{"role": "user", "content": [{"type": "text", "text": "Hello, Claude"}]}

AnthropicClaude모델용 프롬프트 생성에 대한 자세한 내용은 설명서의 프롬프트 소개를 참조하십시오. Anthropic Claude 기존 텍스트 완성 프롬프트를 메시지 API로 마이그레이션하려는 경우 텍스트 완성에서 마이그레이션을 참조하십시오.

시스템 프롬프트

요청에 시스템 프롬프트를 포함할 수도 있습니다. 시스템 프롬프트를 사용하면 특정 목표 또는 역할 지정과 같은 컨텍스트와 지침을 제공할 수 있습니다. Anthropic Claude 다음 예와 같이 system 필드에 시스템 프롬프트를 지정합니다.

"system": "You are Claude, an AI assistant created by Anthropic to be helpful, harmless, and honest. Your goal is to provide informative and substantive responses to queries while avoiding potential harms."

자세한 내용은 Anthropic 설명서의 시스템 프롬프트를 참조하십시오.

멀티모달 프롬프트

멀티모달 프롬프트는 여러 양식 (이미지 및 텍스트) 을 단일 프롬프트에 결합합니다. 입력 필드에 양식을 지정합니다. content 다음 예제는 제공된 이미지의 내용을 Anthropic Claude 설명하도록 요청하는 방법을 보여줍니다. 예제 코드는 멀티모달 코드 예제 항목을 참조하세요.

{ "anthropic_version": "bedrock-2023-05-31", "max_tokens": 1024, "messages": [ { "role": "user", "content": [ { "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": "iVBORw..." } }, { "type": "text", "text": "What's in these images?" } ] } ] }

모델에 최대 20개의 이미지를 제공할 수 있습니다. 이미지는 어시스턴트 역할에 넣을 수 없습니다.

요청에 포함하는 각 이미지는 토큰 사용량에 포함됩니다. 자세한 내용은 Anthropic 설명서의 이미지 비용을 참조하십시오.

지원되는 모델

메시지 API는 다음 Anthropic Claude 모델에서 사용할 수 있습니다.

  • AnthropicClaudeInstantv1.2

  • AnthropicClaude2 v2

  • AnthropicClaude2 v2.1

  • Anthropic Claude 3 Sonnet

  • Anthropic Claude 3 Haiku

  • Anthropic Claude 3 Opus

요청 및 응답

요청 본문은 요청 body 필드에서 InvokeModel또는 InvokeModelWithResponseStream으로 전달됩니다. 요청으로 보낼 수 있는 페이로드의 최대 크기는 20MB입니다.

자세한 내용은 https://docs.anthropic.com/claude/reference/messages_post 을 참조하십시오.

Request

AnthropicClaude메시지 추론 호출에 대한 다음과 같은 추론 파라미터가 있습니다.

{ "anthropic_version": "bedrock-2023-05-31", "max_tokens": int, "system": string, "messages": [ { "role": string, "content": [ { "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": "content image bytes" } }, { "type": "text", "text": "content text" } ] } ], "temperature": float, "top_p": float, "top_k": int, "stop_sequences": [string] }

다음은 필수 파라미터입니다.

  • anthropic_version — (필수) 앤트로픽 버전입니다. 값은 bedrock-2023-05-31여야 합니다.

  • max_token — (필수) 중지하기 전에 생성할 수 있는 최대 토큰 수입니다.

    참고로 Anthropic Claude 모델은 의 값에 도달하기 전에 토큰 생성을 중단할 수 있습니다. max_tokens AnthropicClaude모델마다 이 매개변수의 최대값이 다릅니다. 자세한 내용은 모델 비교를 참조하십시오.

  • 메시지 — (필수) 입력 메시지.

    • 역할 — 대화 차례의 역할. 유효 값은 userassistant입니다.

    • 내용 — (필수) 대화 차례의 내용입니다.

      • 유형 — (필수) 콘텐츠 유형. 유효 값은 imagetext입니다.

        지정하는 image 경우 이미지 소스도 다음 형식으로 지정해야 합니다.

        source — (필수) 대화의 내용이 차례입니다.

        • type — (필수) 이미지의 인코딩 유형입니다. 지정할 수 있습니다base64.

        • media_type — (필수) 이미지의 유형입니다. 다음 이미지 형식을 지정할 수 있습니다.

          • image/jpeg

          • image/png

          • image/webp

          • image/gif

        • data — (필수) 이미지의 base64로 인코딩된 이미지 바이트입니다. 최대 이미지 크기는 3.75MB입니다. 이미지의 최대 높이 및 너비는 8000픽셀입니다.

        지정하는 text 경우 에서 text 프롬프트도 지정해야 합니다.

다음 파라미터는 선택 사항입니다.

  • system — (선택 사항) 요청에 대한 시스템 프롬프트입니다.

    시스템 프롬프트는 특정 목표나 역할을 지정하는 Anthropic Claude 등 컨텍스트와 지침을 제공하는 방법입니다. 자세한 내용은 Anthropic 설명서의 시스템 프롬프트 사용 방법을 참조하십시오.

    참고

    AnthropicClaude버전 2.1 이상에서는 시스템 프롬프트를 사용할 수 있습니다.

  • stop_sequence — (선택 사항) 모델 생성을 중단시키는 사용자 지정 텍스트 시퀀스입니다. AnthropicClaude모델은 보통 자연스럽게 차례를 마치면 멈춥니다. 이 경우 stop_reason 응답 필드 값은 입니다. end_turn 사용자 지정 텍스트 문자열을 발견했을 때 모델 생성이 중지되도록 하려면 stop_sequences 매개변수를 사용할 수 있습니다. 모델에서 사용자 지정 텍스트 문자열 중 하나를 발견하면 stop_reason 응답 필드의 값은 stop_sequence 이고 의 stop_sequence 값에는 일치하는 중지 시퀀스가 포함됩니다.

    최대 항목 수는 8191개입니다.

  • 온도 — (선택 사항) 반응에 주입되는 무작위성의 양입니다.

    기본값 최소 Maximum

    1

    0

    1

  • top_p — (선택 사항) 핵 샘플링을 사용합니다.

    핵 샘플링에서는 각 후속 토큰의 모든 옵션에 대한 누적 분포를 내림차순으로 Anthropic Claude 계산하고 지정된 특정 확률에 도달하면 이를 잘라냅니다. top_p 둘 중 하나를 변경해야 top_p 하지만 temperature 둘 다 변경해서는 안 됩니다.

    기본값 최소 Maximum

    0.999

    0

    1

다음 파라미터는 선택 사항입니다.

  • top_k — (선택 사항) 각 후속 토큰에 대해 상위 K개 옵션의 샘플만 추출합니다.

    롱테일 저확률 응답을 제거하는 top_k 데 사용합니다.

    기본값 최소 Maximum

    기본적으로 비활성화되어 있습니다.

    0

    500

Response

AnthropicClaude모델은 메시지 추론 호출에 대해 다음 필드를 반환합니다.

{ "id": string, "model": string, "type" : "message", "role" : "assistant", "content": [ { "type": "text", "text": string } ], "stop_reason": string, "stop_sequence": string, "usage": { "input_tokens": integer, "output_tokens": integer } }
  • id — 응답의 고유 식별자입니다. ID의 형식과 길이는 시간이 지남에 따라 변경될 수 있습니다.

  • 모델 — 요청을 한 Anthropic Claude 모델의 ID입니다.

  • stop_reason — 응답 생성을 Anthropic Claude 중단한 이유.

    • end_turn — 모델이 자연스러운 정지점에 도달했습니다.

    • max_token — 생성된 텍스트가 max_tokens 입력 필드 값을 초과했거나 모델이 지원하는 최대 토큰 수를 초과했습니다. '

    • stop_sequence — 입력 필드에 지정한 중지 시퀀스 중 하나가 모델이 생성했습니다. stop_sequences

  • 유형 — 응답 유형. 이 값은 항상 message입니다.

  • 역할 — 생성된 메시지의 대화적 역할. 이 값은 항상 assistant입니다.

  • 콘텐츠 — 모델에서 생성된 콘텐츠입니다. 배열로 반환됩니다.

    • type — 콘텐츠의 유형입니다. 현재 지원되는 값은 text입니다.

    • 텍스트 — 콘텐츠의 텍스트입니다.

  • 사용 — 요청에서 제공한 토큰 수와 응답에서 모델이 생성한 해당 모델의 토큰 수를 나타내는 컨테이너입니다.

    • input_token — 요청의 입력 토큰 수입니다.

    • output_token — 응답에서 모델이 생성한 해당 모델의 토큰 수입니다.

    • stop_sequence — 모델은 입력 필드에 지정한 중지 시퀀스 중 하나를 생성했습니다. stop_sequences

코드 예시

다음 코드 예제는 메시지 API를 사용하는 방법을 보여줍니다.

메시지 코드 예제

이 예제에서는 싱글턴 사용자 메시지와 미리 채워진 어시스턴트 메시지가 포함된 사용자 턴을 Anthropic Claude 3 Sonnet 모델에 보내는 방법을 보여줍니다.

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate a message with Anthropic Claude (on demand). """ import boto3 import json import logging from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_message(bedrock_runtime, model_id, system_prompt, messages, max_tokens): body=json.dumps( { "anthropic_version": "bedrock-2023-05-31", "max_tokens": max_tokens, "system": system_prompt, "messages": messages } ) response = bedrock_runtime.invoke_model(body=body, modelId=model_id) response_body = json.loads(response.get('body').read()) return response_body def main(): """ Entrypoint for Anthropic Claude message example. """ try: bedrock_runtime = boto3.client(service_name='bedrock-runtime') model_id = 'anthropic.claude-3-sonnet-20240229-v1:0' system_prompt = "Please respond only with emoji." max_tokens = 1000 # Prompt with user turn only. user_message = {"role": "user", "content": "Hello World"} messages = [user_message] response = generate_message (bedrock_runtime, model_id, system_prompt, messages, max_tokens) print("User turn only.") print(json.dumps(response, indent=4)) # Prompt with both user turn and prefilled assistant response. #Anthropic Claude continues by using the prefilled assistant text. assistant_message = {"role": "assistant", "content": "<emoji>"} messages = [user_message, assistant_message] response = generate_message(bedrock_runtime, model_id,system_prompt, messages, max_tokens) print("User turn and prefilled assistant response.") print(json.dumps(response, indent=4)) except ClientError as err: message=err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) if __name__ == "__main__": main()

멀티모달 코드 예제

다음 예제는 멀티모달 메시지의 이미지와 프롬프트 텍스트를 모델에 전달하는 방법을 보여줍니다. Anthropic Claude 3 Sonnet

멀티모달 프롬프트: InvokeModel

다음 예제에서는 with로 멀티모달 프롬프트를 보내는 방법을 보여줍니다. Anthropic Claude 3 Sonnet InvokeModel

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to run a multimodal prompt with Anthropic Claude (on demand) and InvokeModel. """ import json import logging import base64 import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def run_multi_modal_prompt(bedrock_runtime, model_id, messages, max_tokens): """ Invokes a model with a multimodal prompt. Args: bedrock_runtime: The Amazon Bedrock boto3 client. model_id (str): The model ID to use. messages (JSON) : The messages to send to the model. max_tokens (int) : The maximum number of tokens to generate. Returns: None. """ body = json.dumps( { "anthropic_version": "bedrock-2023-05-31", "max_tokens": max_tokens, "messages": messages } ) response = bedrock_runtime.invoke_model( body=body, modelId=model_id) response_body = json.loads(response.get('body').read()) return response_body def main(): """ Entrypoint for Anthropic Claude multimodal prompt example. """ try: bedrock_runtime = boto3.client(service_name='bedrock-runtime') model_id = 'anthropic.claude-3-sonnet-20240229-v1:0' max_tokens = 1000 input_image = "/path/to/image" input_text = "What's in this image?" # Read reference image from file and encode as base64 strings. with open(input_image, "rb") as image_file: content_image = base64.b64encode(image_file.read()).decode('utf8') message = {"role": "user", "content": [ {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": content_image}}, {"type": "text", "text": input_text} ]} messages = [message] response = run_multi_modal_prompt( bedrock_runtime, model_id, messages, max_tokens) print(json.dumps(response, indent=4)) except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) if __name__ == "__main__": main()

를 사용하여 멀티모달 프롬프트를 스트리밍합니다. InvokeModelWithResponseStream

다음 예제는 with 로 전송된 멀티모달 프롬프트에서 응답을 스트리밍하는 방법을 보여줍니다. Anthropic Claude 3 Sonnet InvokeModelWithResponseStream

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to stream the response from Anthropic Claude Sonnet (on demand) for a multimodal request. """ import json import base64 import logging import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def stream_multi_modal_prompt(bedrock_runtime, model_id, input_text, image, max_tokens): """ Streams the response from a multimodal prompt. Args: bedrock_runtime: The Amazon Bedrock boto3 client. model_id (str): The model ID to use. input_text (str) : The prompt text image (str) : The path to an image that you want in the prompt. max_tokens (int) : The maximum number of tokens to generate. Returns: None. """ with open(image, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) body = json.dumps({ "anthropic_version": "bedrock-2023-05-31", "max_tokens": max_tokens, "messages": [ { "role": "user", "content": [ {"type": "text", "text": input_text}, {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": encoded_string.decode('utf-8')}} ] } ] }) response = bedrock_runtime.invoke_model_with_response_stream( body=body, modelId=model_id) for event in response.get("body"): chunk = json.loads(event["chunk"]["bytes"]) if chunk['type'] == 'message_delta': print(f"\nStop reason: {chunk['delta']['stop_reason']}") print(f"Stop sequence: {chunk['delta']['stop_sequence']}") print(f"Output tokens: {chunk['usage']['output_tokens']}") if chunk['type'] == 'content_block_delta': if chunk['delta']['type'] == 'text_delta': print(chunk['delta']['text'], end="") def main(): """ Entrypoint for Anthropic Claude Sonnet multimodal prompt example. """ model_id = "anthropic.claude-3-sonnet-20240229-v1:0" input_text = "What can you tell me about this image?" image = "/path/to/image" max_tokens = 100 try: bedrock_runtime = boto3.client('bedrock-runtime') stream_multi_modal_prompt( bedrock_runtime, model_id, input_text, image, max_tokens) except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) if __name__ == "__main__": main()