使用護欄與匡威 API - Amazon Bedrock

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用護欄與匡威 API

您可以使用護欄來保護您使用 Converse API 建立的對話式應用程式。例如,如果您使用 Converse API 創建聊天應用程序,則可以使用護欄阻止用戶輸入的不適當內容以及模型生成的不適當內容。如需有關匡威 API 的資訊,請參閱使用匡威 API

調用匡威 API

若要使用護欄,您可以在呼叫 ConverseConverseStream(用於串流回應) 作業中加入護欄的組態資訊。或者,您可以在要護欄評估的訊息中選取特定內容。如需可與護欄和 Converse API 搭配使用之模型的相關資訊,請參閱。支援的型號和模型特徵

配置護欄

您可以在guardrailConfig輸入參數中指定護欄的規劃資訊。組態包括 ID 和您要使用的護欄版本。您也可以啟用護欄的追蹤,以提供護欄封鎖之內容的相關資訊。

隨著Converse操作,guardrailConfig是一個GuardrailConfiguration對象,如下面的例子所示。

{ "guardrailIdentifier": "Guardrail ID", "guardrailVersion": "Guardrail version", "trace": "enabled" }

如果你使用ConverseStream,你傳遞一個GuardrailStreamConfiguration對象。或者,您可以使用streamProcessingMode欄位來指定您要模型在傳回串流回應區塊之前完成護欄評估。或者,您可以讓模型異步響應,而護欄在後台繼續其評估。如需詳細資訊,請參閱 設定串流回應行為

守護訊息

當您將訊息 (訊) 傳遞給模型時,護欄會評估訊息中的內容。或者,您可以透過指定 guardContent (GuardrailConverseContentBlock) 欄位來保護郵件中選取的內容。護欄僅評估guardContent欄位中的內容,而不會評估訊息的其餘部分。這對於讓護欄只評估交談中最多的訊息非常有用,如下列範例所示。

[ { "role": "user", "content": [ { "text": "Create a playlist of 2 pop songs." } ] }, { "role": "assistant", "content": [ { "text": " Sure! Here are two pop songs:\n1. \"Bad Habits\" by Ed Sheeran\n2. \"All Of The Lights\" by Kanye West\n\nWould you like to add any more songs to this playlist? " } ] }, { "role": "user", "content": [ { "guardContent": { "text": { "text": "Create a playlist of 2 heavy metal songs." } } } ] } ]

另一個用途是為消息提供額外的上下文,而不必讓護欄評估該附加上下文。

[ { "role": "user", "content": [ { "text": "Only answer with a list of songs." }, { "guardContent": { "text": { "text": "Create a playlist of heavy metal songs." } } } ] } ]
注意

使用該guardContent字段類似於使用帶InvokeModel有和的輸入標籤。InvokeModelWithResponseStream如需詳細資訊,請參閱 使用標籤選擇性評估用戶輸入

防護系統提示

您可以將護欄與傳送至 Converse API 的系統提示一起使用。若要保護系統提示,請在傳遞至 API 的系統提示中指定 guardContent (SystemContentBlock) 欄位,如下列範例所示。

[ { "guardContent": { "text": { "text": "Only respond with Welsh heavy metal songs." } } } ]

如果您未提供guardContent欄位,護欄不會評估系統提示訊息。

訊息和系統提示護欄行為

護欄評估guardContent欄位在系統提示與您傳入訊息的訊息之間的行為不同。

系統提示具有護欄圖塊 系統提示沒有護欄圖塊

訊息有護欄封鎖

系統:護欄調查護欄中的內容

訊息:護欄會調查護欄中的內容

系統:護欄什麼都不調查

訊息:護欄會調查護欄中的內容

訊息沒有護欄封鎖

系統:護欄調查護欄中的內容

消息:護欄調查一切

系統:護欄什麼都不調查

消息:護欄調查一切

處理響應

當您呼叫匡威作業時,護欄會評估您傳送的訊息。如果護欄偵測到封鎖的內容,會發生下列情況。

  • 回應中的stopReason欄位設定為guardrail_intervened

  • 如果您啟用追蹤,追蹤可在 trace (ConverseTrace) 欄位中使用。使用時ConverseStream,追蹤位於作業傳回的 metadata (ConverseStreamMetadataEvent) 中。

  • output (ConverseOutput) 欄位中傳回您在護欄中設定的封鎖內容文字。封鎖ConverseStream內容的文字會出現在串流訊息中。

下列部分回應會顯示封鎖的內容文字,以及護欄評估中的追蹤。護欄阻止了消息中的「重金屬」一詞。

{ "output": { "message": { "role": "assistant", "content": [ { "text": "Sorry, I can't answer questions about heavy metal music." } ] } }, "stopReason": "guardrail_intervened", "usage": { "inputTokens": 0, "outputTokens": 0, "totalTokens": 0 }, "metrics": { "latencyMs": 721 }, "trace": { "guardrail": { "inputAssessment": { "3o06191495ze": { "topicPolicy": { "topics": [ { "name": "Heavy metal", "type": "DENY", "action": "BLOCKED" } ] } } } } } }

範例程式碼

此範例顯示如何保護與ConverseConverseStream作業的交談。此範例顯示如何防止模型建立包含重金屬類型歌曲的播放清單。

為了保護對話
  1. 依照中的指示建立護欄。建立護欄在步驟 6a 中,輸入下列資訊以建立拒絕的主題:

    • 名稱 — 輸入重金屬

    • 主題定義 — 輸入避免提及重金屬音樂類型的歌曲

    • 新增範例片語 — 輸入建立重金屬歌曲的播放清單。

    在步驟 9 中,輸入以下內容:

    • 顯示封鎖提示的訊息 — 輸入抱歉,我無法回答有關重金屬音樂的問題。

    • 封鎖回應的訊息 — 輸入抱歉,模型產生了一個提到重金屬音樂的答案。

    您可以設定其他護欄選項,但此範例並不需要此選項。

  2. 依照中的指示建立護欄版本。建立和管理護欄版本

  3. 在下列程式碼範例 (ConverseConverseStream) 中,設定下列變數:

    • guardrail_id— 您在步驟 1 中建立的護欄 ID。

    • guardrail_version— 您在步驟 2 中建立的護欄版本。

    • text— 使用 Create a playlist of heavy metal songs.

  4. 執行程式碼範例。輸出應該顯示護欄評估和輸出消息。Text: Sorry, I can't answer questions about heavy metal music.護欄輸入評估顯示模型在輸入訊息中偵測到「重金屬」一詞。

  5. (選擇性) 測試護欄是否封鎖模型產生的不適當文字,方法是text將的值變更為 [列出所有類型的搖滾音樂]。 。再次執行範例。您應該會在回應中看到輸出評估。

Converse

以下代碼將您的護欄與操作一Converse起使用。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to use a guardrail with the Converse API. """ import logging import json import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_conversation(bedrock_client, model_id, messages, guardrail_config): """ Sends a message to a model. Args: bedrock_client: The Boto3 Bedrock runtime client. model_id (str): The model ID to use. messages JSON): The message to send to the model. guardrail_config : Configuration for the guardrail. Returns: response (JSON): The conversation that the model generated. """ logger.info("Generating message with model %s", model_id) # Send the message. response = bedrock_client.converse( modelId=model_id, messages=messages, guardrailConfig=guardrail_config ) return response def main(): """ Entrypoint for example. """ logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") # The model to use. model_id="meta.llama3-8b-instruct-v1:0" # The ID and version of the guardrail. guardrail_id = "Your guardrail ID" guardrail_version = "DRAFT" # Configuration for the guardrail. guardrail_config = { "guardrailIdentifier": guardrail_id, "guardrailVersion": guardrail_version, "trace": "enabled" } text = "Create a playlist of 2 heavy metal songs." context_text = "Only answer with a list of songs." # The message for the model and the content that you want the guardrail to assess. messages = [ { "role": "user", "content": [ { "text": context_text, }, { "guardContent": { "text": { "text": text } } } ] } ] try: print(json.dumps(messages, indent=4)) bedrock_client = boto3.client(service_name='bedrock-runtime') response = generate_conversation( bedrock_client, model_id, messages, guardrail_config) output_message = response['output']['message'] if response['stopReason'] == "guardrail_intervened": trace = response['trace'] print("Guardrail trace:") print(json.dumps(trace['guardrail'], indent=4)) for content in output_message['content']: print(f"Text: {content['text']}") except ClientError as err: message = err.response['Error']['Message'] logger.error("A client error occurred: %s", message) print(f"A client error occured: {message}") else: print( f"Finished generating text with model {model_id}.") if __name__ == "__main__": main()
ConverseStream

以下代碼將您的護欄與操作一ConverseStream起使用。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to use a guardrail with the ConverseStream operation. """ import logging import json import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def stream_conversation(bedrock_client, model_id, messages, guardrail_config): """ Sends messages to a model and streams the response. Args: bedrock_client: The Boto3 Bedrock runtime client. model_id (str): The model ID to use. messages (JSON) : The messages to send. guardrail_config : Configuration for the guardrail. Returns: Nothing. """ logger.info("Streaming messages with model %s", model_id) response = bedrock_client.converse_stream( modelId=model_id, messages=messages, guardrailConfig=guardrail_config ) stream = response.get('stream') if stream: for event in stream: if 'messageStart' in event: print(f"\nRole: {event['messageStart']['role']}") if 'contentBlockDelta' in event: print(event['contentBlockDelta']['delta']['text'], end="") if 'messageStop' in event: print(f"\nStop reason: {event['messageStop']['stopReason']}") if 'metadata' in event: metadata = event['metadata'] if 'trace' in metadata: print("\nAssessment") print(json.dumps(metadata['trace'], indent=4)) def main(): """ Entrypoint for streaming message API response example. """ logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") # The model to use. model_id = "amazon.titan-text-express-v1" # The ID and version of the guardrail. guardrail_id = "Change to your guardrail ID" guardrail_version = "DRAFT" # Configuration for the guardrail. guardrail_config = { "guardrailIdentifier": guardrail_id, "guardrailVersion": guardrail_version, "trace": "enabled", "streamProcessingMode" : "sync" } text = "Create a playlist of heavy metal songs." # The message for the model and the content that you want the guardrail to assess. messages = [ { "role": "user", "content": [ { "text": text, }, { "guardContent": { "text": { "text": text } } } ] } ] try: bedrock_client = boto3.client(service_name='bedrock-runtime') stream_conversation(bedrock_client, model_id, messages, guardrail_config) except ClientError as err: message = err.response['Error']['Message'] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) else: print( f"Finished streaming messages with model {model_id}.") if __name__ == "__main__": main()