יצירה וניהול של תבניות

אתם משתמשים בתבניות של Model Armor כדי להגדיר את הסינון של הנחיות ותשובות באפליקציות ה-AI שלכם. התבניות מספקות מסננים וערכי סף מותאמים אישית למספר קטגוריות של בטיחות ואבטחה. במאמר הזה נסביר איך ליצור ולנהל תבניות של Model Armor. מידע נוסף זמין במאמר בנושא תבניות הגנה מוגברת על המודל.

לפני שמתחילים

לפני שמתחילים, צריך לבצע את המשימות הבאות.

קבלת ההרשאות הנדרשות

כדי לקבל את ההרשאות שנדרשות לניהול תבניות של Model Armor, צריך לבקש מהאדמין להקצות לכם ב-IAM את התפקיד אדמין של Model Armor (roles/modelarmor.admin) בתבניות של Model Armor. כדי לקרוא הסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.

הפעלת ממשקי ה-API

כדי להשתמש בהגנה מוגברת על המודל, צריך להפעיל את Model Armor API.

המסוף

  1. מפעילים את הגנה מוגברת על המודל API.

    תפקידים שנדרשים להפעלת ממשקי API

    כדי להפעיל ממשקי API, צריך את תפקיד ה-IAM 'אדמין של Service Usage' (roles/serviceusage.serviceUsageAdmin), שכולל את ההרשאה serviceusage.services.enable. איך מקצים תפקידים

    להפעלת ה-API

  2. בוחרים את הפרויקט שבו רוצים להפעיל את הגנה מוגברת על המודל.

gcloud

לפני שמתחילים, צריך לבצע את השלבים הבאים באמצעות Google Cloud CLI עם Model Armor API:

  1. במסוף Google Cloud , מפעילים את Cloud Shell.

    הפעלת Cloud Shell

    בחלק התחתון של Google Cloud המסוף יתחיל סשן של Cloud Shell ותופיע הודעה של שורת הפקודה. Cloud Shell היא סביבת מעטפת שבה ה-CLI של Google Cloud מותקן ומוגדרים ערכים לפרויקט הקיים. הסשן יופעל תוך כמה שניות.

  2. הגדרת שינוי מברירת המחדל של נקודת קצה ל-API באמצעות ה-CLI של gcloud

הגדרת שינוי מברירת המחדל של נקודת קצה ל-API באמצעות ה-CLI של gcloud

השלב הזה נדרש רק אם משתמשים ב-CLI של gcloud כדי להפעיל את Model Armor API. כדי לוודא שה-CLI של gcloud מנתב את הבקשות לשירות Model Armor בצורה נכונה, צריך להגדיר ידנית את החלפת נקודת הקצה של ה-API.

מריצים את הפקודה הבאה כדי להגדיר את נקודת קצה ל-API לשירות הגנה מוגברת על המודל.

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

מחליפים את LOCATION באזור שבו רוצים להשתמש בהגנה מוגברת על המודל.

יצירת תבנית של הגנה מוגברת על המודל

תבניות של הגנה מוגברת על המודל מגדירות את המסננים והסף הספציפיים שבהם נעשה שימוש בהגנה מוגברת על המודל כדי לסנן הנחיות ותשובות לסיכוני בטיחות ואבטחה. כדי ליצור תבנית הגנה מוגברת על המודל:

המסוף

  1. נכנסים לדף הגנה מוגברת על המודל במסוף Google Cloud .

    מעבר אל הגנה מוגברת על המודל

  2. מוודאים שאתם צופים בפרויקט שבו הפעלתם את הגנה מוגברת על המודל.

  3. בדף Model Armor (הגנה על מודלים), לוחצים על Create Template (יצירת תבנית). יופיע הדף Create Template (יצירת תבנית).

  4. מציינים את מזהה התבנית. מזהה התבנית יכול להכיל אותיות, ספרות או מקפים. הוא לא יכול להכיל יותר מ-63 תווים, לכלול רווחים או להתחיל במקף.

  5. בוחרים אזור שבו יופעלו תבניות הגנה מוגברת על המודל. אי אפשר לשנות את האזור בהמשך.

  6. אופציונלי: מוסיפים תוויות. תוויות הן צמדי מפתח/ערך שבעזרתם אפשר לקבץ תבניות קשורות.

  7. בקטע Filter version, בוחרים את מספר גרסת המסנן או את הכינוי של גרסת המסנן.

  8. בקטע זיהויים, מגדירים את הגדרות הזיהוי.

  9. אופציונלי: אם בוחרים באפשרות 'זיהוי של Sensitive Data Protection', צריך להגדיר את ההגדרות של Sensitive Data Protection.

  10. בקטע אתיקה של בינה מלאכותית, מגדירים את רמת הסמך לכל מסנן תוכן.

  11. אופציונלי: בקטע Configure logging (הגדרת רישום ביומן), בוחרים את הפעולות שרוצים להגדיר עבורן רישום ביומן.

  12. אופציונלי: בוחרים באפשרות הפעלת תמיכה בכמה שפות כדי להשתמש בהגדרות זיהוי רב-לשוני.

  13. לוחצים על יצירה.

gcloud

מריצים את הפקודה הבאה:

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

מחליפים את מה שכתוב בשדות הבאים:

  • LOCATION: המיקום של התבנית.
  • TEMPLATE_ID: מזהה התבנית.
  • PROJECT_ID: מזהה הפרויקט שאליו שייך התבנית.

REST

כדי ליצור תבנית חדשה של Model Armor, משתמשים בפקודה הבאה.

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

מחליפים את מה שכתוב בשדות הבאים:

  • FILTER_CONFIG: הגדרות הסינון של התבנית.
  • PROJECT_ID: מזהה הפרויקט שאליו שייך התבנית.
  • TEMPLATE_ID: המזהה של התבנית שרוצים ליצור.
  • LOCATION: המיקום של התבנית.

בדוגמה הבאה מוצגת ההגדרה של תבנית Model Armor. בדוגמה הזו, המסננים של אתיקה של בינה מלאכותית מוגדרים לזיהוי של דברי שטנה, הטרדה, תוכן מסוכן ותוכן מיני בוטה עם רמות שונות של רמת סמך. המסנן prompt injection and jailbreak detection מופעל עם רמת מהימנות של HIGH, כלומר רק תוכן שיש סבירות גבוהה שהוא בעייתי יסומן. המסנן malicious URI מופעל.

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

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

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

כדי ליצור תבנית הגנה מוגברת על המודל עם זיהוי רב-לשוני מופעל, צריך להעביר את הפרמטר TEMPLATE_CONFIG בפקודה. הפרמטר הזה מגדיר את ההגדרות של זיהוי השפה.

כדי ליצור תבנית חדשה של Model Armor עם זיהוי רב-לשוני מופעל, משתמשים בפקודה הבאה:

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

בדוגמה הבאה אפשר לראות את ההגדרה של תבנית הגנה מוגברת על המודל עם זיהוי רב-לשוני מופעל.

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

  "piAndJailbreakFilterSettings": {
    "filterEnforcement": "ENABLED",
    "confidenceLevel": "HIGH"
  },
  "maliciousUriFilterSettings": {
    "filterEnforcement": "ENABLED"
  }
 },
 "templateMetadata": {
    "multiLanguageDetection": {
      "enableMultiLanguageDetection": true
    }
  }
}'

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"

C#‎

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את Model Armor C# SDK.

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

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

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

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

        raiFilterSettings.RaiFilters.Add(filters);

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

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

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

        return createdTemplate;
    }
}

המשך

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Model Armor Go SDK.


import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

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

	return err
}

Java

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Model Armor Java SDK.


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

public class CreateTemplate {

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

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

    createTemplate(projectId, locationId, templateId);
  }

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

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

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

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

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

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

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

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

      return createdTemplate;
    }
  }
}

Node.js

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Model Armor Node.js SDK.

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

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

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

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

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

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

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

PHP

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של PHP ולהתקין את Model Armor PHP SDK.

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

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

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

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

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

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

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

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

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

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

Python

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Model Armor Python SDK.


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

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

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

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

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

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

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

בחירת גרסת מסנן

גרסאות המסננים של Model Armor מספקות איזון בין יציבות לעומסי עבודה של ייצור ובין גישה למודלים מעודכנים לזיהוי איומים. מגדירים את גרסת המסנן ברמת התבנית. המסנן version חל על כל המסננים בתבנית, למעט אלה שמפורטים בקטע מסננים שלא משתמשים בגרסאות מסנן. מידע נוסף זמין במאמר בנושא הגדרת גרסת המסנן לתבנית.

הגדרת זיהויים

זיהויים הם הבדיקות הספציפיות ש-הגנה מוגברת על המודל מבצע בהנחיות ובתשובות. ‫Model Armor הוא מערכת גמישה להגדרת זיהויים, שמאפשרת לכם להתאים את רמת ההגנה של אפליקציות ה-AI שלכם. אתם מגדירים את הזיהויים כשיוצרים תבניות. ‫הגנה מוגברת על המודל מבצע את בדיקות הזיהוי הבאות בהנחיות ובתשובות:

  • זיהוי כתובות URL זדוניות: זיהוי כתובות אינטרנט (URL) שנועדו לפגוע במשתמשים או במערכות. כתובות ה-URL האלה עלולות להוביל לאתרי פישינג, להורדות של תוכנות זדוניות או למתקפות סייבר אחרות. מידע נוסף זמין במאמר בנושא זיהוי כתובות URL זדוניות.

  • זיהוי של החדרת הנחיות ופריצה: זיהוי של תוכן זדוני וניסיונות פריצה בהנחיה. מומלץ להגדיר את רמת הסמך לגבוהה כדי למזער תוצאות חיוביות כוזבות ולהבטיח התנהגות עקבית של זיהוי. גם אם מגדירים את רמת הסמך לגבוהה, עדיין יכול להיות שבמקרים נדירים יופיעו תוצאות חיוביות כוזבות. מידע נוסף זמין במאמר זיהוי של הזרקת הנחיות ופריצה.

  • Sensitive Data Protection: איתור מידע רגיש ועזרה במניעת חשיפה מקרית שלו כתוצאה ממתקפות כמו החדרת הנחיות. מידע נוסף זמין במאמר בנושא Sensitive Data Protection.

הגדרת Sensitive Data Protection

‫הגנה מוגברת על המודל משתמש ב-Sensitive Data Protection כדי לזהות מידע רגיש באינטראקציות עם מודלים של LLM ולמנוע את החשיפה שלו. מידע נוסף זמין במאמר Sensitive Data Protection.

ב-Model Armor יש שני מצבים להגדרת Sensitive Data Protection:

  • בסיסי: גישה פשוטה יותר שמשתמשת בסוגי מידע מוגדרים מראש כדי לזהות נתונים רגישים. מידע נוסף על סוגי המידע המוגדרים מראש זמין במאמר בנושא הגדרה בסיסית של Sensitive Data Protection.

  • מתקדם: אפשרות עם יותר הגדרות, שמשתמשת בתבנית בדיקה שמוגדרת בשירות Sensitive Data Protection כמקור יחיד לסוגי מידע (infoTypes) של נתונים רגישים.

אם בוחרים במצב מתקדם, צריך לציין את הפרמטרים הבאים:

  • תבנית בדיקה: תבניות לשמירת פרטי הגדרה של משימות סריקה לבדיקה, כולל גלאים מוגדרים מראש או גלאים בהתאמה אישית לשימוש. מזינים את שם התבנית בפורמט הבא: projects/projectId/locations/locationId/inspectTemplates/templateName

  • אופציונלי: תבנית להסרת פרטים מזהים: תבניות לשמירת פרטי הגדרה של משימות להסרת פרטים מזהים, כולל infoType והמרות של מערכי נתונים מובנים. מזינים מזהה לתבנית לביטול הזיהוי בפורמט הבא: projects/projectId/locations/locationId/deidentifyTemplates/templateName

מוודאים שקיימות תבנית בדיקה ותבנית להסרת פרטי הזיהוי ב-Sensitive Data Protection. אם התבנית נמצאת בפרויקט אחר, צריך להעניק לסוכן השירות של הגנה מוגברת על המודל את התפקיד 'משתמש DLP' (roles/dlp.user) ואת התפקיד 'קורא DLP' (roles/dlp.reader) בפרויקט הזה.

הגדרת רמת הסמך

רמת הסמך מייצגת את הסבירות להתאמה בין הממצאים לסוג של מסנן תוכן. אפשר להגדיר את רמת הסמך לכל מסנן תוכן. הערכים האפשריים הם:

  • ללא: לא זוהה תוכן.
  • נמוכה ומעלה: התוכן מזוהה ברמת אמינות נמוכה, בינונית או גבוהה.
  • בינונית ומעלה: התוכן מזוהה ברמת מהימנות בינונית או גבוהה.
  • גבוהה: התוכן מזוהה ברמת אמינות גבוהה.

כדי להקפיד על אכיפה מחמירה יותר, מגדירים את רמת הסמך לנמוכה ומעלה כדי לזהות את רוב התוכן שמשתייך לסוג של מסנן תוכן.

כדי להפעיל רישום מקיף ביומן בתבנית, אפשר לעיין במאמר רישום ביומן ביקורת ורישום ביומן פלטפורמה של הגנה מוגברת על המודל.

הגדרת סוג האכיפה של תבניות

כדי להגדיר איך הגנה מוגברת על המודל מטפל בזיהויים, צריך להגדיר את סוג האכיפה.

בדוגמה הבאה מוצגת הגדרת תבנית הגנה מוגברת על המודל עם סוג האכיפה Inspect only.

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

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

מחליפים את מה שכתוב בשדות הבאים:

  • PROJECT_ID: מזהה הפרויקט שאליו שייך התבנית.
  • TEMPLATE_ID: המזהה של התבנית שרוצים ליצור.
  • LOCATION: המיקום של התבנית.

הצגת תבנית של Model Armor

אפשר לעיין בתבניות קיימות כדי להבין אילו הגדרות זמינות, וכדי לפתור בעיות שקשורות להנחיות ולתשובות לסינון.

המסוף

  1. נכנסים לדף הגנה מוגברת על המודל במסוף Google Cloud .

    מעבר אל הגנה מוגברת על המודל

  2. מוודאים שאתם צופים בפרויקט שבו הפעלתם את הגנה מוגברת על המודל. מוצג הדף Model Armor עם רשימת התבניות שנוצרו לפרויקט.

  3. לוחצים על תבנית מהרשימה כדי לראות את הפרטים שלה.

gcloud

מריצים את הפקודה הבאה:

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

מחליפים את מה שכתוב בשדות הבאים:

  • LOCATION: המיקום של התבנית.
  • TEMPLATE_ID: מזהה התבנית.
  • PROJECT_ID: מזהה הפרויקט שאליו שייך התבנית.

REST

מריצים את הפקודה הבאה:

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

מחליפים את מה שכתוב בשדות הבאים:

  • PROJECT_ID: מזהה הפרויקט שאליו שייך התבנית.
  • TEMPLATE_ID: המזהה של התבנית שרוצים להציג.
  • LOCATION: המיקום של התבנית.

C#‎

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את Model Armor C# SDK.

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

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

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

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

        return template;
    }
}

המשך

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Model Armor Go SDK.


import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

	return nil
}

Java

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Model Armor Java SDK.


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

public class GetTemplate {

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

    getTemplate(projectId, locationId, templateId);
  }

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

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

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

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

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

      return template;
    }
  }
}

Node.js

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Model Armor Node.js SDK.

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

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

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

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

const request = {
  name: name,
};

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

PHP

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של PHP ולהתקין את Model Armor PHP SDK.

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

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

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

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

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

Python

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Model Armor Python SDK.


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

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

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

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

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

עדכון של תבנית הגנה מוגברת על המודל

חשוב לעדכן את התבניות באופן קבוע כדי לשמור על מצב אבטחה חזק ויעיל של אפליקציות ה-AI.

המסוף

  1. נכנסים לדף הגנה מוגברת על המודל במסוף Google Cloud .

    מעבר אל הגנה מוגברת על המודל

  2. מוודאים שאתם צופים בפרויקט שבו הפעלתם את הגנה מוגברת על המודל. מוצג הדף Model Armor עם רשימת התבניות שנוצרו עבור הארגון.

  3. לוחצים על התבנית שרוצים לעדכן מהרשימה. יוצג הדף Template details.

  4. לוחצים על Edit.

  5. מעדכנים את הפרמטרים הנדרשים ולוחצים על שמירה.

gcloud

מריצים את הפקודה הבאה:

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

מחליפים את מה שכתוב בשדות הבאים:

  • LOCATION: המיקום של התבנית.
  • TEMPLATE_ID: מזהה התבנית.
  • PROJECT_ID: מזהה הפרויקט שאליו שייך התבנית.

REST

מריצים את הפקודה הבאה:

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

מחליפים את מה שכתוב בשדות הבאים:

  • PROJECT_ID: מזהה הפרויקט שאליו שייך התבנית.
  • LOCATION: המיקום של התבנית.
  • TEMPLATE_ID: מזהה התבנית.
  • UPDATE_MASK: השדות שרוצים לעדכן, כמו filterConfig ו-filterConfig.piAndJailbreakFilterSettings. אם משאירים את השדה הזה ריק, כל הגדרות המסנן מתעדכנות.

כל שאר השדות הם קבועים. ניסיונות לעדכן שדות אחרים (לדוגמה, ניסיונות לעדכן את שם התבנית) יגרמו לשגיאה.

C#‎

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את Model Armor C# SDK.

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

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

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

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

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

            raiFilterSettings.RaiFilters.Add(filters);

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

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

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

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

            return updatedTemplate;
        }
    }
}

המשך

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Model Armor Go SDK.


import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

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

	return nil
}

Java

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Model Armor Java SDK.


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

public class UpdateTemplate {

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

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

    updateTemplate(projectId, locationId, templateId);
  }

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

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

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

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

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

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

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

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

      return updatedTemplate;
    }
  }
}

Node.js

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Model Armor Node.js SDK.

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

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

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

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

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

const request = {
  template: updatedTemplate,
};

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

PHP

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של PHP ולהתקין את Model Armor PHP SDK.

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

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

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

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

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

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

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

Python

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Model Armor Python SDK.


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

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

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

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

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

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

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

מחיקה של תבנית Model Armor

מוחקים תבנית כשכבר לא משתמשים בה, כשמחליפים אותה בתבנית חדשה או כשמדיניות האבטחה משתנה.

המסוף

  1. נכנסים לדף הגנה מוגברת על המודל במסוף Google Cloud .

    מעבר אל הגנה מוגברת על המודל

  2. מוודאים שאתם צופים בפרויקט שבו הפעלתם את הגנה מוגברת על המודל. מוצג הדף Model Armor עם רשימת התבניות שנוצרו עבור הארגון.

  3. לוחצים על התבנית שרוצים למחוק מהרשימה. יוצג הדף Template details.

  4. לוחצים על Delete. מוצגת תיבת דו-שיח לאישור.

  5. מזינים את שם התבנית כדי לאשר את המחיקה ולוחצים על מחיקה.

gcloud

מריצים את הפקודה הבאה:

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

מחליפים את מה שכתוב בשדות הבאים:

  • LOCATION: המיקום של התבנית.
  • TEMPLATE_ID: מזהה התבנית.
  • PROJECT_ID: מזהה הפרויקט שאליו שייך התבנית.

REST

מריצים את הפקודה הבאה:

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

מחליפים את מה שכתוב בשדות הבאים:

  • PROJECT_ID: מזהה הפרויקט שאליו שייך התבנית.
  • LOCATION: המיקום של התבנית.
  • TEMPLATE_ID: מזהה התבנית.

C#‎

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את Model Armor C# SDK.

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

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

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

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

המשך

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Model Armor Go SDK.


import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

	return err
}

Java

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Model Armor Java SDK.


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

public class DeleteTemplate {

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

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

    deleteTemplate(projectId, locationId, templateId);
  }

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

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

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

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

Node.js

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Model Armor Node.js SDK.

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

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

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

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

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

PHP

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של PHP ולהתקין את Model Armor PHP SDK.

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

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

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

    $client->deleteTemplate($dltTemplateRequest);

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

Python

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Model Armor Python SDK.


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

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

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

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

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

מטא-נתונים של תבנית

מטא-נתונים של תבנית הגנה מוגברת על המודל עוזרים לכם להגדיר את ההתנהגות של הגנה מוגברת על המודל, כולל טיפול בבדיקות בטיחות ואבטחה, טיפול בשגיאות והתנהגות רישום ביומן.

המטא-נתונים של התבנית עבור Model Armor כוללים את השדות הבאים:

מטא-נתונים סוג ערך ברירת המחדל תיאור
multiLanguageDetection בוליאני לא נכון ההגדרה הזו מאפשרת זיהוי של כמה שפות.
enforcement_type ספירה INSPECT_AND_BLOCK

הגדרה של סוג האכיפה. אפשר להשתמש באחד מהערכים הבאים:

  • INSPECT_ONLY: הגנה מוגברת על המודל בודקת בקשות שמפירות את ההגדרות שנקבעו, אבל לא חוסמת אותן.
  • INSPECT_AND_BLOCK: הגנה מוגברת על המודל חוסמת בקשות שמפירות את ההגדרות שהוגדרו.
log_template_operations בוליאני לא נכון הגדרה שמאפשרת רישום ביומן של פעולות בתבנית.
log_sanitize_operations בוליאני לא נכון הגדרה שמאפשרת רישום ביומן של פעולות ניקוי.

המאמרים הבאים