Membuat dan mengelola template Model Armor

Anda menggunakan template Model Armor untuk mengonfigurasi penyaringan perintah dan respons untuk aplikasi AI Anda. Template ini menyediakan filter dan nilai minimum yang disesuaikan untuk beberapa kategori keselamatan dan keamanan. Dokumen ini menjelaskan cara membuat dan mengelola template Model Armor. Untuk mengetahui informasi selengkapnya, lihat Template Model Armor.

Sebelum memulai

Sebelum memulai, selesaikan tugas berikut.

Mendapatkan izin yang diperlukan

Untuk mendapatkan izin yang diperlukan untuk mengelola template Model Armor, minta administrator Anda untuk memberi Anda peran IAM Admin Model Armor (roles/modelarmor.admin) pada template Model Armor. Untuk mengetahui informasi selengkapnya tentang cara memberikan peran, lihat Mengelola akses ke project, folder, dan organisasi.

Anda mungkin juga bisa mendapatkan izin yang diperlukan melalui peran khusus atau peran bawaan lainnya.

Mengaktifkan API

Anda harus mengaktifkan Model Armor API sebelum dapat menggunakan Model Armor.

Konsol

  1. Enable the Model Armor API.

    Enable the API

  2. Pilih project tempat Anda ingin mengaktifkan Model Armor.

gcloud

Sebelum memulai, ikuti langkah-langkah berikut menggunakan Google Cloud CLI dengan 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. Jalankan perintah berikut untuk menetapkan endpoint API untuk layanan Model Armor.

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

    Ganti LOCATION dengan region tempat Anda ingin menggunakan Model Armor.

  3. Jalankan perintah berikut untuk mengaktifkan Model Armor.

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

    Ganti PROJECT_ID dengan ID project.

    Membuat template Model Armor

    Template Model Armor menentukan filter dan batas tertentu yang digunakan Model Armor untuk menyaring perintah dan respons terkait risiko keamanan dan keselamatan. Untuk membuat template Model Armor, ikuti langkah-langkah berikut:

    Konsol

    1. Di konsol Google Cloud , buka halaman Model Armor.

      Buka Model Armor

    2. Pastikan Anda melihat project tempat Anda mengaktifkan Model Armor.

    3. Di halaman Model Armor, klik Create Template. Halaman Create Template akan ditampilkan.

    4. Tentukan Template ID. ID template dapat berisi huruf, angka, atau tanda hubung. Nama ini tidak boleh melebihi 63 karakter, berisi spasi, atau diawali dengan tanda hubung.

    5. Pilih Region tempat template Model Armor akan dijalankan. Anda tidak dapat mengubah region nanti.

    6. Opsional: Tambahkan Label. Label adalah key-value pair yang dapat Anda gunakan untuk mengelompokkan template terkait.

    7. Di bagian Deteksi, konfigurasi setelan deteksi.

    8. Opsional: Jika Anda memilih deteksi Sensitive Data Protection, Anda perlu mengonfigurasi setelan Sensitive Data Protection.

    9. Di bagian AI yang Bertanggung Jawab, tetapkan tingkat keyakinan untuk setiap filter konten

    10. Opsional: Di bagian Konfigurasi logging, pilih operasi yang logging-nya ingin Anda konfigurasi.

    11. Opsional: Pilih Aktifkan dukungan multi-bahasa untuk menggunakan setelan deteksi multi-bahasa.

    12. Klik Buat.

    gcloud

    Jalankan perintah berikut:

     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
    

    Ganti kode berikut:

    • LOCATION: lokasi template.
    • TEMPLATE_ID: ID template.
    • PROJECT_ID: ID project tempat template berada.

    REST

    Gunakan perintah berikut untuk membuat template Model Armor baru.

      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"
    

    Ganti kode berikut:

    • FILTER_CONFIG: konfigurasi filter untuk template.
    • PROJECT_ID: ID project tempat template berada.
    • TEMPLATE_ID: ID template yang akan dibuat.
    • LOCATION: lokasi template.

    Contoh berikut menunjukkan konfigurasi template Model Armor. Dalam contoh ini, filter AI Bertanggung Jawab dikonfigurasi untuk ujaran kebencian, pelecehan, konten berbahaya, dan konten seksual vulgar dengan tingkat keyakinan yang bervariasi. Filter deteksi injeksi perintah dan pelarian dari batasan model diaktifkan dengan tingkat keyakinan LOW_AND_ABOVE, yang berarti semua konten dengan kemungkinan rendah, sedang, atau tinggi akan ditandai. Filter URI berbahaya diaktifkan.

      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"
    

    Untuk membuat template Model Armor dengan deteksi multi-bahasa yang diaktifkan, Anda harus meneruskan parameter TEMPLATE_CONFIG dalam perintah. Parameter ini menentukan konfigurasi untuk setelan deteksi bahasa.

    Gunakan perintah berikut untuk membuat template Model Armor baru dengan deteksi multi-bahasa diaktifkan.

    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"
    

    Contoh berikut menunjukkan konfigurasi template Model Armor dengan deteksi multi-bahasa diaktifkan.

      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": {
        "multiLanguageDetectionMetadata": {
          "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

    
    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

    
    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

    /**
     * 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

    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

    Untuk menjalankan kode ini, siapkan terlebih dahulu lingkungan pengembangan Python dan instal 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}")
    

    Mengonfigurasi deteksi

    Deteksi adalah pemeriksaan spesifik yang dilakukan Model Armor pada perintah dan respons. Model Armor menawarkan sistem yang fleksibel untuk mengonfigurasi deteksi, sehingga Anda dapat menyesuaikan tingkat perlindungan untuk aplikasi AI Anda. Anda mengonfigurasi deteksi saat membuat template. Model Armor melakukan pemeriksaan deteksi berikut pada perintah dan respons:

    • Deteksi URL berbahaya: Mengidentifikasi alamat web (URL) yang dirancang untuk membahayakan pengguna atau sistem. URL ini dapat mengarahkan ke situs phishing, download malware, atau serangan cyber lainnya. Untuk mengetahui informasi selengkapnya, lihat Deteksi URL berbahaya.

    • Deteksi injeksi perintah dan jailbreak: Mendeteksi konten berbahaya dan upaya jailbreak dalam perintah. Untuk penegakan yang lebih ketat, tetapkan tingkat keyakinan ke Rendah ke atas untuk mendeteksi sebagian besar konten yang kemungkinan merupakan upaya injeksi perintah dan pelarian dari batasan. Untuk informasi selengkapnya, lihat Deteksi injeksi perintah dan pelarian dari batasan.

    • Perlindungan Data Sensitif: Mendeteksi data sensitif dan membantu mencegah eksposurnya secara tidak sengaja dari serangan seperti injeksi perintah. Untuk mengetahui informasi selengkapnya, lihat Sensitive Data Protection.

    Menetapkan setelan Perlindungan Data Sensitif

    Model Armor memanfaatkan Perlindungan Data Sensitif untuk mengidentifikasi dan mencegah eksposur informasi sensitif dalam interaksi LLM Anda. Untuk mengetahui informasi selengkapnya, lihat Perlindungan Data Sensitif.

    Model Armor menawarkan dua mode untuk mengonfigurasi Perlindungan Data Sensitif:

    • Dasar: Pendekatan yang lebih sederhana yang menggunakan infoType yang telah ditentukan sebelumnya untuk mendeteksi data sensitif. Untuk mengetahui informasi selengkapnya tentang infoType yang telah ditentukan, lihat Konfigurasi dasar Perlindungan Data Sensitif.

    • Lanjutan: Opsi yang lebih dapat dikonfigurasi yang menggunakan template pemeriksaan yang ditentukan dalam layanan Perlindungan Data Sensitif sebagai satu sumber untuk infoType data sensitif.

    Jika memilih mode Lanjutan, Anda harus menentukan parameter berikut:

    • Template inspeksi: Template untuk menyimpan informasi konfigurasi untuk tugas pemindaian inspeksi, termasuk detektor bawaan atau kustom yang akan digunakan. Masukkan nama template dalam format berikut: projects/projectName/locations/locationID/inspectTemplates/templateName

    • Opsional: Template de-identifikasi: Template untuk menyimpan informasi konfigurasi untuk tugas de-identifikasi, termasuk transformasi infoType dan set data terstruktur. Masukkan ID untuk template anonim/beridentitas lain dalam format berikut: projects/projectName/locations/locationID/deidentifyTemplates/templateName

    Pastikan Template pemeriksaan dan Template de-identifikasi ada di Sensitive Data Protection. Jika template berada di project lain, agen layanan Model Armor harus diberi peran Pengguna DLP (roles/dlp.user) dan peran Pembaca DLP (roles/dlp.reader) untuk project tersebut.

    Menetapkan tingkat keyakinan

    Tingkat keyakinan menunjukkan seberapa besar kemungkinan temuan cocok dengan jenis filter konten. Anda dapat menyetel tingkat keyakinan untuk setiap filter konten. Kemungkinan nilainya adalah sebagai berikut:

    • Tidak ada: Tidak ada jenis konten yang terdeteksi.
    • Rendah ke atas: Konten terdeteksi dengan tingkat keyakinan rendah, sedang, atau tinggi.
    • Sedang dan lebih tinggi: Konten terdeteksi dengan tingkat keyakinan sedang atau tinggi.
    • Tinggi: Konten terdeteksi dengan tingkat keyakinan tinggi.

    Untuk penegakan yang lebih ketat, tetapkan tingkat keyakinan ke Rendah ke atas untuk mendeteksi sebagian besar konten yang termasuk dalam jenis filter konten. Anda juga dapat memilih tingkat keyakinan

    Untuk mengaktifkan logging komprehensif pada template, lihat Logging platform dan audit Model Armor.

    Melihat template Model Armor

    Lihat template yang ada untuk memahami konfigurasi yang tersedia serta untuk memecahkan masalah dan menyelesaikan masalah terkait perintah dan respons penyaringan.

    Konsol

    1. Di konsol Google Cloud , buka halaman Model Armor.

      Buka Model Armor

    2. Pastikan Anda melihat project tempat Anda mengaktifkan Model Armor. Halaman Model Armor ditampilkan yang mencantumkan template yang dibuat untuk project Anda.

    3. Klik template apa pun dari daftar untuk melihat detailnya.

    gcloud

    Jalankan perintah berikut:

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

    Ganti kode berikut:

    • LOCATION: lokasi template.
    • TEMPLATE_ID: ID template.
    • PROJECT_ID: ID project tempat template berada.

    REST

    Jalankan perintah berikut:

    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"

    Ganti kode berikut:

    • PROJECT_ID: ID project tempat template berada.
    • TEMPLATE_ID: ID template yang akan dilihat.
    • LOCATION: lokasi template.

    Go

    
    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

    
    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

    /**
     * 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

    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

    Untuk menjalankan kode ini, siapkan terlebih dahulu lingkungan pengembangan Python dan instal 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)
    

    Memperbarui template Model Armor

    Perbarui template Anda secara rutin untuk mempertahankan kondisi keamanan yang kuat dan efektif untuk aplikasi AI Anda.

    Konsol

    1. Di konsol Google Cloud , buka halaman Model Armor.

      Buka Model Armor

    2. Pastikan Anda melihat project tempat Anda mengaktifkan Model Armor. Halaman Model Armor ditampilkan yang mencantumkan template yang dibuat untuk organisasi Anda.

    3. Klik template yang ingin Anda perbarui dari daftar. Halaman Template details akan ditampilkan.

    4. Klik Edit.

    5. Perbarui parameter yang diperlukan, lalu klik Simpan.

    gcloud

    Jalankan perintah berikut:

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

    Ganti kode berikut:

    • LOCATION: lokasi template.
    • TEMPLATE_ID: ID template.
    • PROJECT_ID: ID project tempat template berada.

    REST

    Jalankan perintah berikut:

    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=FILTER_CONFIG"

    Ganti kode berikut:

    • PROJECT_ID: ID project tempat template berada.
    • LOCATION: lokasi template.
    • TEMPLATE_ID: ID template.
    • FILTER_CONFIG: representasi JSON dari konfigurasi filter.

    Semua kolom lainnya tidak dapat diubah. Upaya yang dilakukan untuk memperbarui kolom lain (misalnya, upaya untuk memperbarui nama template) akan menghasilkan error.

    Go

    
    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

    
    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

    /**
     * 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

    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

    Untuk menjalankan kode ini, siapkan terlebih dahulu lingkungan pengembangan Python dan instal 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)
    

    Menghapus template Model Armor

    Hapus template jika tidak lagi digunakan, digantikan oleh template baru, atau saat kebijakan keamanan berubah.

    Konsol

    1. Di konsol Google Cloud , buka halaman Model Armor.

      Buka Model Armor

    2. Pastikan Anda melihat project tempat Anda mengaktifkan Model Armor. Halaman Model Armor ditampilkan yang mencantumkan template yang dibuat untuk organisasi Anda.

    3. Klik template yang ingin Anda hapus dari daftar. Halaman Template details akan ditampilkan.

    4. Klik Hapus. Dialog konfirmasi akan ditampilkan.

    5. Masukkan nama template untuk mengonfirmasi penghapusan, lalu klik Hapus.

    gcloud

    Jalankan perintah berikut:

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

    Ganti kode berikut:

    • LOCATION: lokasi template.
    • TEMPLATE_ID: ID template.
    • PROJECT_ID: ID project tempat template berada.

    REST

    Jalankan perintah berikut:

    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"

    Ganti kode berikut:

    • PROJECT_ID: ID project tempat template berada.
    • LOCATION: lokasi template.
    • TEMPLATE_ID: ID template.

    Go

    
    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

    
    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

    /**
     * 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

    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

    Untuk menjalankan kode ini, siapkan terlebih dahulu lingkungan pengembangan Python dan instal 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)
    

    Metadata template

    Metadata template Model Armor membantu Anda mengonfigurasi perilaku Model Armor, termasuk penanganan pemeriksaan keamanan dan keselamatan, penanganan error, dan perilaku logging.

    Metadata template untuk Model Armor mencakup kolom berikut:

    Metadata Jenis Deskripsi
    multiLanguageDetection Boolean Mengaktifkan deteksi multi-bahasa.
    enforcement_type Enum

    Menentukan jenis penegakan. Gunakan salah satu nilai berikut:

    • INSPECT_ONLY: Memeriksa permintaan yang melanggar setelan yang dikonfigurasi, tetapi tidak memblokirnya.
    • INSPECT_AND_BLOCK: API ini memblokir permintaan yang melanggar setelan yang dikonfigurasi.
    log_template_operations Boolean Mengaktifkan logging operasi template.
    log_sanitize_operations Boolean Mengaktifkan logging operasi pembersihan.

    Langkah berikutnya