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 (使用最終助理角色訊息,在 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"}]}

如需建立 提示的相關資訊 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、8,000 px 和 8,000 px。

  • 您最多可以包含五個文件。每個文件的大小不得超過 4.5 MB。

  • 如果 role是 ,您只能包含映像和文件user

您在請求中包含的每個影像都會計入您的字符用量。如需詳細資訊,請參閱 中的映像成本 Anthropic 文件中)。

工具使用 (函數呼叫)

使用 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" }

電腦使用 (Beta 版)

電腦使用是新的 Anthropic Claude 模型功能 (測試版) 僅適用於 Claude 3.5 Sonnet v2。使用電腦時,Claude 可協助您透過基本GUI動作自動化任務。

警告

電腦使用功能會以「Beta Service」的形式提供給您,如 AWS 服務條款所定義。它受您與 AWS和 AWS 服務條款以及適用模型 的協議約束EULA。請注意,電腦使用API會帶來與標準API功能或聊天介面不同的唯一風險。使用電腦使用 API 與網際網路互動時,這些風險會提高。為了將風險降至最低,請考慮採取預防措施,例如:

  • 操作電腦使用專用虛擬機器中的功能,或具有最低權限的容器中的功能,以防止直接系統攻擊或意外。

  • 為了防止資訊遭竊,請避免讓電腦使用API存取敏感帳戶或資料。

  • 限制電腦使用 API對必要網域的網際網路存取,以減少對惡意內容的暴露。

  • 為了確保適當的監督,請讓人類參與敏感任務 (例如做出可能有有意義的實際後果的決策) 以及任何需要明確同意 (例如接受 Cookie、執行金融交易,或同意服務條款) 的循環。

您啟用的任何內容 Claude 查看或存取可能會覆寫指示或導致 Claude 來犯錯或執行非預期的動作。採取適當的預防措施,例如隔離 Claude 來自敏感表面是必要的,包括避免與快速注入相關的風險。在啟用或請求啟用自有產品中電腦使用功能所需的許可之前,請通知最終使用者任何相關風險,並視需要取得他們的同意。

電腦使用API提供多種預先定義的電腦使用工具 ( computer_20241022Bash_20241022text_editor_20241022) 供您使用。然後,您可以使用您的請求建立提示,例如「傳送電子郵件給 Ben 並附上上次會議的備註」和螢幕擷取畫面 (必要時)。回應包含 JSON 格式tool_use的動作清單 (例如 scroll_down、left_button_press、螢幕擷取畫面)。您的程式碼會執行電腦動作並提供 Claude 螢幕擷取畫面,顯示輸出 (如要求)。

工具參數已更新為接受多態性工具類型;正在新增新的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 1.2 版

  • Anthropic Claude 2 v2

  • Anthropic Claude 2 2.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。您可以在請求中傳送的承載大小上限為 20MB。

如需詳細資訊,請參閱 https://docs.anthropic.com/claude/reference/messages_post

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 – (必要) thropic 版本。值必須為 bedrock-2023-05-31

  • anthropic_beta – (必要,如果使用電腦,請使用 API) 要使用的anthropic beta。若要使用電腦使用 API,值必須為 computer-use-2024-10-22

  • max_tokens – (必要) 停止之前要產生的字符數量上限。

    請注意 Anthropic Claude 模型可能會在達到 的值之前停止產生字符max_tokens。不同 Anthropic Claude 此參數的模型具有不同的最大值。如需詳細資訊,請參閱模型比較

  • 訊息 – (必要) 輸入訊息。

    • 角色 – 對話輪換的角色。有效值為 userassistant

    • 內容 – (必要) 對話內容輪換。

      • type – (必要) 內容的類型。有效值為 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 文件中)。

    注意

    您可以搭配 使用系統提示 Anthropic Claude 2.1 版或更新版本。

  • stop_sequences – (選用) 導致模型停止產生的自訂文字序列。Anthropic Claude 模型通常會在自然完成輪換時停止,在此情況下,stop_reason回應欄位的值為 end_turn。如果您希望模型在遇到自訂文字字串時停止產生,您可以使用 stop_sequences 參數。如果模型遇到其中一個自訂文字字串,stop_reason回應欄位的值為 ,stop_sequence而 的值stop_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內容區塊將結果傳回給模型。

    您可以傳遞下列工具類型:

    自訂

    自訂工具的定義。

    • (選用) 類型 – 工具的類型。如果已定義,請使用 值 custom

    • name – 工具的名稱。

    • description – (選用,但強烈建議) 工具的描述。

    • input_schema – JSON 工具的結構描述。

    Computer

    您搭配電腦使用之電腦工具的定義會使用 API。

    • type – 值必須為 computer_20241022

    • name – 值必須為 computer

    • (必要) display_height_px – 模型控制的顯示器高度,以像素為單位。

      預設 下限 最大

      1

      無上限

    • (必要) display_width_px – 模型控制的顯示器寬度,以像素為單位。

      預設 下限 最大

      1

      無上限

    • (選用) display_number – 要控制的顯示編號 (僅適用於 X11 環境)。如果指定,工具將在工具定義中提供一個顯示編號。

      預設 下限 最大

      0

      N

    bash

    您搭配電腦使用的 bash 工具定義會使用 API。

    • (選用) 類型 – 值必須為 bash_20241022

    • name – 值必須是 bash。 工具。

    文字編輯器

    您搭配電腦使用的文字編輯器工具定義會使用 API。

    • (選用) 類型 – 值必須為 text_editor_20241022

    • name – 值必須是 str_replace_editor。 工具。

  • tool_choice – (選用) 指定模型應該如何使用提供的工具。模型可以使用特定工具、任何可用的工具或自行決定。

    注意

    需要 Anthropic Claude 3 個模型。

    • type – 工具選擇類型。可能的值為 any(使用任何可用的工具)、 auto (模型決定) 和 tool(使用指定的工具)。

    • name – (選用) 要使用的工具名稱。如果您在 type 欄位中指定 tool ,則為必要。

Response

所以此 Anthropic Claude 模型會傳回訊息推論呼叫的下列欄位。

{ "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

  • 角色 – 產生訊息的對話角色。值一律為 assistant

  • 內容 – 模型產生的內容。傳回為陣列。內容有兩種類型,text以及 tool_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()