기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
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 다음 예와 같이 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 을 참조하십시오.
코드 예시
다음 코드 예제는 메시지 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()