

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

# 使用内容筛选条件阻止有害图像
<a name="guardrails-mmfilter"></a>

通过在护栏内配置内容筛选条件，Amazon Bedrock 护栏可帮助阻止不恰当或有害的图像。

**先决条件和限制**
+ 此功能仅支持纯图像，不支持包含嵌入式视频内容的图像。
+ 此功能通常适用于美国东部（弗吉尼亚北部）、美国西部（俄勒冈）、欧洲（法兰克福）和亚太地区（东京） AWS 区域，内容过滤器中支持仇恨、侮辱、性、暴力、不当行为和即时攻击类别。
+ 此功能已在美国东部（俄亥俄州）、亚太地区（孟买、首尔、新加坡、悉尼）、欧洲（爱尔兰、伦敦）和美国 GovCloud （美国西部） AWS 区域提供预览版，内容过滤器中支持仇恨、侮辱、性和暴力类别。
+ 此功能允许的最大图像尺寸为 8000 x 8000（对于 JPEG 和 PNG 文件）。
+ 用户可以上传大小不超过 4 MB 的图像，单次请求最多可以上传 20 个图像。
+ 默认限制为每秒 25 张图像。此值不可配置。
+ 仅支持 PNG 和 JPEG 格式的图像内容。

**概述**

仅支持对纯图像或包含文字的图像进行有害图像检测和阻止。在创建护栏时，用户可以单独选择图像选项或同时选择图像选项和文本选项，并将相应的筛选强度设置为**无**、**低**、**中**或**高**。如果同时选择这两种模态，这些阈值将适用于文本和图像内容。护栏将评估用户作为输入发送的图像，或作为模型响应的输出生成的图像。

下面介绍了支持检测有害图像内容的类别：
+ **仇恨** – 描述那些基于身份（例如种族、民族、性别、宗教、性取向、能力和国籍）对个人或群体进行歧视、批评、侮辱、谴责或非人性化语言攻击的内容。还包括展示仇恨团体符号、仇恨性符号的图像化和真实场景视觉内容，以及与各类宣扬歧视、种族主义和不容忍理念的组织相关的图像。
+ **侮辱** – 描述那些包含贬低、羞辱、嘲笑、侮辱或贬低语言的内容。这种语言也被标记为欺凌。还包括各种粗鲁、不尊重或冒犯性的手势，意在表达蔑视、愤怒或反对。
+ **色情** – 描述通过直接或间接提及身体部位、身体特征或性别来表示性兴趣、性活动或性唤起的内容。还包括展示隐私部位和涉及性交的性活动的图像。该类别同样包括其他以性为主题的漫画、动画、绘画、素描和插图内容。
+ **暴力** – 描述具有以下特征的内容：美化对个人、群体或事物施加身体疼痛、伤害或损伤的行为，或威胁要对个人、群体或事物施加身体疼痛、伤害或损伤。还包括与具有伤害意图的武器相关的图像。
+ **不当行为** – 描述那些寻求或提供有关参与犯罪活动、伤害、欺诈或利用个人、群体或机构的信息的输入提示和模型响应。
+ **提示攻击** – 描述旨在绕过基础模型的安全和审核功能以生成有害内容（也称为监狱突破）以及忽略和覆盖开发人员指定的指令（称为提示注入）的用户提示。需要使用输入标记才能应用提示攻击。提示攻击检测需要使用输入标签。

**Topics**
+ [使用图像内容筛选条件](#guardrails-use-mmfilter)
+ [使用 API 为图像配置内容筛选条件](#guardrails-use-mmfilter-configure)
+ [将图像过滤器配置为与 ApplyGuardrail API 配合使用](#guardrails-use-mmfilter-api)
+ [将图像筛选条件配置为与图像生成模型配合使用](#guardrails-use-mmfilter-image-models)

## 使用图像内容筛选条件
<a name="guardrails-use-mmfilter"></a>

**使用针对图像的内容筛选条件来创建或更新护栏**

在创建新的护栏或更新现有护栏时，除了现有的文本选项外，用户现在还会看到一个选择图像的选项。

**注意**  
默认情况下，文本选项处于启用状态，而图像选项需要明确启用。用户可以同时选择文本和图像，也可以选择其中一种，具体取决于使用案例。

**筛选条件分类和阻止级别**

筛选是根据用户输入和 FM 响应的置信度分类来完成的。所有用户输入和模型响应均按四个强度等级进行分类：“无”、“低”、“中”和“高”。筛选条件强度决定了筛选有害内容的灵敏度。随着筛选强度的提高，筛选掉有害内容的可能性就会增加，在应用程序中看到有害内容的可能性也会降低。同时选择了图像和文本选项时，将对两种模态的特定类别应用相同的筛选条件强度。

1. 要针对有害类别配置图像和文本筛选条件，请选择**配置有害类别筛选条件**。

1. 选择 “**文本 and/or ****图像**”，从模型的提示或回复中筛选文本或图像内容。

1. 为要应用于每个类别的筛选级别选择**“无”、“低”、“中”或“高”**。设置为**高**可以阻止适用于该筛选条件类别的大部分文本或图像。

1. 选择**对响应使用相同的有害类别筛选条件**，可以使用您为提示设置的相同筛选条件设置。您也可以不选择此选项，来为提示或响应设置不同的筛选级别。选择**重置阈值**可重置提示或响应的所有筛选级别。

1. 选择**查看并创建**或**下一步**以创建护栏。

## 使用 API 为图像配置内容筛选条件
<a name="guardrails-use-mmfilter-configure"></a>

您可以使用护栏 API，在 Amazon Bedrock 护栏中配置图像内容筛选条件。以下示例展示了应用不同有害内容类别和筛选条件强度的 Amazon Bedrock 护栏筛选条件。您可以使用此模板作为自己使用案例的示例。

对于 `contentPolicyConfig` 操作，`filtersConfig` 是一个对象，如以下示例所示。

**使用图像内容筛选条件创建护栏的 Python Boto3 代码示例**

```
import boto3
import botocore
import json


def main():
    bedrock = boto3.client('bedrock', region_name='us-east-1')
    try:
        create_guardrail_response = bedrock.create_guardrail(
            name='my-image-guardrail',
            contentPolicyConfig={
                'filtersConfig': [
                    {
                        'type': 'SEXUAL',
                        'inputStrength': 'HIGH',
                        'outputStrength': 'HIGH',
                        'inputModalities': ['TEXT', 'IMAGE'],
                        'outputModalities': ['TEXT', 'IMAGE']
                    },
                    {
                        'type': 'VIOLENCE',
                        'inputStrength': 'HIGH',
                        'outputStrength': 'HIGH',
                        'inputModalities': ['TEXT', 'IMAGE'],
                        'outputModalities': ['TEXT', 'IMAGE']
                    },
                    {
                        'type': 'HATE',
                        'inputStrength': 'HIGH',
                        'outputStrength': 'HIGH',
                        'inputModalities': ['TEXT', 'IMAGE'],
                        'outputModalities': ['TEXT', 'IMAGE']
                    },
                    {
                        'type': 'INSULTS',
                        'inputStrength': 'HIGH',
                        'outputStrength': 'HIGH',
                        'inputModalities': ['TEXT', 'IMAGE'],
                        'outputModalities': ['TEXT', 'IMAGE']
                    },
                    {
                        'type': 'MISCONDUCT',
                        'inputStrength': 'HIGH',
                        'outputStrength': 'HIGH',
                        'inputModalities': ['TEXT'],
                        'outputModalities': ['TEXT']
                    },
                    {
                        'type': 'PROMPT_ATTACK',
                        'inputStrength': 'HIGH',
                        'outputStrength': 'NONE',
                        'inputModalities': ['TEXT'],
                        'outputModalities': ['TEXT']
                    }
                ]
            },
            blockedInputMessaging='Sorry, the model cannot answer this question.',
            blockedOutputsMessaging='Sorry, the model cannot answer this question.',
        )
        create_guardrail_response['createdAt'] = create_guardrail_response['createdAt'].strftime('%Y-%m-%d %H:%M:%S')
        print("Successfully created guardrail with details:")
        print(json.dumps(create_guardrail_response, indent=2))
    except botocore.exceptions.ClientError as err:
        print("Failed while calling CreateGuardrail API with RequestId = " + err.response['ResponseMetadata']['RequestId'])
        raise err


if __name__ == "__main__":
    main()
```

## 将图像过滤器配置为与 ApplyGuardrail API 配合使用
<a name="guardrails-use-mmfilter-api"></a>

您可以通过 `ApplyGuardrail` API 对图像和文本内容使用内容筛选条件。此选项可让您在不调用 Amazon Bedrock 模型的情况下使用内容筛选条件设置。您可以按照 Amazon Bedrock 护栏支持的每个 Bedrock 基础模型的推理参数文档，在下方脚本中更新各种模型的请求有效载荷。

您可以按照 Amazon Bedrock 护栏支持的每个 Bedrock 基础模型的推理参数文档，在下方脚本中更新各种模型的请求有效载荷。

```
import boto3
import botocore
import json


guardrail_id = 'guardrail-id'
guardrail_version = 'DRAFT'
content_source = 'INPUT'
image_path = '/path/to/image.jpg'

with open(image_path, 'rb') as image:
    image_bytes = image.read()

content = [
    {
        "text": {
            "text": "Hi, can you explain this image art to me."
        }
    },
    {
        "image": {
            "format": "jpeg",
            "source": {
                "bytes": image_bytes
            }
        }
    }
]


def main():
    bedrock_runtime_client = boto3.client("bedrock-runtime", region_name="us-east-1")
    try:
        print("Making a call to ApplyGuardrail API now")
        response = bedrock_runtime_client.apply_guardrail(
            guardrailIdentifier=guardrail_id,
            guardrailVersion=guardrail_version,
            source=content_source,
            content=content
        )
        print("Received response from ApplyGuardrail API:")
        print(json.dumps(response, indent=2))
    except botocore.exceptions.ClientError as err:
        print("Failed while calling ApplyGuardrail API with RequestId = " + err.response['ResponseMetadata']['RequestId'])
        raise err


if __name__ == "__main__":
    main()
```

## 将图像筛选条件配置为与图像生成模型配合使用
<a name="guardrails-use-mmfilter-image-models"></a>

您还可以将 Amazon Bedrock 护栏图像筛选条件与图像生成模型（如 Titan 图像生成器以及 Stability Image 或 Diffusion 模型）一起使用。这些模型目前支持通过 `InvokeModel` API 使用，可通过护栏调用。您可以按照护栏支持的各种 Amazon Bedrock 基础模型的推理参数文档，在下方脚本中更新各种模型的请求有效载荷。

```
import base64
import boto3
import botocore
import json
import os
import random
import string


guardrail_id = 'guardrail-id'
guardrail_version = 'DRAFT'

model_id = 'stability.sd3-large-v1:0'
output_images_folder = '/path/to/folder/'

body = json.dumps(
    {
        "prompt": "Create an image of a beautiful flower", # Prompt for image generation ("A gun" should get blocked by violence)
        "output_format": "jpeg"
    }
)


def main():
    bedrock_runtime_client = boto3.client("bedrock-runtime", region_name="us-west-2")
    try:
        print("Making a call to InvokeModel API for model: {}".format(model_id))
        response = bedrock_runtime_client.invoke_model(
            body=body,
            modelId=model_id,
            trace='ENABLED',
            guardrailIdentifier=guardrail_id,
            guardrailVersion=guardrail_version
        )
        response_body = json.loads(response.get('body').read())
        print("Received response from InvokeModel API (Request Id: {})".format(response['ResponseMetadata']['RequestId']))
        if 'images' in response_body and len(response_body['images']) > 0:
            os.makedirs(output_images_folder, exist_ok=True)
            images = response_body["images"]
            for image in images:
                image_id = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
                image_file = os.path.join(output_images_folder, "generated-image-{}.jpg".format(image_id))
                print("Saving generated image {} at {}".format(image_id, image_file))
                with open(image_file, 'wb') as image_file_descriptor:
                    image_file_descriptor.write(base64.b64decode(image.encode('utf-8')))
        else:
            print("No images generated from model")
        guardrail_trace = response_body['amazon-bedrock-trace']['guardrail']
        guardrail_trace['modelOutput'] = ['<REDACTED>']
        print("Guardrail Trace: {}".format(json.dumps(guardrail_trace, indent=2)))
    except botocore.exceptions.ClientError as err:
        print("Failed while calling InvokeModel API with RequestId = {}".format(err.response['ResponseMetadata']['RequestId']))
        raise err


if __name__ == "__main__":
    main()
```