Model Armor-Vorlagen erstellen und verwalten

Sie verwenden Model Armor-Vorlagen, um die Überprüfung von Prompts und Antworten für Ihre KI-Anwendungen zu konfigurieren. Die Vorlagen enthalten benutzerdefinierte Filter und Grenzwerte für mehrere Sicherheitskategorien. In diesem Dokument wird beschrieben, wie Sie Model Armor-Vorlagen erstellen und verwalten. Weitere Informationen finden Sie unter Model Armor-Vorlagen.

Hinweise

Führen Sie zuerst die folgenden Schritte aus.

Erforderliche Berechtigungen erhalten

Bitten Sie Ihren Administrator, Ihnen die IAM-Rolle Model Armor Admin (roles/modelarmor.admin) für Model Armor-Vorlagen zuzuweisen, um die Berechtigungen zu erhalten, die Sie zum Verwalten von Model Armor-Vorlagen benötigen. Weitere Informationen zum Zuweisen von Rollen finden Sie unter Zugriff auf Projekte, Ordner und Organisationen verwalten.

Sie können die erforderlichen Berechtigungen auch über benutzerdefinierte Rollen oder andere vordefinierte Rollen erhalten.

APIs aktivieren

Sie müssen die Model Armor APIs aktivieren, bevor Sie Model Armor verwenden können.

Console

  1. Enable the Model Armor API.

    Enable the API

  2. Wählen Sie das Projekt aus, für das Sie Model Armor aktivieren möchten.

gcloud

Führen Sie die folgenden Schritte mit der Google Cloud CLI und der Model Armor API aus, bevor Sie beginnen:

  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. Führen Sie den folgenden Befehl aus, um den API-Endpunkt für den Model Armor-Dienst festzulegen.

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

    Ersetzen Sie LOCATION durch die Region, in der Sie Model Armor verwenden möchten.

  3. Führen Sie den folgenden Befehl aus, um Model Armor zu aktivieren.

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

    Ersetzen Sie PROJECT_ID durch die ID des Projekts.

    Model Armor-Vorlage erstellen

    In Model Armor-Vorlagen werden die spezifischen Filter und Grenzwerte definiert, die Model Armor verwendet, um Prompts und Antworten auf Sicherheitsrisiken zu prüfen. So erstellen Sie eine Model Armor-Vorlage:

    Console

    1. Rufen Sie in der Google Cloud Console die Seite Model Armor auf.

      Zu Model Armor

    2. Prüfen Sie, ob Sie das Projekt aufrufen, für das Sie Model Armor aktiviert haben.

    3. Klicken Sie auf der Seite Model Armor auf Vorlage erstellen. Die Seite Vorlage erstellen wird angezeigt.

    4. Geben Sie die Template ID (Vorlagen-ID) an. Die Vorlagen-ID kann Buchstaben, Ziffern oder Bindestriche enthalten. Sie darf nicht länger als 63 Zeichen sein, keine Leerzeichen enthalten und nicht mit einem Bindestrich beginnen.

    5. Wählen Sie eine Region aus, in der die Model Armor-Vorlagen ausgeführt werden sollen. Sie können die Region später nicht mehr ändern.

    6. Optional: Fügen Sie Labels hinzu. Labels sind Schlüssel/Wert-Paare, mit denen Sie verwandte Vorlagen gruppieren können.

    7. Konfigurieren Sie im Abschnitt Erkennungen die Erkennungseinstellungen.

    8. Optional: Wenn Sie die Sensitive Data Protection-Erkennung auswählen, müssen Sie die Sensitive Data Protection-Einstellungen konfigurieren.

    9. Legen Sie im Bereich Verantwortungsbewusste Anwendung von KI das Konfidenzniveau für jeden Inhaltsfilter fest.

    10. Optional: Wählen Sie im Bereich Logging konfigurieren die Vorgänge aus, für die Sie das Logging konfigurieren möchten.

    11. Optional: Wählen Sie Unterstützung mehrerer Sprachen aktivieren aus, um die Einstellungen für die Erkennung mehrerer Sprachen zu verwenden.

    12. Klicken Sie auf Erstellen.

    gcloud

    Führen Sie dazu diesen Befehl aus:

     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
    

    Ersetzen Sie Folgendes:

    • LOCATION: der Speicherort der Vorlage.
    • TEMPLATE_ID: die ID der Vorlage.
    • PROJECT_ID: die ID des Projekts, zu dem die Vorlage gehört.

    REST

    Verwenden Sie den folgenden Befehl, um eine neue Model Armor-Vorlage zu erstellen.

      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"
    

    Ersetzen Sie Folgendes:

    • FILTER_CONFIG: die Filterkonfiguration für die Vorlage.
    • PROJECT_ID: die ID des Projekts, zu dem die Vorlage gehört.
    • TEMPLATE_ID: Die ID der zu erstellenden Vorlage.
    • LOCATION: der Speicherort der Vorlage.

    Das folgende Beispiel zeigt die Konfiguration der Model Armor-Vorlage. In diesem Beispiel sind die Responsible AI-Filter für Hassreden, Belästigungen, gefährliche und sexuell explizite Inhalte mit unterschiedlichen Konfidenzniveaus konfiguriert. Der Filter Erkennung von Prompt Injection und Jailbreaking ist mit einem LOW_AND_ABOVE-Konfidenzniveau aktiviert. Das bedeutet, dass alle Inhalte mit einer niedrigen, mittleren oder hohen Wahrscheinlichkeit gekennzeichnet werden. Der Filter für schädliche URIs ist aktiviert.

      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"
    

    Wenn Sie eine Model Armor-Vorlage mit aktivierter mehrsprachiger Erkennung erstellen möchten, müssen Sie den Parameter TEMPLATE_CONFIG in Ihrem Befehl übergeben. Mit diesem Parameter wird die Konfiguration für die Einstellungen zur Spracherkennung definiert.

    Verwenden Sie den folgenden Befehl, um eine neue Model Armor-Vorlage mit aktivierter mehrsprachiger Erkennung zu erstellen.

    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"
    

    Das folgende Beispiel zeigt die Konfiguration der Model Armor-Vorlage mit aktivierter mehrsprachiger Erkennung.

      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

    Um diesen Code auszuführen, müssen Sie zuerst eine Python-Entwicklungsumgebung einrichten und das Model Armor Python SDK installieren.

    
    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}")
    

    Erkennungen konfigurieren

    Erkennungen sind die spezifischen Prüfungen, die Model Armor für Prompts und Antworten durchführt. Model Armor bietet ein flexibles System zum Konfigurieren von Erkennungen, mit dem Sie den Schutz Ihrer KI-Anwendungen anpassen können. Sie konfigurieren die Erkennungen beim Erstellen von Vorlagen. Model Armor führt die folgenden Erkennungsprüfungen für Prompts und Antworten durch:

    • Erkennung schädlicher URLs: Identifiziert Webadressen (URLs), die Nutzern oder Systemen schaden sollen. Diese URLs können zu Phishing-Websites, Malware-Downloads oder anderen Cyberangriffen führen. Weitere Informationen finden Sie unter Erkennung schädlicher URLs.

    • Erkennung von Prompt Injection und Jailbreaking: Erkennt schädliche Inhalte und Jailbreak-Versuche in einem Prompt. Wenn Sie eine strengere Erzwingung wünschen, legen Sie das Konfidenzniveau auf Niedrig und höher fest. Damit werden die meisten Inhalte erkannt, bei denen es sich wahrscheinlich um eine Prompt Injection und einen Jailbreak-Versuch handelt. Weitere Informationen finden Sie unter Erkennung von Prompt Injection und Jailbreaking.

    • Schutz sensibler Daten: Erkennt sensible Daten und hilft, deren versehentliche Offenlegung durch Angriffe wie Prompt Injection zu verhindern. Weitere Informationen finden Sie unter Schutz sensibler Daten.

    Einstellungen für Sensitive Data Protection festlegen

    Model Armor nutzt den Schutz sensibler Daten, um die Offenlegung sensibler Informationen in Ihren LLM-Interaktionen zu erkennen und zu verhindern. Weitere Informationen finden Sie unter Schutz sensibler Daten.

    Model Armor bietet zwei Modi zum Konfigurieren von Sensitive Data Protection:

    • Einfach: Ein einfacherer Ansatz, bei dem vordefinierte infoTypes zum Erkennen sensibler Daten verwendet werden. Weitere Informationen zum vordefinierten infoType finden Sie unter Grundlegende Konfiguration des Schutzes sensibler Daten.

    • Erweitert: Eine besser konfigurierbare Option, bei der eine im Sensitive Data Protection-Dienst definierte Inspektionsvorlage als einzige Quelle für infoTypes von sensiblen Daten verwendet wird.

    Wenn Sie den Modus Erweitert auswählen, müssen Sie die folgenden Parameter angeben:

    • Prüfvorlage: Vorlagen zum Speichern von Konfigurationsinformationen für Prüfscanjobs, einschließlich der zu verwendenden vordefinierten oder benutzerdefinierten Detektoren. Geben Sie den Vorlagennamen im folgenden Format ein: projects/projectName/locations/locationID/inspectTemplates/templateName

    • Optional: De-Identifikationsvorlage: Vorlagen zum Speichern von Konfigurationsinformationen für De-Identifikationsjobs, einschließlich Transformationen von infoTypes und strukturierten Datasets. Geben Sie eine Kennzeichnung für die De-Identifikationsvorlage im folgenden Format ein: projects/projectName/locations/locationID/deidentifyTemplates/templateName

    Prüfen Sie, ob die Inspektionsvorlage und die De-Identifikationsvorlage im Schutz sensibler Daten vorhanden sind. Wenn sich die Vorlage in einem anderen Projekt befindet, muss dem Model Armor-Dienst-Agent für dieses Projekt die Rolle „DLP-Nutzer“ (roles/dlp.user) und die Rolle „DLP-Leser“ (roles/dlp.reader) zugewiesen werden.

    Konfidenzniveau festlegen

    Das Konfidenzniveau gibt an, wie wahrscheinlich es ist, dass die Ergebnisse einem Inhaltsfiltertyp entsprechen. Sie können das Konfidenzniveau für jeden Inhaltsfilter festlegen. Folgende Werte sind möglich:

    • Keine: Es wird kein Inhaltstyp erkannt.
    • Niedrig und höher: Inhalte werden mit einem niedrigen, mittleren oder hohen Konfidenzniveau erkannt.
    • Mittel und höher: Inhalte werden mit einem mittleren oder hohen Konfidenzniveau erkannt.
    • Hoch: Inhalte werden mit einem hohen Konfidenzniveau erkannt.

    Wenn Sie eine strengere Erzwingung wünschen, legen Sie das Konfidenzniveau auf Niedrig und höher fest. Damit werden die meisten Inhalte erkannt, die in einen bestimmten Inhaltsfiltertyp fallen. Sie können auch das Konfidenzniveau auswählen.

    Informationen zum Aktivieren des umfassenden Loggings für eine Vorlage finden Sie unter Model Armor-Audit- und Plattform-Logging.

    Model Armor-Vorlage ansehen

    Sie können sich vorhandene Vorlagen ansehen, um zu verstehen, welche Konfigurationen verfügbar sind, und um Probleme mit Screening-Prompts und ‑Antworten zu beheben.

    Console

    1. Rufen Sie in der Google Cloud Console die Seite Model Armor auf.

      Zu Model Armor

    2. Prüfen Sie, ob Sie das Projekt aufrufen, für das Sie Model Armor aktiviert haben. Die Seite Model Armor wird angezeigt und enthält die für Ihr Projekt erstellten Vorlagen.

    3. Klicken Sie auf eine beliebige Vorlage in der Liste, um die zugehörigen Details aufzurufen.

    gcloud

    Führen Sie dazu diesen Befehl aus:

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

    Ersetzen Sie Folgendes:

    • LOCATION: der Speicherort der Vorlage.
    • TEMPLATE_ID: die ID der Vorlage.
    • PROJECT_ID: die ID des Projekts, zu dem die Vorlage gehört.

    REST

    Führen Sie dazu diesen Befehl aus:

    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"

    Ersetzen Sie Folgendes:

    • PROJECT_ID: die ID des Projekts, zu dem die Vorlage gehört.
    • TEMPLATE_ID: Die ID der Vorlage, die angezeigt werden soll.
    • LOCATION: der Speicherort der Vorlage.

    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

    Um diesen Code auszuführen, müssen Sie zuerst eine Python-Entwicklungsumgebung einrichten und das Model Armor Python SDK installieren.

    
    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-Vorlage aktualisieren

    Aktualisieren Sie Ihre Vorlagen regelmäßig, um eine robuste und effektive Sicherheitslage für Ihre KI-Anwendungen aufrechtzuerhalten.

    Console

    1. Rufen Sie in der Google Cloud Console die Seite Model Armor auf.

      Zu Model Armor

    2. Prüfen Sie, ob Sie das Projekt aufrufen, für das Sie Model Armor aktiviert haben. Die Seite Model Armor wird angezeigt und enthält eine Liste der für Ihre Organisation erstellten Vorlagen.

    3. Klicken Sie in der Liste auf die Vorlage, die Sie aktualisieren möchten. Die Seite Vorlagendetails wird angezeigt.

    4. Klicken Sie auf Bearbeiten.

    5. Aktualisieren Sie die erforderlichen Parameter und klicken Sie auf Speichern.

    gcloud

    Führen Sie dazu diesen Befehl aus:

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

    Ersetzen Sie Folgendes:

    • LOCATION: der Speicherort der Vorlage.
    • TEMPLATE_ID: die ID der Vorlage.
    • PROJECT_ID: die ID des Projekts, zu dem die Vorlage gehört.

    REST

    Führen Sie dazu diesen Befehl aus:

    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"

    Ersetzen Sie Folgendes:

    • PROJECT_ID: die ID des Projekts, zu dem die Vorlage gehört.
    • LOCATION: der Speicherort der Vorlage.
    • TEMPLATE_ID: die ID der Vorlage.
    • FILTER_CONFIG: die JSON-Darstellung der Filterkonfiguration.

    Alle anderen Felder sind unveränderlich. Versuche, andere Felder zu aktualisieren (z. B. den Vorlagennamen), führen zu einem Fehler.

    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

    Um diesen Code auszuführen, müssen Sie zuerst eine Python-Entwicklungsumgebung einrichten und das Model Armor Python SDK installieren.

    
    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-Vorlage löschen

    Löschen Sie eine Vorlage, wenn sie nicht mehr verwendet wird, durch eine neue Vorlage ersetzt wird oder sich die Sicherheitsrichtlinien ändern.

    Console

    1. Rufen Sie in der Google Cloud Console die Seite Model Armor auf.

      Zu Model Armor

    2. Prüfen Sie, ob Sie das Projekt aufrufen, für das Sie Model Armor aktiviert haben. Die Seite Model Armor wird angezeigt und enthält eine Liste der für Ihre Organisation erstellten Vorlagen.

    3. Klicken Sie in der Liste auf die Vorlage, die Sie löschen möchten. Die Seite Vorlagendetails wird angezeigt.

    4. Klicken Sie auf Löschen. Es wird ein Bestätigungsdialogfeld angezeigt.

    5. Geben Sie den Namen der Vorlage ein, um das Löschen zu bestätigen, und klicken Sie auf Löschen.

    gcloud

    Führen Sie dazu diesen Befehl aus:

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

    Ersetzen Sie Folgendes:

    • LOCATION: der Speicherort der Vorlage.
    • TEMPLATE_ID: die ID der Vorlage.
    • PROJECT_ID: die ID des Projekts, zu dem die Vorlage gehört.

    REST

    Führen Sie dazu diesen Befehl aus:

    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"

    Ersetzen Sie Folgendes:

    • PROJECT_ID: die ID des Projekts, zu dem die Vorlage gehört.
    • LOCATION: der Speicherort der Vorlage.
    • TEMPLATE_ID: die ID der Vorlage.

    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

    Um diesen Code auszuführen, müssen Sie zuerst eine Python-Entwicklungsumgebung einrichten und das Model Armor Python SDK installieren.

    
    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)
    

    Vorlagenmetadaten

    Mit den Metadaten der Model Armor-Vorlage können Sie das Verhalten von Model Armor konfigurieren, einschließlich der Verarbeitung von Sicherheits- und Schutzprüfungen, der Fehlerbehandlung und des Logging-Verhaltens.

    Die Vorlagenmetadaten für Model Armor enthalten die folgenden Felder:

    Metadaten Typ Beschreibung
    multiLanguageDetection Boolesch Ermöglicht die Erkennung mehrerer Sprachen.
    enforcement_type Enum

    Definiert den Erzwingungstyp. Verwenden Sie einen der folgenden Werte:

    • INSPECT_ONLY: Anfragen, die gegen die konfigurierten Einstellungen verstoßen, werden geprüft, aber nicht blockiert.
    • INSPECT_AND_BLOCK: Anfragen, die gegen die konfigurierten Einstellungen verstoßen, werden blockiert.
    log_template_operations Boolesch Aktiviert das Logging von Vorlagenvorgängen.
    log_sanitize_operations Boolesch Ermöglicht das Logging von Bereinigungsvorgängen.

    Nächste Schritte