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

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

始める前に

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

必要な権限を取得する

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

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

API を有効にする

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

コンソール

  1. Enable the Model Armor API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

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

gcloud

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

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

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

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

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

  3. 次のコマンドを実行して、Model Armor を有効にします。

      gcloud services enable modelarmor.googleapis.com --project=PROJECT_ID
       

    PROJECT_ID は、プロジェクトの ID に置き換えます。

    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. 省略可: ラベルを追加します。ラベルは、関連するテンプレートをグループ化するために使用できる Key-Value ペアです。

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

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

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

    10. 省略可: [ロギングを構成する] セクションで、ロギングを構成するオペレーションを選択します。

    11. 省略可: 多言語検出の設定を使用するには、[多言語サポートを有効にする] を選択します。

    12. [作成] をクリックします。

    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=LOW_AND_ABOVE \
         --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: テンプレートのフィルタ構成。
    • PROJECT_ID: テンプレートが属するプロジェクトの ID。
    • TEMPLATE_ID: 作成するテンプレートの ID。
    • LOCATION: テンプレートのロケーション。

    次の例は、Model Armor テンプレートの構成を示しています。この例では、ヘイトスピーチ、ハラスメント、危険なコンテンツ、性的描写が露骨なコンテンツに対して、さまざまな信頼度レベル責任ある AI フィルタが構成されています。プロンプト インジェクションとジェイルブレイクの検出フィルタは LOW_AND_ABOVE の信頼レベルで有効になっています。これは、低、中、高のいずれかの可能性を持つコンテンツがフラグ付けされることを意味します。悪意のある 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": "LOW_AND_ABOVE"
      },
      "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_ID/templates?template_id=TEMPLATE_ID"
    

    多言語検出が有効になっている Model Armor テンプレートを作成するには、コマンドで TEMPLATE_CONFIG パラメータを渡す必要があります。このパラメータは、言語検出設定の構成を定義します。

    次のコマンドを使用して、多言語検出が有効になっている新しい Model Armor テンプレートを作成します。

    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"
    

    次の例は、多言語検出が有効になっている 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": "LOW_AND_ABOVE"
      },
      "maliciousUriFilterSettings": {
        "filterEnforcement": "ENABLED"
      }
     },
     "templateMetadata": {
        "multiLanguageDetection": {
          "enableMultiLanguageDetection": 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_ID/templates?template_id=TEMPLATE_ID"
    

    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 がプロンプトとレスポンスに対して実行する特定のチェックです。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/projectName/locations/locationID/inspectTemplates/templateName の形式で入力します。

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

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

    信頼度を設定する

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

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

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

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

    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_ID.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID"

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

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

    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 TEMPLATE_ID --project=PROJECT_ID --location=LOCATION

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

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

    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 など)。このフィールドを空欄のままにすると、フィルタ構成全体が更新されます。

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

    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_ID.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID"

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

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

    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 のテンプレート メタデータには次のフィールドが含まれます。

    メタデータ タイプ 説明
    multiLanguageDetection ブール値 多言語検出を有効にします。
    enforcement_type 列挙型

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

    • INSPECT_ONLY: 構成された設定に違反するリクエストを検査しますが、ブロックはしません。
    • INSPECT_AND_BLOCK: 構成された設定に違反するリクエストをブロックします。
    log_template_operations ブール値 テンプレート オペレーションのロギングを有効にします。
    log_sanitize_operations ブール値 サニタイズ オペレーションのロギングを有効にします。

    次のステップ