本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
您可以使用護欄來保護您使用 Converse API 建立的對話應用程式。例如,如果您使用 Converse API 建立聊天應用程式,您可以使用護欄來封鎖使用者輸入的不適當內容,以及模型產生的不適當內容。如需 Converse API 的相關資訊,請參閱 與 Converse API 操作進行對話。
使用護欄呼叫 Converse API
若要使用護欄,請在呼叫 Converse 或 ConverseStream (用於串流回應) 操作時包含護欄的組態資訊。或者,您可以在您希望護欄評估的訊息中選取特定內容。如需可與護欄和 Converse API 搭配使用之模型的相關資訊,請參閱 支援的模型和模型功能。
設定護欄以使用 Converse API
您可以在guardrailConfig
輸入參數中指定護欄的組態資訊。組態包含 ID 和您要使用的護欄版本。您也可以啟用護欄的追蹤,提供護欄封鎖內容的相關資訊。
透過 Converse
操作, guardrailConfig
是 GuardrailConfiguration 物件,如下列範例所示。
{
"guardrailIdentifier": "Guardrail ID
",
"guardrailVersion": "Guardrail version
",
"trace": "enabled"
}
如果您使用 ConverseStream
,您會傳遞 GuardrailStreamConfiguration 物件。或者,您可以使用 streamProcessingMode
欄位指定您希望模型在傳回串流回應區塊之前完成護欄評估。或者,您可以讓模型非同步回應,同時護欄在背景繼續其評估。如需詳細資訊,請參閱設定串流回應行為以篩選內容。
使用 APIs 保護訊息以評估有害內容
當您將訊息 (訊息) 傳遞至模型時,護欄會評估訊息中的內容。或者,您可以透過指定 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."
}
}
}
]
}
]
另一個用途是為訊息提供額外的內容,而不讓護欄評估該額外內容。在下列範例中,護欄只會評估"Create a playlist of heavy metal songs"
和忽略 "Only answer with a list of 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 的系統提示
您可以將護欄與傳送至 Converse API 的系統提示搭配使用。若要保護系統提示,請在您傳遞給 API 的系統提示中指定 guardContent
(SystemContentBlock) 欄位,如下列範例所示。
[
{
"guardContent": {
"text": {
"text": "Only respond with Welsh heavy metal songs."
}
}
}
]
如果您未提供 guardContent
欄位,護欄不會評估系統提示訊息。
訊息和系統提示護欄行為
護欄評估guardContent
欄位在系統提示和您在訊息中傳遞的訊息之間的行為方式不同。
系統提示具有 Guardrail 區塊 | 系統提示沒有護欄區塊 | |
---|---|---|
訊息具有護欄區塊 |
系統:Guardrail 調查 Guardrail 區塊中的內容 訊息:Guardrail 會調查 Guardrail 區塊中的內容 |
系統:Guardrail 不會調查任何內容 訊息:Guardrail 會調查 Guardrail 區塊中的內容 |
訊息沒有護欄區塊 |
系統:Guardrail 調查 Guardrail 區塊中的內容 訊息:Guardrail 會調查所有項目 |
系統:Guardrail 不會調查任何內容 訊息:Guardrail 會調查所有項目 |
使用 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 的範例程式碼
此範例說明如何保護與 Converse
和 ConverseStream
操作的對話。此範例示範如何防止模型建立播放清單,其中包含重金屬類型的歌曲。
保護對話
-
遵循 中的指示建立護欄建立護欄。在步驟 6a 中,輸入下列資訊以建立拒絕的主題:
-
名稱 – 輸入重金屬。
-
主題的定義 – 輸入 避免提及來自重金屬音樂類型的歌曲。
-
新增範例片語 – 輸入建立重金屬歌曲的播放清單。
在步驟 9 中,輸入下列項目:
-
針對封鎖提示顯示的訊息 – 輸入對不起,我無法回答有關重金屬音樂的問題。
-
封鎖回應的訊息 – 輸入對不起,模型產生了提及重金屬音樂的答案。
您可以設定其他護欄選項,但此範例不需要。
-
-
遵循 中的指示建立護欄的版本建立護欄版本。
-
在下列程式碼範例 (Converse 和 ConverseStream) 中,設定下列變數:
guardrail_id
– 您在步驟 1 中建立的護欄 ID。guardrail_version
– 您在步驟 2 中建立的護欄版本。text
– 使用Create a playlist of heavy metal songs.
-
執行程式碼範例。輸出應會顯示護欄評估和輸出訊息
Text: Sorry, I can't answer questions about heavy metal music.
。護欄輸入評估顯示模型在輸入訊息中偵測到重金屬一詞。 -
(選用) 透過將 值變更為列出所有類型的搖滾音樂
text
,測試護欄封鎖模型產生的不適當文字。 再次執行範例。您應該會在回應中看到輸出評估。
下列程式碼會將您的護欄與 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()