テンプレートの作成と管理

Model Armor テンプレートを使用して、AI アプリケーションのプロンプトとレスポンスのスクリーニングを構成します。テンプレートには、複数の安全性とセキュリティのカテゴリ用にカスタマイズされたフィルタと上限値が用意されています。このドキュメントでは、Model Armor テンプレートを作成して管理する方法について説明します。詳細については、Model Armor テンプレートをご覧ください。

リージョン エンドポイントまたはマルチリージョン エンドポイントを使用する

Model Armor テンプレートを使用する場合は、テンプレートのロケーションと一致するリージョンまたはマルチリージョン エンドポイントmodelarmor.LOCATION.rep.googleapis.com)を使用する必要があります。

グローバル エンドポイント(modelarmor.googleapis.com)は、Model Armor テンプレートの管理や、プロンプトとレスポンスのサニタイズをサポートしていません。

始める前に

始める前に、次のタスクを完了します。

必要な権限を取得する

Model Armor テンプレートの管理に必要な権限を取得するには、Model Armor テンプレートに対する Model Armor 管理者 roles/modelarmor.admin)IAM ロールを付与するよう管理者に依頼してください。ロールの付与については、プロジェクト、フォルダ、組織に対するアクセス権の管理をご覧ください。

必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

API を有効にする

Model Armor を使用するには、Model Armor API を有効にする必要があります。

コンソール

  1. Model Armor API を有効にします。

    API を有効にするために必要なロール

    API を有効にするには、serviceusage.services.enable 権限が必要です。プロジェクトを作成した場合は、オーナーロール(roles/owner)を介してこの権限がすでに付与されている可能性があります。それ以外の場合は、Service Usage 管理者ロール(roles/serviceusage.serviceUsageAdmin)を介してこの権限を取得できます。ロールを付与する方法をご覧ください。

    API の有効化

  2. Model Armor を有効にするプロジェクトを選択します。

gcloud

始める前に、Google Cloud CLI で Model Armor API を使用して、次の処理を行います。

  1. Google Cloud コンソールで Cloud Shell をアクティブにします。

    Cloud Shell をアクティブにする

    Google Cloud コンソールの下部にある Cloud Shell セッションが開始し、コマンドライン プロンプトが表示されます。Cloud Shell はシェル環境です。Google Cloud CLI がすでにインストールされており、現在のプロジェクトの値もすでに設定されています。セッションが初期化されるまで数秒かかることがあります。

  2. gcloud CLI を使用して API エンドポイントのオーバーライドを設定する

gcloud CLI を使用して API エンドポイントのオーバーライドを設定する

この手順は、Model Armor で gcloud CLI を使用し、デフォルトの us マルチリージョン以外のリージョンまたはマルチリージョンを使用する場合にのみ必要です。gcloud CLI がリクエストを Model Armor サービスに正しく転送するように、API エンドポイントのオーバーライドを手動で設定する必要があります。

次のコマンドを実行して、Model Armor サービスの API エンドポイントを設定します。

gcloud config set api_endpoint_overrides/modelarmor "https://modelarmor.LOCATION.rep.googleapis.com/"

LOCATION は、Model Armor を使用するリージョンまたはマルチリージョンに置き換えます。

Model Armor テンプレートを作成する

Model Armor テンプレートは、Model Armor がプロンプトとレスポンスをスクリーニングして安全性とセキュリティのリスクを検出するために使用する特定のフィルタとしきい値を定義します。Model Armor テンプレートを作成する手順は次のとおりです。

コンソール

  1. Google Cloud コンソールで、[Model Armor] ページに移動します。

    [Model Armor] に移動

  2. Model Armor を有効にしたプロジェクトが表示されていることを確認します。

  3. [Model Armor ] ページで、[テンプレートを作成] をクリックします。[テンプレートの作成] ページが表示されます。

  4. テンプレート ID を指定します。テンプレート ID には、英字、数字、アンダースコア、ハイフンを使用できます。63 文字以内で指定してください。スペースを含めることや、先頭をハイフンにすることはできません。

  5. [ロケーション タイプ] セクションで、Model Armor オペレーションを実行するリージョンまたはマルチリージョンを選択します。ロケーションは後で変更できません。

  6. 省略可: [データ所在地コンプライアンス] セクションで、データ所在地の適用を有効にするかどうかを選択します。デフォルトでは、選択したロケーションでローカルにホストされていない Model Armor 機能は、データが他の法域に移行しないように無効になっています。無効になった機能は、このセクションに記載されています。

    [データ所在地を適用する] オプションを無効にすると、データ所在地の適用によって制限されている機能を有効にできます。この操作により、データが複数の法域にまたがって転送されるようになります。

  7. 省略可: [ラベル] セクションで、関連するテンプレートをグループ化するために使用する Key-Value ペアを追加します。

  8. [フィルタ バージョン] セクションで、フィルタ バージョン番号またはフィルタ バージョン エイリアスを選択します

  9. Select modality: テキスト、画像、またはその両方を画面に表示するかどうかを指定します。

  10. [検出] セクションで、検出設定を構成します

  11. 省略可: Sensitive Data Protection の検出を選択する場合は、Sensitive Data Protection の設定を構成する必要があります。

  12. [責任ある AI] セクションで、コンテンツ フィルタごとに信頼度を設定します。

  13. 省略可: [追加構成(省略可)] セクションを開き、次のいずれかの設定を構成します。

    • [ロギングを構成する] セクションで、ロギングを構成するオペレーションを選択します。
    • [多言語サポート] セクションで、[多言語サポートを有効にする] を選択して、多言語検出を使用します。
    • [適用モード] セクションで、適用タイプを選択します。
  14. [作成] をクリックします。

gcloud

次のコマンドを実行します。

 gcloud model-armor templates create TEMPLATE_ID --project=PROJECT_ID --location=LOCATION \
     --rai-settings-filters='[{ "filterType": "HATE_SPEECH", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "HARASSMENT", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "SEXUALLY_EXPLICIT", "confidenceLevel": "MEDIUM_AND_ABOVE" }]' \
     --basic-config-filter-enforcement=enabled  \
     --pi-and-jailbreak-filter-settings-enforcement=enabled \
     --pi-and-jailbreak-filter-settings-confidence-level=HIGH \
     --malicious-uri-filter-settings-enforcement=enabled \
     --template-metadata-custom-llm-response-safety-error-code=798 \
     --template-metadata-custom-llm-response-safety-error-message="test template llm response evaluation failed" \
     --template-metadata-custom-prompt-safety-error-code=799 \
     --template-metadata-custom-prompt-safety-error-message="test template prompt evaluation failed" \
     --template-metadata-ignore-partial-invocation-failures \
     --template-metadata-log-operations \
     --template-metadata-log-sanitize-operations

次のように置き換えます。

  • LOCATION: テンプレートのロケーション
  • TEMPLATE_ID: テンプレートの ID。
  • PROJECT_ID: テンプレートが属するプロジェクトの ID。

REST

次のコマンドを使用して、新しい Model Armor テンプレートを作成します。

  curl -X POST \
    -d "FILTER_CONFIG" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates?template_id=TEMPLATE_ID"

次のように置き換えます。

  • FILTER_CONFIG: テンプレートのフィルタ構成(JSON 形式)。
  • PROJECT_ID: テンプレートが属するプロジェクトの ID。
  • TEMPLATE_ID: 作成するテンプレートの ID。
  • LOCATION: テンプレートのロケーション

次の例は、検出する内容を定義する Model Armor フィルタ構成(FilterConfig)を示しています。この例では、ヘイトスピーチ、ハラスメント、危険なコンテンツ、性的描写が露骨なコンテンツに対して、さまざまな信頼度レベル責任ある AI フィルタが構成されています。プロンプト インジェクションとジェイルブレイクの検出フィルタは HIGH の信頼レベルで有効になっています。これは、可能性が高いコンテンツのみがフラグ付けされることを意味します。悪意のある URI フィルタは有効になっています。

  export FILTER_CONFIG='{
   "filterConfig": {
    "raiSettings": {
     "raiFilters": [{
       "filterType": "HATE_SPEECH",
       "confidenceLevel": "MEDIUM_AND_ABOVE"
      }, {
      "filterType": "HARASSMENT",
      "confidenceLevel": "HIGH"
    }, {
      "filterType": "DANGEROUS",
      "confidenceLevel": "MEDIUM_AND_ABOVE"
    },{
      "filterType": "SEXUALLY_EXPLICIT",
      "confidenceLevel": "MEDIUM_AND_ABOVE"
    }]
  },

  "piAndJailbreakFilterSettings": {
    "filterEnforcement": "ENABLED",
    "confidenceLevel": "HIGH"
  },
  "maliciousUriFilterSettings": {
    "filterEnforcement": "ENABLED"
  }
 }
}'

curl -X POST \
 -d "$FILTER_CONFIG" \
 -H "Content-Type: application/json" \
 -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates?template_id=TEMPLATE_ID"

Model Armor がオペレーション、エラー、ログを処理する方法を定義するには、コマンドでテンプレート メタデータ(TemplateMetadata)を設定します。テンプレートのメタデータには、言語検出、モダリティ、データ所在地コンプライアンスの設定が含まれます。

次の例では、多言語検出とモダリティ(画像とテキスト)が有効になっている Model Armor テンプレート構成を作成します。

  export TEMPLATE_CONFIG='{
   "filterConfig": {
    "raiSettings": {
     "raiFilters": [{
       "filterType": "HATE_SPEECH",
       "confidenceLevel": "MEDIUM_AND_ABOVE"
      }, {
      "filterType": "HARASSMENT",
      "confidenceLevel": "HIGH"
    }, {
      "filterType": "DANGEROUS",
      "confidenceLevel": "MEDIUM_AND_ABOVE"
    },{
      "filterType": "SEXUALLY_EXPLICIT",
      "confidenceLevel": "MEDIUM_AND_ABOVE"
    }]
  },

  "piAndJailbreakFilterSettings": {
    "filterEnforcement": "ENABLED",
    "confidenceLevel": "HIGH"
  },
  "maliciousUriFilterSettings": {
    "filterEnforcement": "ENABLED"
  }
 },
 "templateMetadata": {
    "multiLanguageDetection": {
      "enableMultiLanguageDetection": true
    },
    "modalities": ["MODALITY_IMAGE", "MODALITY_TEXT"]
  }
}'

curl -X POST \
 -d "$TEMPLATE_CONFIG"  \
 -H "Content-Type: application/json" \
 -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates?template_id=TEMPLATE_ID"

C#

このコードを実行するには、まず C# 開発環境を設定し、Model Armor C# SDK をインストールします。

using Google.Api.Gax.ResourceNames;
using Google.Cloud.ModelArmor.V1;
using System.Collections.Generic;

public class CreateTemplateSample
{
    public Template CreateTemplate(
        string projectId = "my-project",
        string locationId = "us-central1",
        string templateId = "my-template"
    )
    {
        ModelArmorClient client = new ModelArmorClientBuilder
        {
            Endpoint = $"modelarmor.{locationId}.rep.googleapis.com",
        }.Build();

        // Build the Model Armor template with your preferred filters.
        // For more details on filters, please refer to the following doc:
        // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters

        // Configure Responsible AI filter with multiple categories and their confidence
        // levels.
        RaiFilterSettings raiFilterSettings = new RaiFilterSettings();
        List<RaiFilterSettings.Types.RaiFilter> filters =
            new List<RaiFilterSettings.Types.RaiFilter>
            {
                new RaiFilterSettings.Types.RaiFilter
                {
                    FilterType = RaiFilterType.Dangerous,
                    ConfidenceLevel = DetectionConfidenceLevel.High,
                },
                new RaiFilterSettings.Types.RaiFilter
                {
                    FilterType = RaiFilterType.HateSpeech,
                    ConfidenceLevel = DetectionConfidenceLevel.High,
                },
                new RaiFilterSettings.Types.RaiFilter
                {
                    FilterType = RaiFilterType.SexuallyExplicit,
                    ConfidenceLevel = DetectionConfidenceLevel.LowAndAbove,
                },
                new RaiFilterSettings.Types.RaiFilter
                {
                    FilterType = RaiFilterType.Harassment,
                    ConfidenceLevel = DetectionConfidenceLevel.MediumAndAbove,
                },
            };

        raiFilterSettings.RaiFilters.Add(filters);

        Template template = new Template
        {
            FilterConfig = new FilterConfig { RaiSettings = raiFilterSettings },
        };

        CreateTemplateRequest request = new CreateTemplateRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, locationId),
            TemplateId = templateId,
            Template = template,
        };

        Template createdTemplate = client.CreateTemplate(request);
        System.Console.WriteLine($"Created template: {createdTemplate.Name}");

        return createdTemplate;
    }
}

Go

このコードを実行するには、まず Go 開発環境を設定し、Model Armor Go SDK をインストールします。


import (
	"context"
	"fmt"
	"io"

	modelarmor "cloud.google.com/go/modelarmor/apiv1"
	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
	"google.golang.org/api/option"
)

// createModelArmorTemplate method creates a new
// Model Armor template with the provided settings.
//
// w io.Writer: The writer to use for logging.
// projectID string: The ID of the Google Cloud project.
// locationID string: The ID of the Google Cloud location.
// templateID string: The ID of the template to create.
func createModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error {
	ctx := context.Background()

	// Create the call options
	opts := option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID))
	// Create the Model Armor client.
	client, err := modelarmor.NewClient(ctx, opts)
	if err != nil {
		return fmt.Errorf("failed to create client for project %s, location %s: %w", projectID, locationID, err)
	}
	defer client.Close()

	// Build the Model Armor template with your preferred filters.
	// For more details on filters, please refer to the following doc:
	// [https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters)
	template := &modelarmorpb.Template{
		FilterConfig: &modelarmorpb.FilterConfig{
			PiAndJailbreakFilterSettings: &modelarmorpb.PiAndJailbreakFilterSettings{
				FilterEnforcement: modelarmorpb.PiAndJailbreakFilterSettings_ENABLED,
				ConfidenceLevel:   modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE,
			},
			MaliciousUriFilterSettings: &modelarmorpb.MaliciousUriFilterSettings{
				FilterEnforcement: modelarmorpb.MaliciousUriFilterSettings_ENABLED,
			},
		},
	}
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)

	// Prepare the request for creating the template.
	req := &modelarmorpb.CreateTemplateRequest{
		Parent:     parent,
		TemplateId: templateID,
		Template:   template,
	}

	// Create the template.
	response, err := client.CreateTemplate(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create template: %v", err)
	}

	// Print the new template name using fmt.Fprintf with the io.Writer.
	fmt.Fprintf(w, "Created template: %s\n", response.Name)

	return err
}

Java

このコードを実行するには、まず Java 開発環境を設定し、Model Armor Java SDK をインストールします。


import com.google.cloud.modelarmor.v1.CreateTemplateRequest;
import com.google.cloud.modelarmor.v1.DetectionConfidenceLevel;
import com.google.cloud.modelarmor.v1.FilterConfig;
import com.google.cloud.modelarmor.v1.LocationName;
import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.RaiFilterSettings;
import com.google.cloud.modelarmor.v1.RaiFilterSettings.RaiFilter;
import com.google.cloud.modelarmor.v1.RaiFilterType;
import com.google.cloud.modelarmor.v1.Template;
import java.io.IOException;
import java.util.List;

public class CreateTemplate {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Specify the Google Project ID.
    String projectId = "your-project-id";
    // Specify the location ID. For example, us-central1. 
    String locationId = "your-location-id";
    // Specify the template ID.
    String templateId = "your-template-id";

    createTemplate(projectId, locationId, templateId);
  }

  public static Template createTemplate(String projectId, String locationId, String templateId)
      throws IOException {
    // Construct the API endpoint URL.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);
    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder().setEndpoint(apiEndpoint)
        .build();

    // Initialize the client that will be used to send requests. This client
    // only needs to be created once, and can be reused for multiple requests.
    try (ModelArmorClient client = ModelArmorClient.create(modelArmorSettings)) {
      String parent = LocationName.of(projectId, locationId).toString();

      // Build the Model Armor template with your preferred filters.
      // For more details on filters, please refer to the following doc:
      // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters

      // Configure Responsible AI filter with multiple categories and their confidence
      // levels.
      RaiFilterSettings raiFilterSettings = RaiFilterSettings.newBuilder()
          .addAllRaiFilters(
              List.of(
                  RaiFilter.newBuilder()
                      .setFilterType(RaiFilterType.DANGEROUS)
                      .setConfidenceLevel(DetectionConfidenceLevel.HIGH)
                      .build(),
                  RaiFilter.newBuilder()
                      .setFilterType(RaiFilterType.HATE_SPEECH)
                      .setConfidenceLevel(DetectionConfidenceLevel.HIGH)
                      .build(),
                  RaiFilter.newBuilder()
                      .setFilterType(RaiFilterType.SEXUALLY_EXPLICIT)
                      .setConfidenceLevel(DetectionConfidenceLevel.LOW_AND_ABOVE)
                      .build(),
                  RaiFilter.newBuilder()
                      .setFilterType(RaiFilterType.HARASSMENT)
                      .setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
                      .build()))
          .build();

      FilterConfig modelArmorFilter = FilterConfig.newBuilder()
          .setRaiSettings(raiFilterSettings)
          .build();

      Template template = Template.newBuilder()
          .setFilterConfig(modelArmorFilter)
          .build();

      CreateTemplateRequest request = CreateTemplateRequest.newBuilder()
          .setParent(parent)
          .setTemplateId(templateId)
          .setTemplate(template)
          .build();

      Template createdTemplate = client.createTemplate(request);
      System.out.println("Created template: " + createdTemplate.getName());

      return createdTemplate;
    }
  }
}

Node.js

このコードを実行するには、まず Node.js 開発環境を設定し、Model Armor Node.js SDK をインストールします。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'your-project-id';
// const locationId = 'us-central1';
// const templateId = 'your-template-id';

const parent = `projects/${projectId}/locations/${locationId}`;

// Imports the Model Armor library
const modelarmor = require('@google-cloud/modelarmor');
const {ModelArmorClient} = modelarmor.v1;
const {protos} = modelarmor;

// Instantiates a client
const client = new ModelArmorClient({
  apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`,
});

/**  Build the Model Armor template with your preferred filters.
    For more details on filters, please refer to the following doc:
    https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
 */
const templateConfig = {
  filterConfig: {
    raiSettings: {
      raiFilters: [
        {
          filterType:
            protos.google.cloud.modelarmor.v1.RaiFilterType.HATE_SPEECH,
          confidenceLevel:
            protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel.HIGH,
        },
        {
          filterType:
            protos.google.cloud.modelarmor.v1.RaiFilterType.SEXUALLY_EXPLICIT,
          confidenceLevel:
            protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
              .MEDIUM_AND_ABOVE,
        },
      ],
    },
  },
};

// Construct request
const request = {
  parent,
  templateId,
  template: templateConfig,
};

// Create the template
const [response] = await client.createTemplate(request);
return response;

PHP

このコードを実行するには、まず PHP 開発環境を設定し、Model Armor PHP SDK をインストールします。

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\Template;
use Google\Cloud\ModelArmor\V1\CreateTemplateRequest;
use Google\Cloud\ModelArmor\V1\FilterConfig;
use Google\Cloud\ModelArmor\V1\RaiFilterType;
use Google\Cloud\ModelArmor\V1\RaiFilterSettings;
use Google\Cloud\ModelArmor\V1\RaiFilterSettings\RaiFilter;
use Google\Cloud\ModelArmor\V1\DetectionConfidenceLevel;

/**
 * Create a Model Armor template.
 *
 * @param string $projectId The ID of the project (e.g. 'my-project').
 * @param string $locationId The ID of the location (e.g. 'us-central1').
 * @param string $templateId The ID of the template (e.g. 'my-template').
 */
function create_template(string $projectId, string $locationId, string $templateId): void
{
    $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
    $client = new ModelArmorClient($options);
    $parent = $client->locationName($projectId, $locationId);

    /**
     * Build the Model Armor template with preferred filters.
     * For more details on filters, refer to:
     * https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
     */

    $raiFilters = [
        (new RaiFilter())
            ->setFilterType(RaiFilterType::DANGEROUS)
            ->setConfidenceLevel(DetectionConfidenceLevel::HIGH),
        (new RaiFilter())
            ->setFilterType(RaiFilterType::HATE_SPEECH)
            ->setConfidenceLevel(DetectionConfidenceLevel::HIGH),
        (new RaiFilter())
            ->setFilterType(RaiFilterType::SEXUALLY_EXPLICIT)
            ->setConfidenceLevel(DetectionConfidenceLevel::LOW_AND_ABOVE),
        (new RaiFilter())
            ->setFilterType(RaiFilterType::HARASSMENT)
            ->setConfidenceLevel(DetectionConfidenceLevel::MEDIUM_AND_ABOVE),
    ];

    $raiFilterSetting = (new RaiFilterSettings())->setRaiFilters($raiFilters);

    $templateFilterConfig = (new FilterConfig())->setRaiSettings($raiFilterSetting);

    $template = (new Template())->setFilterConfig($templateFilterConfig);

    $request = (new CreateTemplateRequest)
        ->setParent($parent)
        ->setTemplateId($templateId)
        ->setTemplate($template);

    $response = $client->createTemplate($request);

    printf('Template created: %s' . PHP_EOL, $response->getName());
}

Python

このコードを実行するには、まず Python 開発環境を設定し、Model Armor Python SDK をインストールします。


from google.api_core.client_options import ClientOptions
from google.cloud import modelarmor_v1

# TODO(Developer): Uncomment these variables.
# project_id = "your-google-cloud-project-id"
# location_id = "us-central1"
# template_id = "template_id"

# Create the Model Armor client.
client = modelarmor_v1.ModelArmorClient(
    transport="rest",
    client_options=ClientOptions(
        api_endpoint=f"modelarmor.{location_id}.rep.googleapis.com"
    ),
)

# Build the Model Armor template with your preferred filters.
# For more details on filters, please refer to the following doc:
# https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
template = modelarmor_v1.Template(
    filter_config=modelarmor_v1.FilterConfig(
        pi_and_jailbreak_filter_settings=modelarmor_v1.PiAndJailbreakFilterSettings(
            filter_enforcement=modelarmor_v1.PiAndJailbreakFilterSettings.PiAndJailbreakFilterEnforcement.ENABLED,
            confidence_level=modelarmor_v1.DetectionConfidenceLevel.MEDIUM_AND_ABOVE,
        ),
        malicious_uri_filter_settings=modelarmor_v1.MaliciousUriFilterSettings(
            filter_enforcement=modelarmor_v1.MaliciousUriFilterSettings.MaliciousUriFilterEnforcement.ENABLED,
        ),
    ),
)

# Prepare the request for creating the template.
request = modelarmor_v1.CreateTemplateRequest(
    parent=f"projects/{project_id}/locations/{location_id}",
    template_id=template_id,
    template=template,
)

# Create the template.
response = client.create_template(request=request)

# Print the new template name.
print(f"Created template: {response.name}")

データ所在地に関するコンプライアンスを設定する

デフォルトでは、作成したテンプレートはデータ所在地コンプライアンスを厳密に適用します。つまり、テンプレートのリージョンをカバーする管轄区域内でホストされていない Model Armor 機能は無効になります。データ所在地コンプライアンスの適用により、データが管轄区域外に移動することを防ぎます。

厳格なデータ所在地よりも包括的なセキュリティ フィルタリングを優先するテンプレートの場合は、使用中および転送中のデータのデータ所在地適用を無効にできます。これを行うには、Google Cloud コンソールで [データ所在地を適用する] オプションを無効にするか、Model Armor API で data_residency_compliantfalse に設定します。このオプションの状態に関係なく、保存データはデータ所在地に準拠したままです。

テンプレートでデータ所在地に関するコンプライアンスを無効にすると、データが管轄区域を越えてルーティングされるようになります。つまり、特定の機能がテンプレートの法域でローカルに利用できない場合、Model Armor はリクエストを他の法域に転送する可能性があります。

データ所在地のコンプライアンスを無効にすると、画像モダリティを除くすべての Model Armor 機能が有効になります。画像モダリティは、引き続き us マルチリージョンと eu マルチリージョンに制限されます。

フィルタのバージョンを選択する

Model Armor フィルタ バージョンは、本番環境ワークロードの安定性と、更新された脅威検出モデルへのアクセスのバランスを提供します。フィルタ バージョンはテンプレート レベルで構成します。フィルタ バージョンは、フィルタ バージョンを使用しないフィルタに記載されているものを除く、そのテンプレート内のすべてのフィルタに適用されます。詳細については、テンプレートのフィルタ バージョンを設定するをご覧ください。

モダリティを選択する

モダリティを使用して、次のものをスキャンするかどうかを指定します。

  • すべて: テキストと画像をスキャンします。
  • 特定のモダリティ:

詳細については、画像スクリーニング画像を含むプロンプトをサニタイズするをご覧ください。

検出を構成する

検出は、Model Armor がプロンプトとレスポンスに対して実行する特定のチェックです。Model Armor は、検出を構成するための柔軟なシステムを提供し、AI アプリケーションの保護レベルを調整できます。検出は、テンプレートの作成時に構成します。Model Armor は、プロンプトとレスポンスに対して次の検出チェックを実行します。

  • 悪意のある URL の検出: ユーザーやシステムに害を及ぼすように設計されたウェブアドレス(URL)を特定します。これらの URL は、フィッシング サイト、マルウェアのダウンロード、その他のサイバー攻撃につながる可能性があります。詳細については、悪意のある URL の検出をご覧ください。

  • プロンプト インジェクションとジェイルブレイクの検出: プロンプト内の悪意のあるコンテンツとジェイルブレイクの試行を検出します。誤検出を最小限に抑え、一貫した検出動作を確保するには、信頼度を [] に設定することをおすすめします。信頼度を [] に設定すると、偽陽性率が低下しますが、まれに偽陽性が検出されることがあります。詳細については、プロンプト インジェクションとジェイルブレイクの検出をご覧ください。

  • Sensitive Data Protection: センシティブ データを検出し、プロンプト インジェクションなどの攻撃で露出しないようにします。詳細については、Sensitive Data Protection をご覧ください。

Sensitive Data Protection の設定を行う

Model Armor は Sensitive Data Protection を活用して、LLM のインタラクションで機密情報が公開されるのを特定して防ぎます。詳細については、Sensitive Data Protection をご覧ください。

Model Armor には、Sensitive Data Protection の構成用に次の 2 つのモードがあります。

  • 基本: 事前定義された infoTypes を使用してセンシティブ データを検出する、よりシンプルなアプローチ。事前定義された infoType の詳細については、基本的な Sensitive Data Protection の構成をご覧ください。

  • 高度: 構成可能なオプション。Sensitive Data Protection サービスで定義された検査テンプレートをセンシティブ データの infoType の単一ソースとして使用します。

[高度] モードを選択する場合は、次のパラメータを指定する必要があります。

  • 検査テンプレート: 検査スキャンジョブの構成情報(使用する定義済み検出機能またはカスタム検出機能など)を保存するためのテンプレート。テンプレート名を projects/projectId/locations/locationId/inspectTemplates/templateName の形式で入力します。

  • 省略可: 匿名化テンプレート: 匿名化ジョブの構成情報(infoType の変換と構造化データセットの変換の両方を含む)を保存するためのテンプレート。匿名化テンプレートの ID を projects/projectId/locations/locationId/deidentifyTemplates/templateName の形式で入力します。

Sensitive Data Protection に検査テンプレート匿名化テンプレートが存在することを確認します。テンプレートが別のプロジェクトにある場合は、Model Armor サービス エージェントに、そのプロジェクトの DLP ユーザーロールroles/dlp.user)と DLP 読み取りロールroles/dlp.reader)を付与する必要があります。

信頼度を設定する

信頼度は、検出結果がコンテンツ フィルタ タイプと一致する可能性を表します。コンテンツ フィルタごとに信頼度を設定できます。値は次のいずれかになります。

  • なし: コンテンツは検出されません。
  • 低以上: 信頼度が低、中、高のコンテンツが検出されます。
  • 中以上: 信頼度が中または高のコンテンツが検出されます。
  • : 信頼度が高いコンテンツが検出されます。

より厳格な適用を行うには、信頼度を「低以上」に設定して、コンテンツ フィルタ タイプに該当するほとんどのコンテンツを検出できるようにします。

テンプレートで包括的なロギングを有効にするには、Model Armor の監査とプラットフォームのロギングをご覧ください。

テンプレートの適用タイプを定義する

Model Armor が検出を処理する方法を構成するには、適用タイプを設定します。

テンプレート構成の template_metadata フィールドで、enforcement_typeINSPECT_ONLY または INSPECT_AND_BLOCK に設定します。

export TEMPLATE_CONFIG='{
   "filter_config": {
    "rai_settings": {
     "rai_filters": [{
       "filter_type": "HATE_SPEECH",
       "confidence_level": "MEDIUM_AND_ABOVE"
      }, {
      "filter_type": "HARASSMENT",
      "confidence_level": "MEDIUM_AND_ABOVE"
    }, {
      "filter_type": "DANGEROUS",
      "confidence_level": "MEDIUM_AND_ABOVE"
    },{
      "filter_type": "SEXUALLY_EXPLICIT",
      "confidence_level": "MEDIUM_AND_ABOVE"
    }]
  },
  "pi_and_jailbreak_filter_settings": {
    "filter_enforcement": "ENABLED",
    "confidence_level": "HIGH"
  },
  "malicious_uri_filter_settings": {
    "filter_enforcement": "ENABLED"
  }
 },
 "template_metadata": {
    "enforcement_type": "INSPECT_ONLY",
    "multi_language_detection": {
      "enable_multi_language_detection": true
    }
  }
}'

curl -X POST \
    -d "$TEMPLATE_CONFIG"  \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates?template_id=TEMPLATE_ID"

次のように置き換えます。

  • PROJECT_ID: テンプレートが属するプロジェクトの ID。
  • TEMPLATE_ID: 作成するテンプレートの ID。
  • LOCATION: テンプレートのロケーション

Model Armor テンプレートを表示する

既存のテンプレートを表示して、使用可能な構成を確認し、プロンプトとレスポンスのスクリーニングに関する問題をトラブルシューティングして解決します。

コンソール

  1. Google Cloud コンソールで、[Model Armor] ページに移動します。

    [Model Armor] に移動

  2. Model Armor を有効にしたプロジェクトが表示されていることを確認します。[Model Armor] ページが表示され、プロジェクト用に作成されたテンプレートが一覧表示されます。

  3. リストからテンプレートをクリックすると、その詳細が表示されます。

gcloud

次のコマンドを実行します。

gcloud model-armor templates describe TEMPLATE_ID --project=PROJECT_ID --location=LOCATION

次のように置き換えます。

  • LOCATION: テンプレートのロケーション
  • TEMPLATE_ID: テンプレートの ID。
  • PROJECT_ID: テンプレートが属するプロジェクトの ID。

REST

次のコマンドを実行します。

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
  "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID"

次のように置き換えます。

  • PROJECT_ID: テンプレートが属するプロジェクトの ID。
  • TEMPLATE_ID: 表示するテンプレートの ID。
  • LOCATION: テンプレートのロケーション

C#

このコードを実行するには、まず C# 開発環境を設定し、Model Armor C# SDK をインストールします。

using Google.Cloud.ModelArmor.V1;
using System;

public class GetTemplateSample
{
    public Template GetTemplate(
        string projectId = "my-project",
        string locationId = "us-central1",
        string templateId = "my-template"
    )
    {
        ModelArmorClient client = new ModelArmorClientBuilder
        {
            Endpoint = $"modelarmor.{locationId}.rep.googleapis.com",
        }.Build();

        GetTemplateRequest request = new GetTemplateRequest
        {
            TemplateName = TemplateName.FromProjectLocationTemplate(projectId, locationId, templateId),
        };

        Template template = client.GetTemplate(request);
        Console.WriteLine($"Retrieved template: {template.Name}");

        return template;
    }
}

Go

このコードを実行するには、まず Go 開発環境を設定し、Model Armor Go SDK をインストールします。


import (
	"context"
	"fmt"
	"io"

	modelarmor "cloud.google.com/go/modelarmor/apiv1"
	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
	"google.golang.org/api/option"
)

// getModelArmorTemplate method retrieves a Model Armor template.
//
// w io.Writer: The writer to use for logging.
// projectID string: The ID of the project.
// locationID string: The location of the template.
// templateID string: The ID of the template.
func getModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error {
	ctx := context.Background()

	// Create options for the Model Armor client
	opts := option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID))
	// Create the Model Armor client.
	client, err := modelarmor.NewClient(ctx, opts)
	if err != nil {
		return fmt.Errorf("failed to create client for project %s, location %s: %w", projectID, locationID, err)
	}
	defer client.Close()

	// Initialize request arguments.
	req := &modelarmorpb.GetTemplateRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID),
	}

	// Get the template.
	response, err := client.GetTemplate(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get template: %w", err)
	}

	// Print the template name using fmt.Fprintf with the io.Writer.
	fmt.Fprintf(w, "Retrieved template: %s\n", response.Name)

	return nil
}

Java

このコードを実行するには、まず Java 開発環境を設定し、Model Armor Java SDK をインストールします。


import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.Template;
import com.google.cloud.modelarmor.v1.TemplateName;
import java.io.IOException;

public class GetTemplate {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "your-location-id";
    String templateId = "your-template-id";

    getTemplate(projectId, locationId, templateId);
  }

  public static Template getTemplate(String projectId, String locationId, String templateId)
      throws IOException {
    // Construct the API endpoint URL.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);

    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder().setEndpoint(apiEndpoint)
        .build();

    // Initialize the client that will be used to send requests. This client
    // only needs to be created once, and can be reused for multiple requests.
    try (ModelArmorClient client = ModelArmorClient.create(modelArmorSettings)) {
      // Build the template name.
      String name = TemplateName.of(projectId, locationId, templateId).toString();

      // Get the template.
      Template template = client.getTemplate(name);

      // Find more details about Template object here:
      // https://cloud.google.com/security-command-center/docs/reference/model-armor/rest/v1/projects.locations.templates#Template
      System.out.printf("Retrieved template: %s\n", template.getName());

      return template;
    }
  }
}

Node.js

このコードを実行するには、まず Node.js 開発環境を設定し、Model Armor Node.js SDK をインストールします。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const locationId = 'my-location';
// const templateId = 'my-template';

const name = `projects/${projectId}/locations/${locationId}/templates/${templateId}`;

// Imports the Model Armor library
const {ModelArmorClient} = require('@google-cloud/modelarmor').v1;

// Instantiates a client
const client = new ModelArmorClient({
  apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`,
});

const request = {
  name: name,
};

// Run request
const [response] = await client.getTemplate(request);
return response;

PHP

このコードを実行するには、まず PHP 開発環境を設定し、Model Armor PHP SDK をインストールします。

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\GetTemplateRequest;

/**
 * Gets a Model Armor template.
 *
 * @param string $projectId The ID of your Google Cloud Platform project (e.g. 'my-project').
 * @param string $locationId The ID of the location where the template is stored (e.g. 'us-central1').
 * @param string $templateId The ID of the template (e.g. 'my-template').
 */
function get_template(string $projectId, string $locationId, string $templateId): void
{
    $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
    $client = new ModelArmorClient($options);
    $name = sprintf('projects/%s/locations/%s/templates/%s', $projectId, $locationId, $templateId);

    $getTemplateRequest = (new GetTemplateRequest())->setName($name);

    $response = $client->getTemplate($getTemplateRequest);

    printf('Template retrieved: %s' . PHP_EOL, $response->getName());
}

Python

このコードを実行するには、まず Python 開発環境を設定し、Model Armor Python SDK をインストールします。


from google.api_core.client_options import ClientOptions
from google.cloud import modelarmor_v1

# TODO(Developer): Uncomment these variables.
# project_id = "YOUR_PROJECT_ID"
# location_id = "us-central1"
# template_id = "template_id"

# Create the Model Armor client.
client = modelarmor_v1.ModelArmorClient(
    transport="rest",
    client_options=ClientOptions(
        api_endpoint=f"modelarmor.{location_id}.rep.googleapis.com"
    ),
)

# Initialize request arguments.
request = modelarmor_v1.GetTemplateRequest(
    name=f"projects/{project_id}/locations/{location_id}/templates/{template_id}",
)

# Get the template.
response = client.get_template(request=request)
print(response.name)

Model Armor テンプレートを更新する

AI アプリケーションの堅牢で効果的なセキュリティ ポスチャーを維持するために、テンプレートを定期的に更新します。

コンソール

  1. Google Cloud コンソールで、[Model Armor] ページに移動します。

    [Model Armor] に移動

  2. Model Armor を有効にしたプロジェクトが表示されていることを確認します。[Model Armor] ページが開き、組織用に作成されたテンプレートが一覧表示されます。

  3. リストから、更新するテンプレートをクリックします。[テンプレートの詳細] ページが表示されます。

  4. [編集] をクリックします。

  5. 必要なパラメータを入力し、[保存] をクリックします。

gcloud

テンプレートを更新するには、gcloud model-armor templates update コマンドを実行し、変更する設定のフラグを含めます。

たとえば、次のコマンドは、テンプレートのフィルタ設定とメタデータを更新します。

gcloud model-armor templates update TEMPLATE_ID \
    --project=PROJECT_ID \
    --location=LOCATION \
    --rai-settings-filters='[{ "filterType": "HATE_SPEECH", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "HARASSMENT", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "DANGEROUS", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "SEXUALLY_EXPLICIT", "confidenceLevel": "MEDIUM_AND_ABOVE" }]' \
    --basic-config-filter-enforcement=enabled \
    --pi-and-jailbreak-filter-settings-enforcement=enabled \
    --pi-and-jailbreak-filter-settings-confidence-level=HIGH \
    --malicious-uri-filter-settings-enforcement=enabled \
    --template-metadata-custom-llm-response-safety-error-code=798 \
    --template-metadata-custom-llm-response-safety-error-message="test template llm response evaluation failed" \
    --template-metadata-custom-prompt-safety-error-code=799 \
    --template-metadata-custom-prompt-safety-error-message="test template prompt evaluation failed" \
    --template-metadata-ignore-partial-invocation-failures \
    --template-metadata-log-operations \
    --template-metadata-log-sanitize-operations

次のように置き換えます。

  • TEMPLATE_ID: テンプレートの ID。
  • PROJECT_ID: テンプレートが属するプロジェクトの ID。
  • LOCATION: テンプレートのロケーション

REST

次のコマンドを実行します。

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d "$FILTER_CONFIG" \
  "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID?updateMask=UPDATE_MASK"

次のように置き換えます。

  • PROJECT_ID: テンプレートが属するプロジェクトの ID。
  • LOCATION: テンプレートのロケーション
  • TEMPLATE_ID: テンプレートの ID。
  • UPDATE_MASK: 更新されるフィールド(filterConfigfilterConfig.piAndJailbreakFilterSettings など)。このフィールドを空欄のままにすると、フィルタ構成全体が更新されます。

他のフィールドはすべて変更できません。他のフィールドを更新しようとすると(テンプレート名を更新しようとするなど)、エラーが発生します。

C#

このコードを実行するには、まず C# 開発環境を設定し、Model Armor C# SDK をインストールします。

using Google.Cloud.ModelArmor.V1;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;

namespace ModelArmor.Samples
{
    public class UpdateTemplateSample
    {
        public Template UpdateTemplate(
            string projectId = "my-project",
            string locationId = "us-central1",
            string templateId = "my-template"
        )
        {
            // Construct the API endpoint URL.
            ModelArmorClientBuilder clientBuilder = new ModelArmorClientBuilder
            {
                Endpoint = $"modelarmor.{locationId}.rep.googleapis.com",
            };

            // Create the client.
            ModelArmorClient client = clientBuilder.Build();

            // Get the template name.
            TemplateName name = TemplateName.FromProjectLocationTemplate(projectId, locationId, templateId);

            // Build the updated Model Armor template with modified filters.
            // For more details on filters, please refer to the following doc:
            // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
            RaiFilterSettings raiFilterSettings = new RaiFilterSettings();
            List<RaiFilterSettings.Types.RaiFilter> filters =
                new List<RaiFilterSettings.Types.RaiFilter>
                {
                    new RaiFilterSettings.Types.RaiFilter
                    {
                        FilterType = RaiFilterType.Dangerous,
                        ConfidenceLevel = DetectionConfidenceLevel.High,
                    },
                    new RaiFilterSettings.Types.RaiFilter
                    {
                        FilterType = RaiFilterType.HateSpeech,
                        ConfidenceLevel = DetectionConfidenceLevel.MediumAndAbove,
                    },
                    new RaiFilterSettings.Types.RaiFilter
                    {
                        FilterType = RaiFilterType.SexuallyExplicit,
                        ConfidenceLevel = DetectionConfidenceLevel.MediumAndAbove,
                    },
                    new RaiFilterSettings.Types.RaiFilter
                    {
                        FilterType = RaiFilterType.Harassment,
                        ConfidenceLevel = DetectionConfidenceLevel.MediumAndAbove,
                    },
                };

            raiFilterSettings.RaiFilters.Add(filters);

            Template template = new Template
            {
                TemplateName = name,
                FilterConfig = new FilterConfig { RaiSettings = raiFilterSettings },
            };

            // Create a field mask to specify which fields to update.
            // Ref: https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask
            FieldMask updateMask = new FieldMask { Paths = { "filter_config.rai_settings" } };

            // Prepare the request.
            UpdateTemplateRequest request = new UpdateTemplateRequest
            {
                Template = template,
                UpdateMask = updateMask,
            };

            // Send the request.
            Template updatedTemplate = client.UpdateTemplate(request);
            Console.WriteLine($"Updated template: {updatedTemplate.Name}");

            return updatedTemplate;
        }
    }
}

Go

このコードを実行するには、まず Go 開発環境を設定し、Model Armor Go SDK をインストールします。


import (
	"context"
	"fmt"
	"io"

	modelarmor "cloud.google.com/go/modelarmor/apiv1"
	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
	"google.golang.org/api/option"
)

// updateModelArmorTemplate updates a Model Armor template.
//
// updateModelArmorTemplate method updates a Model Armor template.
//
// w io.Writer: The writer to use for logging.
// projectID string: The ID of the project.
// locationID string: The ID of the location.
// templateID string: The ID of the template.
func updateModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error {
	ctx := context.Background()

	// Create options for Model Armor client.
	opts := option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID))
	// Create the Model Armor client.
	client, err := modelarmor.NewClient(ctx, opts)
	if err != nil {
		return fmt.Errorf("failed to create client for project %s, location %s: %w", projectID, locationID, err)
	}
	defer client.Close()

	// Build the Model Armor template with your preferred filters.
	// For more details on filters, please refer to the following doc:
	// [https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters)
	updatedTemplate := &modelarmorpb.Template{
		Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID),
		FilterConfig: &modelarmorpb.FilterConfig{
			PiAndJailbreakFilterSettings: &modelarmorpb.PiAndJailbreakFilterSettings{
				FilterEnforcement: modelarmorpb.PiAndJailbreakFilterSettings_ENABLED,
				ConfidenceLevel:   modelarmorpb.DetectionConfidenceLevel_LOW_AND_ABOVE,
			},
			MaliciousUriFilterSettings: &modelarmorpb.MaliciousUriFilterSettings{
				FilterEnforcement: modelarmorpb.MaliciousUriFilterSettings_ENABLED,
			},
		},
	}

	// Initialize request argument(s).
	req := &modelarmorpb.UpdateTemplateRequest{
		Template: updatedTemplate,
	}

	// Update the template.
	response, err := client.UpdateTemplate(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update template: %w", err)
	}

	// Print the updated filters in the template.
	fmt.Fprintf(w, "Updated Filter Config: %+v\n", response.FilterConfig)

	return nil
}

Java

このコードを実行するには、まず Java 開発環境を設定し、Model Armor Java SDK をインストールします。


import com.google.cloud.modelarmor.v1.DetectionConfidenceLevel;
import com.google.cloud.modelarmor.v1.FilterConfig;
import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.RaiFilterSettings;
import com.google.cloud.modelarmor.v1.RaiFilterSettings.RaiFilter;
import com.google.cloud.modelarmor.v1.RaiFilterType;
import com.google.cloud.modelarmor.v1.Template;
import com.google.cloud.modelarmor.v1.TemplateName;
import com.google.cloud.modelarmor.v1.UpdateTemplateRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.List;

public class UpdateTemplate {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Specify the Google Project ID.
    String projectId = "your-project-id";
    // Specify the location ID. For example, us-central1. 
    String locationId = "your-location-id";
    // Specify the template ID.
    String templateId = "your-template-id";

    updateTemplate(projectId, locationId, templateId);
  }

  public static Template updateTemplate(String projectId, String locationId, String templateId)
      throws IOException {
    // Construct the API endpoint URL.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);
    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder().setEndpoint(apiEndpoint)
        .build();

    // Initialize the client that will be used to send requests. This client
    // only needs to be created once, and can be reused for multiple requests.
    try (ModelArmorClient client = ModelArmorClient.create(modelArmorSettings)) {
      // Get the template name.
      String name = TemplateName.of(projectId, locationId, templateId).toString();

      // Build the updated Model Armor template with modified filters.
      // For more details on filters, please refer to the following doc:
      // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
      RaiFilterSettings raiFilterSettings =
          RaiFilterSettings.newBuilder()
              .addAllRaiFilters(
                  List.of(
                      RaiFilter.newBuilder()
                          .setFilterType(RaiFilterType.DANGEROUS)
                          .setConfidenceLevel(DetectionConfidenceLevel.HIGH)
                          .build(),
                      RaiFilter.newBuilder()
                          .setFilterType(RaiFilterType.HATE_SPEECH)
                          .setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
                          .build(),
                      RaiFilter.newBuilder()
                          .setFilterType(RaiFilterType.HARASSMENT)
                          .setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
                          .build(),
                      RaiFilter.newBuilder()
                          .setFilterType(RaiFilterType.SEXUALLY_EXPLICIT)
                          .setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
                          .build()))
              .build();

      FilterConfig modelArmorFilter = FilterConfig.newBuilder()
          .setRaiSettings(raiFilterSettings)
          .build();

      Template template = Template.newBuilder()
          .setName(name)
          .setFilterConfig(modelArmorFilter)
          .build();

      // Create a field mask to specify which fields to update.
      // Ref: https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask
      FieldMask updateMask = FieldMask.newBuilder()
          .addPaths("filter_config.rai_settings")
          .build();

      UpdateTemplateRequest request = UpdateTemplateRequest.newBuilder()
          .setTemplate(template)
          .setUpdateMask(updateMask)
          .build();

      Template updatedTemplate = client.updateTemplate(request);
      System.out.println("Updated template: " + updatedTemplate.getName());

      return updatedTemplate;
    }
  }
}

Node.js

このコードを実行するには、まず Node.js 開発環境を設定し、Model Armor Node.js SDK をインストールします。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'your-project-id';
// const locationId = 'us-central1';
// const templateId = 'template-id';

const modelarmor = require('@google-cloud/modelarmor');
const {ModelArmorClient} = modelarmor.v1;
const {protos} = modelarmor;

const DetectionConfidenceLevel =
  protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel;
const PiAndJailbreakFilterEnforcement =
  protos.google.cloud.modelarmor.v1.PiAndJailbreakFilterSettings
    .PiAndJailbreakFilterEnforcement;
const MaliciousUriFilterEnforcement =
  protos.google.cloud.modelarmor.v1.MaliciousUriFilterSettings
    .MaliciousUriFilterEnforcement;

// Instantiates a client
const client = new ModelArmorClient({
  apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`,
});

// Build the updated template configuration
const updatedTemplate = {
  name: `projects/${projectId}/locations/${locationId}/templates/${templateId}`,
  filterConfig: {
    piAndJailbreakFilterSettings: {
      filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED,
      confidenceLevel: DetectionConfidenceLevel.LOW_AND_ABOVE,
    },
    maliciousUriFilterSettings: {
      filterEnforcement: MaliciousUriFilterEnforcement.ENABLED,
    },
  },
};

const request = {
  template: updatedTemplate,
};

const [response] = await client.updateTemplate(request);
return response;

PHP

このコードを実行するには、まず PHP 開発環境を設定し、Model Armor PHP SDK をインストールします。

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\DetectionConfidenceLevel;
use Google\Cloud\ModelArmor\V1\PiAndJailbreakFilterSettings\PiAndJailbreakFilterEnforcement;
use Google\Cloud\ModelArmor\V1\PiAndJailbreakFilterSettings;
use Google\Cloud\ModelArmor\V1\MaliciousUriFilterSettings;
use Google\Cloud\ModelArmor\V1\UpdateTemplateRequest;
use Google\Cloud\ModelArmor\V1\FilterConfig;
use Google\Cloud\ModelArmor\V1\Template;

/**
 * Updates a Model Armor template with the specified configuration.
 *
 * @param string $projectId The ID of the project (e.g. 'my-project').
 * @param string $locationId The ID of the location (e.g. 'us-central1').
 * @param string $templateId The ID of the template (e.g. 'my-template').
 */
function update_template(string $projectId, string $locationId, string $templateId): void
{
    $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
    $client = new ModelArmorClient($options);

    $templateFilterConfig = (new FilterConfig())
        ->setPiAndJailbreakFilterSettings(
            (new PiAndJailbreakFilterSettings())
                ->setFilterEnforcement(PiAndJailbreakFilterEnforcement::ENABLED)
                ->setConfidenceLevel(DetectionConfidenceLevel::LOW_AND_ABOVE)
        )
        ->setMaliciousUriFilterSettings(
            (new MaliciousUriFilterSettings())
                ->setFilterEnforcement(PiAndJailbreakFilterEnforcement::ENABLED)
        );

    $template = (new Template())
        ->setFilterConfig($templateFilterConfig)
        ->setName("projects/$projectId/locations/$locationId/templates/$templateId");

    $updateTemplateRequest = (new UpdateTemplateRequest())->setTemplate($template);

    $response = $client->updateTemplate($updateTemplateRequest);

    printf('Template updated: %s' . PHP_EOL, $response->getName());
}

Python

このコードを実行するには、まず Python 開発環境を設定し、Model Armor Python SDK をインストールします。


from google.api_core.client_options import ClientOptions
from google.cloud import modelarmor_v1

# TODO(Developer): Uncomment these variables.
# project_id = "YOUR_PROJECT_ID"
# location_id = "us-central1"
# template_id = "template_id"

# Create the Model Armor client.
client = modelarmor_v1.ModelArmorClient(
    transport="rest",
    client_options=ClientOptions(
        api_endpoint=f"modelarmor.{location_id}.rep.googleapis.com"
    ),
)

# Build the Model Armor template with your preferred filters.
# For more details on filters, please refer to the following doc:
# https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
updated_template = modelarmor_v1.Template(
    name=f"projects/{project_id}/locations/{location_id}/templates/{template_id}",
    filter_config=modelarmor_v1.FilterConfig(
        pi_and_jailbreak_filter_settings=modelarmor_v1.PiAndJailbreakFilterSettings(
            filter_enforcement=modelarmor_v1.PiAndJailbreakFilterSettings.PiAndJailbreakFilterEnforcement.ENABLED,
            confidence_level=modelarmor_v1.DetectionConfidenceLevel.LOW_AND_ABOVE,
        ),
        malicious_uri_filter_settings=modelarmor_v1.MaliciousUriFilterSettings(
            filter_enforcement=modelarmor_v1.MaliciousUriFilterSettings.MaliciousUriFilterEnforcement.ENABLED,
        ),
    ),
)

# Initialize request argument(s).
request = modelarmor_v1.UpdateTemplateRequest(template=updated_template)

# Update the template.
response = client.update_template(request=request)

# Print the updated filters in the template.
print(response.filter_config)

Model Armor テンプレートを削除する

テンプレートが使用されなくなった場合、新しいテンプレートに置き換えられた場合、またはセキュリティ ポリシーが変更された場合は、テンプレートを削除します。

コンソール

  1. Google Cloud コンソールで、[Model Armor] ページに移動します。

    [Model Armor] に移動

  2. Model Armor を有効にしたプロジェクトが表示されていることを確認します。[Model Armor] ページが開き、組織用に作成されたテンプレートが一覧表示されます。

  3. リストから、削除するテンプレートをクリックします。[テンプレートの詳細] ページが表示されます。

  4. [削除] をクリックします。確認ダイアログが表示されます。

  5. 削除を確定するには、テンプレート名を入力して [削除] をクリックします。

gcloud

次のコマンドを実行します。

gcloud model-armor templates delete TEMPLATE_ID --project=PROJECT_ID --location=LOCATION

次のように置き換えます。

  • LOCATION: テンプレートのロケーション
  • TEMPLATE_ID: テンプレートの ID。
  • PROJECT_ID: テンプレートが属するプロジェクトの ID。

REST

次のコマンドを実行します。

curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)"  \
  "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID"

次のように置き換えます。

  • PROJECT_ID: テンプレートが属するプロジェクトの ID。
  • LOCATION: テンプレートのロケーション
  • TEMPLATE_ID: テンプレートの ID。

C#

このコードを実行するには、まず C# 開発環境を設定し、Model Armor C# SDK をインストールします。

using Google.Cloud.ModelArmor.V1;
using System;

public class DeleteTemplateSample
{
    public void DeleteTemplate(
        string projectId = "my-project",
        string locationId = "us-central1",
        string templateId = "my-template"
    )
    {
        ModelArmorClient client = new ModelArmorClientBuilder
        {
            Endpoint = $"modelarmor.{locationId}.rep.googleapis.com",
        }.Build();

        DeleteTemplateRequest request = new DeleteTemplateRequest
        {
            TemplateName = TemplateName.FromProjectLocationTemplate(projectId, locationId, templateId),
        };

        client.DeleteTemplate(request);
        Console.WriteLine($"Deleted template: {templateId}");
    }
}

Go

このコードを実行するには、まず Go 開発環境を設定し、Model Armor Go SDK をインストールします。


import (
	"context"
	"fmt"
	"io"

	modelarmor "cloud.google.com/go/modelarmor/apiv1"
	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
	"google.golang.org/api/option"
)

// deleteModelArmorTemplate method deletes a Model Armor template with the provided ID.
//
// w io.Writer: The writer to use for logging.
// projectID string: The ID of the Google Cloud project.
// locationID string: The ID of the Google Cloud location.
// templateID string: The ID of the template to delete.
func deleteModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error {
	ctx := context.Background()

	// Create option for Model Armor client.
	opts := option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID))
	// Create the Model Armor client.
	client, err := modelarmor.NewClient(ctx, opts)
	if err != nil {
		return fmt.Errorf("failed to create client for project %s, location %s: %w", projectID, locationID, err)
	}
	defer client.Close()

	// Build the request for deleting the template.
	req := &modelarmorpb.DeleteTemplateRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID),
	}

	// Delete the template.
	if err := client.DeleteTemplate(ctx, req); err != nil {
		return fmt.Errorf("failed to delete template: %w", err)
	}

	// Print the success message using fmt.Fprintf with the io.Writer.
	fmt.Fprintf(w, "Successfully deleted Model Armor template: %s\n", req.Name)

	return err
}

Java

このコードを実行するには、まず Java 開発環境を設定し、Model Armor Java SDK をインストールします。


import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.TemplateName;
import java.io.IOException;

public class DeleteTemplate {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Specify the Google Project ID.
    String projectId = "your-project-id";
    // Specify the location ID. For example, us-central1.
    String locationId = "your-location-id";
    // Specify the template ID.
    String templateId = "your-template-id";

    deleteTemplate(projectId, locationId, templateId);
  }

  public static void deleteTemplate(String projectId, String locationId, String templateId)
      throws IOException {

    // Construct the API endpoint URL.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);
    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder().setEndpoint(apiEndpoint)
        .build();

    // Initialize the client that will be used to send requests. This client
    // only needs to be created once, and can be reused for multiple requests.
    try (ModelArmorClient client = ModelArmorClient.create(modelArmorSettings)) {
      String name = TemplateName.of(projectId, locationId, templateId).toString();

      // Note: Ensure that the template you are deleting isn't used by any models.
      client.deleteTemplate(name);
      System.out.println("Deleted template: " + name);
    }
  }
}

Node.js

このコードを実行するには、まず Node.js 開発環境を設定し、Model Armor Node.js SDK をインストールします。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const locationId = 'us-central1';
// const templateId = 'my-template';

const name = `projects/${projectId}/locations/${locationId}/templates/${templateId}`;

// Imports the Model Armor library
const {ModelArmorClient} = require('@google-cloud/modelarmor');

// Instantiates a client
const client = new ModelArmorClient({
  apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`,
});

const response = await client.deleteTemplate({
  name: name,
});
return response;

PHP

このコードを実行するには、まず PHP 開発環境を設定し、Model Armor PHP SDK をインストールします。

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\DeleteTemplateRequest;

/**
 * Deletes a Model Armor template.
 *
 * @param string $projectId The ID of the project (e.g. 'my-project').
 * @param string $locationId The ID of the location (e.g. 'us-central1').
 * @param string $templateId The ID of the template (e.g. 'my-template').
 */
function delete_template(string $projectId, string $locationId, string $templateId): void
{
    $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
    $client = new ModelArmorClient($options);
    $templateName = sprintf('projects/%s/locations/%s/templates/%s', $projectId, $locationId, $templateId);

    $dltTemplateRequest = (new DeleteTemplateRequest())->setName($templateName);

    $client->deleteTemplate($dltTemplateRequest);

    printf('Deleted template: %s' . PHP_EOL, $templateName);
}

Python

このコードを実行するには、まず Python 開発環境を設定し、Model Armor Python SDK をインストールします。


from google.api_core.client_options import ClientOptions
from google.cloud import modelarmor_v1

# TODO(Developer): Uncomment these variables.
# project_id = "YOUR_PROJECT_ID"
# location_id = "us-central1"
# template_id = "template_id"

# Create the Model Armor client.
client = modelarmor_v1.ModelArmorClient(
    transport="rest",
    client_options=ClientOptions(
        api_endpoint=f"modelarmor.{location_id}.rep.googleapis.com"
    ),
)

# Build the request for deleting the template.
request = modelarmor_v1.DeleteTemplateRequest(
    name=f"projects/{project_id}/locations/{location_id}/templates/{template_id}",
)

# Delete the template.
client.delete_template(request=request)

テンプレート メタデータ

Model Armor テンプレートのメタデータは、安全性とセキュリティのチェック処理、エラー処理、ロギング動作など、Model Armor の動作を構成する際に役立ちます。

Model Armor のテンプレート メタデータには次のフィールドが含まれます。

メタデータ タイプ デフォルト値 説明
enforcement_type 列挙型 INSPECT_AND_BLOCK

適用タイプを定義します。次の値のいずれかを使用できます。

  • INSPECT_ONLY: Model Armor は、構成された設定に違反するリクエストを検査しますが、ブロックはしません。
  • INSPECT_AND_BLOCK: Model Armor は、構成された設定に違反するリクエストをブロックします。
log_template_operations ブール値 False テンプレート オペレーションのロギングを有効にします。
log_sanitize_operations ブール値 False サニタイズ オペレーションのロギングを有効にします。
multiLanguageDetection ブール値 False 多言語検出を有効にします。
モダリティプレビュー 列挙型 空白 テキスト、画像、またはその両方をスキャンするかどうかを決定します。このフィールドを空欄のままにすると、テキストのみがスキャンされます。

次の値のいずれかを使用できます。

data_residency_compliant ブール値 正しい

テンプレートが厳格なデータ所在地コンプライアンス(管轄区域内の処理)の対象となるかどうかを示します。

  • True: テンプレートのリージョンの地域の適用法令内でローカルにサポートされていない機能を無効にして、データがローカルの地域の適用法令外に移動しないようにします。
  • False: データ所在地に関するコンプライアンス チェックを無効にし、地域の適用法令で機能がローカルに利用できない場合に、データが地域の適用法令を越えてルーティングされることを許可します。

このフィールドの詳細については、このドキュメントのデータ所在地コンプライアンスを設定するをご覧ください。

テンプレートのデータ所在地について詳しくは、テンプレートのデータ所在地の適用をご覧ください。

次のステップ