AnthropicClaude消息 API - Amazon Bedrock

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

AnthropicClaude消息 API

本节提供推理参数和使用AnthropicClaude消息 API 的代码示例。

AnthropicClaude消息 API 概述

你可以使用 Messages API 来创建聊天机器人或虚拟助手应用程序。API 管理用户和AnthropicClaude模特(助手)之间的对话交流。

Anthropic训练 Claude 模型在交替的用户和助手对话回合中进行操作。创建新消息时,您可以使用 messages 参数指定之前的对话回合。然后,模型在对话中生成下一条消息。

每条输入消息都必须是一个具有角色和内容的对象。您可以指定一条用户角色消息,也可以包含多条用户和助手消息。第一条消息必须始终使用用户角色。

如果你使用的是预填回复的技巧Claude(使用最后一个助手角色 Message 填写 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{"}, ]

每个输入消息内容可以是单个字符串,也可以是内容块数组,其中每个块都有特定的类型。使用字符串是由 “文本” 类型的一个内容块组成的数组的简写。以下输入消息是等效的:

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

有关为AnthropicClaude模型创建提示的信息,请参阅文档中的提示简介。Anthropic Claude如果您想要迁移到消息 API 的现有文本完成提示,请参阅从文本完成迁移

系统提示

您还可以在请求中加入系统提示。系统提示允许您为其提供上下文和说明 AnthropicClaude,例如指定特定的目标或角色。在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输入字段中指定模式。以下示例显示了AnthropicClaude如何要求描述所提供图片的内容。有关代码示例,请参阅 多式联运代码示例

{ "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 与以下AnthropicClaude模型配合使用。

  • AnthropicClaudeInstantv1.2

  • AnthropicClaude2 v2

  • AnthropicClaude2 v2.1

  • Anthropic Claude 3 Sonnet

  • Anthropic Claude 3 Haiku

请求和响应

请求正文在请求body字段中传递给InvokeModelInvokeModelWithResponseStream。您可以在请求中发送的最大负载大小为 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 s —(必填)停止前要生成的最大令牌数。

    请注意,AnthropicClaude模型可能会在达到的值之前停止生成代币max_tokens。不同的AnthropicClaude模型对此参数有不同的最大值。有关更多信息,请参阅模型比较

  • 消息-(必填)输入消息。

    • 角色 — 对话的角色转向。有效值为 userassistant

    • 内容 —(必填)对话的内容转向。

      • type —(必填)内容的类型。有效值为 imagetext

        如果指定image,则还必须按以下格式指定图像源

        s@@ ourc e —(必填)对话内容转向。

        • type —(必填)图像的编码类型。您可以指定base64

        • media_type —(必填)图像的类型。您可以指定以下图像格式。

          • image/jpeg

          • image/png

          • image/webp

          • image/gif

        • 数据-(必填)图像的 base64 编码图像字节。最大图像大小为 3.75MB。图像的最大高度和宽度为 8000 像素。

        如果指定text,则还必须在中指定提示text

以下是可选参数。

  • s@@ y stem —(可选)请求的系统提示符。

    系统提示是向其提供上下文和说明的一种方式 AnthropicClaude,例如指定特定的目标或角色。有关更多信息,请参阅Anthropic文档中的如何使用系统提示

    注意

    您可以在 2.1 或更高AnthropicClaude版本中使用系统提示。

  • stop_seq uences —(可选)导致模型停止生成的自定义文本序列。 AnthropicClaude模型通常在自然完成回合后停止,在本例中,stop_reason响应字段的值为end_turn。如果您希望模型在遇到自定义文本字符串时停止生成,则可以使用stop_sequences参数。如果模型遇到其中一个自定义文本字符串,则stop_reason响应字段的值为stop_sequence,的值stop_sequence包含匹配的停止序列。

    最大条目数为 8191。

  • 温度-(可选)注入响应的随机性量。

    默认 最低 最高

    1

    0

    1

  • top_p —(可选)使用原子核采样。

    在 nucleus 采样中,按概率递减顺序AnthropicClaude计算每个后续代币的所有选项的累积分布,并在达到由指定的特定概率后将其切断。top_p您应该更改其中一个temperaturetop_p,但不能同时更改两个。

    默认 最低 最高

    0.999

    0

    1

以下是可选参数。

  • top_k —(可选)仅从每个后续令牌的前 K 个选项中取样。

    用于top_k移除长尾低概率响应。

    默认 最低 最高

    默认情况下处于禁用状态

    0

    100,000,000

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 — 响应的唯一标识符。身份证的格式和长度可能会随着时间的推移而改变。

  • 模型-发出请求的AnthropicClaude模型的 ID。

  • stop_ reason — Anthropic Claude 停止生成响应的原因。

    • end_tur n — 模型到达了自然停止点

    • max_token s — 生成的文本超过了max_tokens输入字段的值或超过了模型支持的最大标记数。'.

    • stop_seq uence — 模型生成了您在stop_sequences输入字段中指定的一个停止序列。

  • 类型-响应的类型。此值始终为 message

  • 角色-生成的消息的对话角色。此值始终为 assistant

  • 内容-模型生成的内容。以数组形式返回。

    • 类型-内容的类型。目前唯一支持的值是 text

    • 文本-内容的文本。

  • 用法 — 容器,用于存放您在请求中提供的令牌数量以及模型在响应中生成的令牌数量。

    • input_token s — 请求中输入令牌的数量。

    • ou@@ tput_tok ens — 模型在响应中生成的标记数。

    • stop_seq uence — 模型生成了您在stop_sequences输入字段中指定的一个停止序列。

代码示例

以下代码示例展示了如何使用消息 API。

消息代码示例

此示例说明如何向AnthropicClaude 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()

多式联运代码示例

以下示例说明如何将多式联运消息中的图像和提示文本传递给AnthropicClaude 3 Sonnet模型。

多式联运提示 InvokeModel

以下示例说明如何向 with 发送多式联运AnthropicClaude 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

以下示例说明如何将发送到的多式联运提示中的响应流AnthropicClaude 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()