Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.
AnthropicClaudePesan API
Bagian ini menyediakan parameter inferensi dan contoh kode untuk menggunakan Anthropic Claude Messages API.
AnthropicClaudeIkhtisar pesan API
Anda dapat menggunakan Messages API untuk membuat bot obrolan atau aplikasi asisten virtual. API mengelola pertukaran percakapan antara pengguna dan Anthropic Claude model (asisten).
Anthropicmelatih model Claude untuk beroperasi pada giliran percakapan pengguna dan asisten yang bergantian. Saat membuat pesan baru, Anda menentukan giliran percakapan sebelumnya dengan parameter pesan. Model kemudian menghasilkan Pesan berikutnya dalam percakapan.
Setiap pesan input harus berupa objek dengan peran dan konten. Anda dapat menentukan satu pesan peran pengguna, atau Anda dapat menyertakan beberapa pesan pengguna dan asisten. Pesan pertama harus selalu menggunakan peran pengguna.
Jika Anda menggunakan teknik pengisian awal respons dari Claude (mengisi awal respons Claude dengan menggunakan peran asisten akhir Pesan), Claude akan merespons dengan mengambil dari tempat Anda tinggalkan. Dengan teknik ini, masih Claude akan mengembalikan respons dengan peran asisten.
Jika pesan terakhir menggunakan peran asisten, konten respons akan langsung dilanjutkan dari konten dalam pesan tersebut. Anda dapat menggunakan ini untuk membatasi bagian dari respons model.
Contoh dengan pesan pengguna tunggal:
[{"role": "user", "content": "Hello, Claude"}]
Contoh dengan beberapa putaran percakapan:
[ {"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?"}, ]
Contoh dengan respons yang diisi sebagian dari Claude:
[ {"role": "user", "content": "Please describe yourself using only JSON"}, {"role": "assistant", "content": "Here is my JSON description:\n{"}, ]
Setiap konten pesan input dapat berupa string tunggal atau array blok konten, di mana setiap blok memiliki tipe tertentu. Menggunakan string adalah singkatan untuk array dari satu blok konten tipe “teks”. Pesan masukan berikut setara:
{"role": "user", "content": "Hello, Claude"}
{"role": "user", "content": [{"type": "text", "text": "Hello, Claude"}]}
Untuk informasi tentang membuat prompt untuk Anthropic Claude model, lihat Pengantar petunjuk dalam dokumentasi
Permintaan sistem
Anda juga dapat menyertakan prompt sistem dalam permintaan. Prompt sistem memungkinkan Anda memberikan konteks dan instruksi AnthropicClaude, seperti menentukan tujuan atau peran tertentu. Tentukan prompt sistem di system
lapangan, seperti yang ditunjukkan pada contoh berikut.
"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."
Untuk informasi selengkapnya, lihat Permintaan sistem
Permintaan multimodal
Prompt multimodal menggabungkan beberapa modalitas (gambar dan teks) dalam satu prompt. Anda menentukan modalitas di bidang content
input. Contoh berikut menunjukkan bagaimana Anda bisa meminta Anthropic Claude untuk mendeskripsikan konten gambar yang disediakan. Untuk kode sampel, lihat Contoh kode multimodal.
{ "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?" } ] } ] }
Anda dapat menyediakan hingga 20 gambar ke model. Anda tidak dapat menempatkan gambar dalam peran asisten.
Setiap gambar yang Anda sertakan dalam permintaan dihitung terhadap penggunaan token Anda. Untuk informasi selengkapnya, lihat Biaya gambar
Model yang didukung
Anda dapat menggunakan Messages API dengan Anthropic Claude model berikut.
AnthropicClaudeInstantv1.2
AnthropicClaude2 v2
AnthropicClaude2 v2.1
Anthropic Claude 3 Sonnet
Anthropic Claude 3 Haiku
Anthropic Claude 3 Opus
Permintaan dan Tanggapan
Badan permintaan diteruskan di body
bidang permintaan ke InvokeModelatau InvokeModelWithResponseStream. Ukuran maksimum muatan yang dapat Anda kirim dalam permintaan adalah 20MB.
Untuk informasi lebih lanjut, lihat https://docs.anthropic.com/claude/reference/messages_post
Contoh kode
Contoh kode berikut menunjukkan cara menggunakan API pesan.
Contoh kode pesan
Contoh ini menunjukkan cara mengirim pesan pengguna giliran tunggal dan giliran pengguna dengan pesan asisten yang telah diisi sebelumnya ke Anthropic Claude 3 Sonnet model.
# 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()
Contoh kode multimodal
Contoh berikut menunjukkan cara meneruskan gambar dan teks prompt dalam pesan multimodal ke Anthropic Claude 3 Sonnet model.
Topik
Prompt multimodal dengan InvokeModel
Contoh berikut menunjukkan cara mengirim prompt multimodal ke Anthropic Claude 3 Sonnet with 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()
Streaming prompt multimodal dengan InvokeModelWithResponseStream
Contoh berikut menunjukkan cara mengalirkan respons dari prompt multimodal yang dikirim ke Anthropic Claude 3 Sonnet with 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()