View a markdown version of this page

包含防護機制與 Converse API - Amazon Bedrock

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

包含防護機制與 Converse API

您可以使用防護機制來保護您使用 Converse API 建立的對話式應用程式。例如,如果您使用 Converse API 建立聊天應用程式,可以使用防護機制來封鎖使用者輸入的不適當內容,以及模型產生的不適當內容。如需 Converse API 的相關資訊,請參閱 使用 Converse API 進行推論

使用防護機制呼叫 Converse API

若要使用防護機制,請在呼叫 ConverseConverseStream (用於串流回應) 操作時,包含防護機制的組態資訊。或者,您可以在您希望防護機制評估的訊息中選取特定內容。如需可與護欄和 Converse API 搭配使用之模型的相關資訊,請參閱模型一目了然

設定防護機制以使用 Converse API

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

使用 Converse 操作時,guardrailConfigGuardrailConfiguration 物件,如下列範例所示。

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

如果您使用 ConverseStream,則會傳遞 GuardrailStreamConfiguration 物件。或者,您可以使用 streamProcessingMode 欄位指定您希望模型在傳回串流回應區塊之前完成防護機制評估。或者,您可以讓模型以非同步方式回應,同時防護機制在背景繼續其評估。如需詳細資訊,請參閱設定串流回應行為以篩選內容

僅評估訊息中的特定內容

當您將訊息傳遞至模型時,防護機制會評估訊息中的內容。您也可以使用 guardContent (GuardrailConverseContentBlock) 欄位來評估訊息的特定部分。

提示

使用 guardContent 欄位類似於搭配 InvokeModelInvokeModelWithResponseStream 使用輸入標籤。如需詳細資訊,請參閱將標籤套用至使用者輸入以篩選內容

例如,下列防護機制只會評估 guardContent 欄位中的內容,而不會評估訊息的其餘部分。這對於讓防護機制僅評估對話中的最新訊息很有用,如下列範例所示。

重要

一旦您在訊息的任何位置包含guardContent區塊,護欄只會評估guardContent區塊中的內容。所有其他未包裝的內容區塊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. \"Blinding Lights\" by The Weeknd\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." } } } ] } ]

guardContent 的另一個使用案例是為訊息提供額外的內容,而您的防護機制不會評估該內容。在下列範例中,防護機制只會評估 "Create a playlist of heavy metal songs" 而忽略 "Only answer with a list of songs"

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

如果內容不在 guardContent 區塊中,這不一定表示不會進行評估。此行為取決於防護機制使用的篩選政策。

下列範例顯示具有情境依據檢查 (根據 qualifiers 欄位) 的兩個 guardContent 區塊。防護機制中的情境依據檢查只會評估這些區塊中的內容。不過,如果防護機制也有封鎖「背景」一詞的字詞篩選條件,則「某些額外的背景資訊。」文字 仍會進行評估,即使字詞不在 guardContent 區塊中也一樣。

[{ "role": "user", "content": [{ "guardContent": { "text": { "text": "London is the capital of UK. Tokyo is the capital of Japan.", "qualifiers": ["grounding_source"] } } }, { "text": "Some additional background information." }, { "guardContent": { "text": { "text": "What is the capital of Japan?", "qualifiers": ["query"] } } } ] }]

保護傳送至 Converse API 的系統提示

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

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

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

訊息和系統提示防護機制行為

防護機制如何評估您在訊息中傳遞的系統提示與訊息之間的 guardContent 欄位行為不同。

系統提示具有防護機制區塊 系統提示沒有防護機制區塊

訊息具有防護機制區塊

系統:防護機制會調查防護機制區塊中的內容

訊息:防護機制會調查防護機制區塊中的內容

系統:防護機制不會調查任何內容

訊息:防護機制會調查防護機制區塊中的內容

訊息沒有防護機制區塊

系統:防護機制會調查防護機制區塊中的內容

訊息:防護機制會調查所有內容

系統:防護機制不會調查任何內容

訊息:防護機制會調查所有內容

使用 Converse API 時處理回應

當您呼叫 Converse 操作時,防護機制會評估您傳送的訊息。如果防護機制偵測到封鎖的內容,會發生下列情況。

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

  • 如果您啟用追蹤,則追蹤可在 trace (ConverseTrace) 欄位中使用。使用 ConverseStream,追蹤位於操作傳回的中繼資料 (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" } ] }, "invocationMetrics": { "guardrailProcessingLatency": 240, "usage": { "topicPolicyUnits": 1, "contentPolicyUnits": 0, "wordPolicyUnits": 0, "sensitiveInformationPolicyUnits": 0, "sensitiveInformationPolicyFreeUnits": 0, "contextualGroundingPolicyUnits": 0 }, "guardrailCoverage": { "textCharacters": { "guarded": 39, "total": 72 } } } } } } } }

搭配防護機制使用 Converse API 的程式碼範例

此範例說明如何保護與 ConverseConverseStream 操作的對話。此範例示範如何防止模型建立播放清單,其中包含重金屬類型的歌曲。

保護對話
  1. 遵循 建立防護機制 中的指示建立防護機制。

    • 名稱 – 輸入重金屬

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

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

    在步驟 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 <noloc>Converse</noloc> 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.nova-micro-v1:0" # 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()