Anthropic Claude 消息 API - Amazon Bedrock

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

Anthropic Claude 消息 API

本节提供推理参数和代码示例,用于使用 Anthropic Claude 消息API。

Anthropic Claude 消息API概述

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

提示

本主题说明如何使用 Anthropic Claude API带有基本推理操作(InvokeModelInvokeModelWithResponseStream)的消息。但是,我们建议您使用 Converse API在您的应用程序中实现消息。这些区域有:Converse API提供了一组统一的参数,适用于所有支持消息的模型。有关更多信息,请参阅 与... 进行对话 Converse API 操作

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

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

如果您使用的是预先填充来自的响应的技术 Claude (使用最后一个助手角色 Message 填写克劳德回复的开头),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"}]}

有关为创建提示的信息 Anthropic Claude 模型,参见《提示简介》中的 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?" } ] } ] }
注意

以下限制适用于 content 字段:

  • 您最多可以包含 20 个图像。每个图像的大小、高度和宽度必须分别不超过 3.75 MB、8000 像素和 8000 像素。

  • 您最多可以包含五个文档。每个文档的大小不得超过 4.5 MB。

  • 如果 roleuser,则只能包含图像和文档。

您在请求中包含的每张图像都计入您的词元使用量。有关更多信息,请参阅《》中的图片费用 Anthropic 文档中)。

工具使用(函数调用)

With Anthropic Claude 3 个模型,你可以指定模型可以用来回复消息的工具。例如,您可以指定一种工具来获取电台热门歌曲。如果用户传递消息最受欢迎的歌曲WZPZ是什么? ,模型确定您指定的工具可以帮助回答问题。在响应中,模型将请求您代表其运行该工具。然后,您运行该工具并将工具结果传递给模型,然后模型会生成对原始消息的响应。有关更多信息,请参阅《》中的工具使用(函数调用) Anthropic Claude 文档中)。

提示

我们建议您使用 Converse API用于将工具的使用集成到您的应用程序中。有关更多信息,请参阅 使用工具完成 Amazon Bedrock 模型响应

您可以在 tools 字段中指定想供模型使用的工具。以下示例展示了一种用于获取电台热门歌曲的工具。

[ { "name": "top_song", "description": "Get the most popular song played on a radio station.", "input_schema": { "type": "object", "properties": { "sign": { "type": "string", "description": "The call sign for the radio station for which you want the most popular song. Example calls signs are WZPZ and WKRP." } }, "required": [ "sign" ] } } ]

当模型需要工具来生成对消息的响应时,它会在消息 content 字段中返回有关所请求工具的信息以及对该工具的输入。它还会将响应的停止原因设置为 tool_use

{ "id": "msg_bdrk_01USsY5m3XRUF4FCppHP8KBx", "type": "message", "role": "assistant", "model": "claude-3-sonnet-20240229", "stop_sequence": null, "usage": { "input_tokens": 375, "output_tokens": 36 }, "content": [ { "type": "tool_use", "id": "toolu_bdrk_01SnXQc6YVWD8Dom5jz7KhHy", "name": "top_song", "input": { "sign": "WZPZ" } } ], "stop_reason": "tool_use" }

在代码中,您代表工具调用该工具。然后,您在用户消息中将工具结果 (tool_result) 传递给模型。

{ "role": "user", "content": [ { "type": "tool_result", "tool_use_id": "toolu_bdrk_01SnXQc6YVWD8Dom5jz7KhHy", "content": "Elemental Hotel" } ] }

在其响应中,模型使用工具结果为原始消息生成响应。

{ "id": "msg_bdrk_012AaqvTiKuUSc6WadhUkDLP", "type": "message", "role": "assistant", "model": "claude-3-sonnet-20240229", "content": [ { "type": "text", "text": "According to the tool, the most popular song played on radio station WZPZ is \"Elemental Hotel\"." } ], "stop_reason": "end_turn" }

计算机使用(测试版)

计算机的使用是一种新事物 Anthropic Claude 模型功能(测试版)仅在 Claude 3.5 Sonnet v2 中提供。使用电脑时,Claude 可以帮助您通过基本GUI操作自动执行任务。

警告

根据服务条款的定义,计算机使用功能作为 “测试版服务” 提供给AWS您。它受您的协议AWS和AWS服务条款以及适用的模型的约束EULA。请注意,计算机使用API会带来与标准API功能或聊天界面不同的独特风险。当使用 “计算机使用” 与互联网进行API交互时,这些风险会增加。为了最大限度地降低风险,请考虑采取如下预防措施:

  • 在具有最低权限的专用虚拟机或容器中操作计算机使用功能,以防止直接的系统攻击或事故。

  • 为防止信息被盗,请避免授予计算机用户API访问敏感帐户或数据的权限。

  • 将计算机用户API的 Internet 访问限制在所需的域中,以减少对恶意内容的暴露。

  • 请人工随时关注敏感任务(例如做出可能导致实际后果的决策)和任何需要肯定同意的操作(例如接受 Cookie、执行金融交易或同意服务条款),以确保进行适当的监督。

您启用的任何内容 Claude 查看或访问可能会覆盖说明或原因 Claude 犯错误或执行意想不到的行动。采取适当的预防措施,例如隔离 Claude 来自敏感表面,是必不可少的,包括避免与及时注射相关的风险。在启用或请求必要的权限以在您自己的产品中启用计算机使用功能之前,请告知终端用户任何相关风险,并酌情征得他们的同意。

计算机使用API提供了几种预定义的计算机使用工具(comp uter_20241022、bash_20241022 和 text_editor_20 241022)供你使用。然后,您可以根据您的请求创建提示,例如“向 Ben 发送一封包含我上次会议笔记的电子邮件”和屏幕截图(如果需要)。响应包含JSON格式化的tool_use操作列表(例如,向下滚动、left_button_press、屏幕截图)。您的代码运行计算机操作并提供 Claude 屏幕截图显示输出(如果需要)。

Tools 参数已更新为接受多态工具类型;添加了一个新的 tool.type 属性来区分它们。type 是可选的;如果省略该属性,则假定该工具为自定义工具(以前是唯一支持的工具类型)。此外,还添加了一个新参数 anthropic_beta,且带有相应枚举值:computer-use-2024-10-22。只有使用此参数和枚举值发出的请求才能使用新的计算机使用工具。可以按如下方式指定此参数:"anthropic_beta": ["computer-use-2024-10-22"]

有关更多信息,请参阅《计算机使用(测试版)》中的 Anthropic 文档中)。

以下是一个示例响应,它假定请求包含带有 Firefox 图标的桌面屏幕截图。

{ "id": "msg_123", "type": "message", "role": "assistant", "model": "anthropic.claude-3-5-sonnet-20241022-v2:0", "content": [ { "type": "text", "text": "I see the Firefox icon. Let me click on it and then navigate to a weather website." }, { "type": "tool_use", "id": "toolu_123", "name": "computer", "input": { "action": "mouse_move", "coordinate": [ 708, 736 ] } }, { "type": "tool_use", "id": "toolu_234", "name": "computer", "input": { "action": "left_click" } } ], "stop_reason": "tool_use", "stop_sequence": null, "usage": { "input_tokens": 3391, "output_tokens": 132 } }

支持的模型

您可以将消息API与以下内容一起使用 Anthropic Claude 模型。

  • Anthropic Claude Instant v1.2

  • Anthropic Claude 2 v2

  • Anthropic Claude 2 v2.1

  • Anthropic Claude 3 Sonnet

  • Anthropic Claude 3.5 Sonnet

  • Anthropic Claude 3.5 Sonnet v2

  • Anthropic Claude 3 Haiku

  • Anthropic Claude 3 Opus

请求和响应

请求正文在请求body字段中传递给InvokeModelInvokeModelWithResponseStream。您可以在请求中发送的最大有效载荷大小为 20 MB。

有关更多信息,请参阅https://docs.anthropic.com/claude/参考文献/ 消息帖子。

Request

Anthropic Claude 具有以下用于消息推理调用的推理参数。

{ "anthropic_version": "bedrock-2023-05-31", "anthropic_beta": ["computer-use-2024-10-22"] "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, "tools": [ { "type": "custom", "name": string, "description": string, "input_schema": json }, { "type": "computer_20241022", "name": "computer", "display_height_px": int, "display_width_px": int, "display_number": 0 int }, { "type": "bash_20241022", "name": "bash" }, { "type": "text_editor_20241022", "name": "str_replace_editor" } ], "tool_choice": { "type" : string, "name" : string, }, "stop_sequences": [string] }

以下是必要参数。

  • anthropic_version –(必要)Anthropic 版本。值必须为 bedrock-2023-05-31

  • anthropic_beta —(如果使用计算机则为必填项API)要使用的人类测试版。要使用计算机使用API,值必须为computer-use-2024-10-22

  • max_tokens –(必要)停止前要生成的最大词元数。

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

  • messages –(必要)输入消息。

    • role – 对话回合的角色。有效值为 userassistant

    • content –(必要)对话回合的内容。

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

        如果指定 image,您还必须使用以下格式指定图像来源

        source –(必要)对话回合的内容。

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

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

          • image/jpeg

          • image/png

          • image/webp

          • image/gif

        • data –(必要)图像的 base64 编码图像字节。最大图像大小为 3.75 MB。图像的最大高度和宽度为 8000 像素。

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

以下是可选参数。

  • system –(可选)请求的系统提示。

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

    注意

    您可以将系统提示与 Anthropic Claude 版本 2.1 或更高版本。

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

    条目的最大数量为 8191。

  • temperature –(可选)注入响应的随机性数量。

    默认 最小值 最大值

    1

    0

    1

  • top_p –(可选)使用 nucleus 采样。

    在原子核采样中,Anthropic Claude 按概率递减顺序计算每个后续代币在所有期权上的累积分布,并在达到由top_p指定的特定概率时将其切断。您应该更改 temperaturetop_p,但不能同时更改这两个。

    默认 最小值 最大值

    0.999

    0

    1

  • top_k –(可选)仅从每个后续词元的前 K 个选项中取样。

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

    默认 最小值 最大值

    默认情况下禁用

    0

    500

  • tools –(可选)模型可能使用的工具的定义。

    注意

    需要一个 Anthropic Claude 3 个模型。

    如果您在请求中包含 tools,则模型可能会返回 tool_use 内容块,表示该模型使用这些工具。然后,您可以使用模型生成的工具输入来运行这些工具,接着使用 tool_result 内容块选择性地将结果返回到模型。

    您可以传递以下工具类型:

    自定义

    自定义工具的定义。

    • (可选)type – 工具的类型。如果已定义,则使用值 custom

    • name - 工具的名称。

    • description –(可选,但强烈推荐)工具的描述。

    • input_schem a-JSON 工具的架构。

    计算机

    与计算机一起使用的计算机工具的定义API。

    • type – 值必须为 computer_20241022

    • name – 值必须为 computer

    • (必要)display_height_px – 模型控制的显示屏高度,以像素为单位。

      默认 最小值 最大值

      1

      无最大值

    • (必要)display_width_px – 模型控制的显示屏宽度,以像素为单位。

      默认 最小值 最大值

      1

      无最大值

    • (可选)display_number – 要控制的显示屏编号(仅与 X11 环境相关)。如果指定,则将在工具定义中为该工具提供显示屏编号。

      默认 最小值 最大值

      0

      N

    bash

    与计算机一起使用的 bash 工具的定义。API

    • (可选)type – 值必须为 bash_20241022

    • name – 值必须为 bash

    文本编辑器

    用于计算机的文本编辑器工具的定义API。

    • (可选)type – 值必须为 text_editor_20241022

    • name – 值必须为 str_replace_editor

  • tool_choice –(可选)指定模型应如何使用提供的工具。模型可以使用特定的工具、任何可用的工具,也可以自行决定使用什么工具。

    注意

    需要一个 Anthropic Claude 3 个模型。

    • type – 选择的工具类型。可能的值是 any(使用任何可用的工具)、auto(由模型决定)和 tool(使用指定的工具)。

    • name –(可选)要使用的工具的名称。如果您在 type 字段中指定 tool,则为必要参数。

Response

这些区域有:Anthropic Claude model 为消息推理调用返回以下字段。

{ "id": string, "model": string, "type" : "message", "role" : "assistant", "content": [ { "type": string, "text": string } ], "stop_reason": string, "stop_sequence": string, "tool_use" : { "type": string, "id" : string, "input" : json }, "usage": { "input_tokens": integer, "output_tokens": integer } }
  • id – 响应的唯一标识符。ID 的格式和长度可能会随着时间的推移而改变。

  • 模型 — 的 ID Anthropic Claude 提出请求的模型。

  • stop_reason — 原因 Anthropic Claude 停止生成响应。

    • end_turn – 模型达到了自然停止点

    • max_tokens – 生成的文本超过了 max_tokens 输入字段的值或超过了模型支持的最大词元数量。

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

  • stop_sequence – 结束生成的停止序列。

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

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

  • content – 模型生成的内容。以数组形式返回。有两种类型的内容:texttool_use

    • text – 文本响应。

      • type – 此值为 text。内容的类型。

      • text – 内容的文本。

    • tool_use – 模型发出的使用工具的请求。

      • type – 此值为 text。内容的类型。

      • id – 模型请求使用的工具的 ID。

      • input – 要传递给工具的输入参数。

  • usage – 用于存放您在请求中提供的词元数量以及模型在响应中生成的词元数量的容器。

    • input_tokens – 请求中的输入词元数量。

    • output_tokens – 模型在响应中生成的词元数量。

    • 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

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

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