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

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

שימוש בנקודת קצה אזורית או במספר אזורים

כשעובדים עם תבנית של Model Armor, צריך להשתמש בנקודת קצה אזורית או במספר אזורים (modelarmor.LOCATION.rep.googleapis.com) שתואמת למיקום של התבנית. במאמר אכיפת מיקום אחסון הנתונים בתבניות מוסבר איך אוכפים את מיקום אחסון הנתונים בכל אזור או במספר אזורים.

בנקודת הקצה הגלובלית (modelarmor.googleapis.com) אי אפשר לנהל תבניות של Model Armor או להסיר תוכן זדוני או רגיש מהנחיות ומתשובות.

מתי כדאי להשתמש בתבניות של Model Armor

הנה כמה תרחישי שימוש נפוצים:

  • סינון אחיד בכל האפליקציות: הגדירו הגדרות סינון ורמות סף מרכזיות, שעומסי עבודה שונים יכולים להפנות אליהן.
  • התאמה אישית של ספי הזיהוי וההגדרות: אפשר לשנות את רגישות המסנן – למשל, להגדיר ספי סמך נמוכים, בינוניים או גבוהים – ואת הגדרות המסנן לתרחישי שימוש או לסביבות שונות.
  • הגדרת הגנה בכמה קטגוריות: שילוב של Sensitive Data Protection, זיהוי פריצה, בדיקת URI זדוניים ומסננים להחדרת פרומפטים במדיניות אחת.
  • הפרדה בין מדיניות הפיתוח למדיניות הייצור: כדאי להשתמש בתבניות נפרדות כדי לבדוק כללי סינון מחמירים יותר בסביבת ה-Staging לפני שמפעילים אותם בשירותי הייצור.

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

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

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

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

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

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

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

המסוף

  1. מפעילים את Model Armor API, אם הוא עדיין לא מופעל.

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

    כדי להפעיל ממשקי API, צריך את ההרשאה serviceusage.services.enable. אם יצרתם את הפרויקט, סביר להניח שכבר יש לכם את ההרשאה הזו דרך התפקיד "בעלים" (roles/owner). אחרת, תוכלו לקבל את ההרשאה הזו דרך התפקיד "אדמין בממשק 'שימוש בשירות'" (roles/serviceusage.serviceUsageAdmin). איך מקצים תפקידים

    להפעלת ה-API

  2. בוחרים את הפרויקט שבו רוצים להפעיל את Model Armor.

gcloud

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

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

    הפעלת Cloud Shell

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

  2. מפעילים את Model Armor API, אם הוא עדיין לא מופעל:

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

    כדי להפעיל ממשקי API, צריך את ההרשאה serviceusage.services.enable. אם אתם יצרתם את הפרויקט, סביר להניח שכבר יש לכם את ההרשאה הזו דרך התפקיד "בעלים" (roles/owner). אחרת, תוכלו לקבל את ההרשאה הזו דרך התפקיד "אדמין בממשק 'שימוש בשירות'" (roles/serviceusage.serviceUsageAdmin). איך מקצים תפקידים

    gcloud services enable modelarmor.googleapis.com

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

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

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

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

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

מחליפים את LOCATION באזור או במספר האזורים שבהם רוצים להשתמש ב-Model Armor.

יצירת תבנית של Model Armor

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

המסוף

  1. נכנסים לדף Model Armor במסוף Google Cloud .

    כניסה לדף Model Armor

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

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

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

  5. בקטע Location type, בוחרים אזור או כמה אזורים שבהם יפעלו הפעולות של Model Armor. אי אפשר לשנות את המיקום אחר כך.

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

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

  7. אופציונלי: בקטע Labels, מוסיפים את צמדי המפתח/ערך שרוצים להשתמש בהם כדי לקבץ תבניות קשורות.

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

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

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

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

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

  13. אופציונלי: מרחיבים את הקטע Additional configurations (optional) ומשנים את ההגדרות הבאות:

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

gcloud

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

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

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

  • ‫LOCATION: המיקום של התבנית.
  • ‫TEMPLATE_ID: מזהה התבנית.
  • ‫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: הגדרת המסנן של התבנית בפורמט JSON.
  • ‫PROJECT_ID: מזהה הפרויקט שהתבנית שייכת אליו.
  • ‫TEMPLATE_ID: המזהה של התבנית שרוצים ליצור.
  • ‫LOCATION: המיקום של התבנית.

בדוגמה הבאה מוצגת הגדרת המסנן של Model Armor‏ (FilterConfig), שבה אתם מגדירים מה אתם רוצים לזהות. בדוגמה הזו, המסננים של AI אחראי מוגדרים לדברי שטנה, הטרדה, תוכן מסוכן ותוכן מיני בוטה, עם רמות סמך שונות. מסנן הזיהוי של החדרת פרומפטים ופריצות מופעל ברמת סמך של 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/templates?template_id=TEMPLATE_ID"

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

בדוגמה הבאה יוצרים הגדרת תבנית של "הגנה מוגברת על המודל" שמופעלים בה זיהוי של כמה שפות וסוגי נתונים (תמונה וטקסט).

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

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

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

C#‎

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

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

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

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

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

        raiFilterSettings.RaiFilters.Add(filters);

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

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

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

        return createdTemplate;
    }
}

המשך

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


import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

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

	return err
}

Java

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


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

public class CreateTemplate {

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

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

    createTemplate(projectId, locationId, templateId);
  }

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

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

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

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

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

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

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

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

      return createdTemplate;
    }
  }
}

Node.js

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

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

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

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

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

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

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

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

PHP

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

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

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

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

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

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

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

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

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

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

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

Python

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


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

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

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

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

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

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

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

הגדרת תאימות של מיקום אחסון הנתונים

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

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

השבתת התאימות למיקום אחסון הנתונים מפעילה את כל התכונות של Model Armor, חוץ ממודליות התמונה, שעדיין מוגבלת לאזורים us ו-eu.

השבתת האילוץ של מדיניות הארגון לגבי מיקום אחסון הנתונים

כברירת מחדל, Model Armor אוכף את המגבלה המנוהלת Require Model Armor Template Data Residency Compliance (constraints/modelarmor.managed.requireTemplateDataResidencyCompliance) של שירות מדיניות הארגון. כשהאילוץ הזה נאכף, לא ניתן ליצור או לעדכן תבנית שבה data_residency_compliant מוגדר ל-false. תבניות קיימות ובקשות להסרת תוכן זדוני או רגיש מהנחיות ומתשובות לא מושפעות, אלא אם מעדכנים תבנית בזמן שהערך של data_residency_compliant הוא false. מידע נוסף זמין במאמר חובה לעמוד בדרישות של מיקום אחסון הנתונים של התבנית.

כדי להשבית את אכיפת מיקום אחסון הנתונים בתבנית:

  1. מבקשים מהאדמין של מדיניות הארגון (roles/orgpolicy.policyAdmin) להשבית את האילוץ constraints/modelarmor.managed.requireTemplateDataResidencyCompliance בפרויקט, בתיקייה או בארגון. הוראות מפורטות זמינות במאמר שימוש באילוצים מנוהלים במדיניות הארגון.
  2. כשיוצרים או מעדכנים את התבנית, מבטלים את הבחירה באפשרות Enforce data residency במסוף Google Cloud , או מגדירים את data_residency_compliant לערך false באמצעות Model Armor API.

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

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

בחירת אופן ההגעה

אתם יכולים להשתמש במודליות כדי לציין אם אתם רוצים לסרוק את הדברים הבאים:

  • הכול: סריקה של טקסט ותמונות.
  • אופנים ספציפיים:

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

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

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

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

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

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

קביעת הגדרות של Sensitive Data Protection

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

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

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

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

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

  • תבנית בדיקה: תבניות לשמירת פרטי ההגדרות של משימות סריקה לבדיקה, כולל אילו גלאי infoType מוגדרים מראש או מותאמים אישית צריך להשתמש. מזינים את שם התבנית בפורמט הבא: projects/PROJECT_ID/locations/LOCATION/inspectTemplates/TEMPLATE_ID

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

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

הבקשות מעובדות ב-Model Armor באופן שונה בהתאם לתבנית שציינתם – רק תבנית בדיקה או גם תבנית בדיקה וגם תבנית להסרת פרטי הזיהוי:

  • בדיקת תבנית בלבד: Model Armor מחפש בתוכן את סוגי המידע שצוינו בתבנית הבדיקה ומדווח על הממצאים.

  • בדיקה והסרת פרטים מזהים מתבנית: "הגנה מוגברת על המודל" מסירה את פרטי הזיהוי של סוגי המידע שצוינו גם בתבנית הבדיקה וגם בתבנית הסרת פרטי הזיהוי.

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

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

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

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

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

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

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

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

בשדה template_metadata של הגדרת התבנית, מגדירים את enforcement_type לערך INSPECT_ONLY או INSPECT_AND_BLOCK.

export TEMPLATE_CONFIG='{
   "filter_config": {
    "rai_settings": {
     "rai_filters": [{
       "filter_type": "HATE_SPEECH",
       "confidence_level": "MEDIUM_AND_ABOVE"
      }, {
      "filter_type": "HARASSMENT",
      "confidence_level": "MEDIUM_AND_ABOVE"
    }, {
      "filter_type": "DANGEROUS",
      "confidence_level": "MEDIUM_AND_ABOVE"
    },{
      "filter_type": "SEXUALLY_EXPLICIT",
      "confidence_level": "MEDIUM_AND_ABOVE"
    }]
  },
  "pi_and_jailbreak_filter_settings": {
    "filter_enforcement": "ENABLED",
    "confidence_level": "HIGH"
  },
  "malicious_uri_filter_settings": {
    "filter_enforcement": "ENABLED"
  }
 },
 "template_metadata": {
    "enforcement_type": "INSPECT_ONLY",
    "multi_language_detection": {
      "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/templates?template_id=TEMPLATE_ID"

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

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

הגדרת כללי החרגה ספציפיים לתבנית

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

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

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

המסוף

  1. נכנסים לדף Model Armor במסוף Google Cloud .

    כניסה לדף Model Armor

  2. מוודאים שאתם צופים בפרויקט שבו הפעלתם את Model Armor. נפתח הדף 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.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)

עדכון תבנית של Model Armor

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

המסוף

  1. נכנסים לדף Model Armor במסוף Google Cloud .

    כניסה לדף Model Armor

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

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

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

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

gcloud

כדי לעדכן תבנית, מריצים את הפקודה gcloud model-armor templates update וכוללים את הדגלים של ההגדרות שרוצים לשנות.

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

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

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

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

REST

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

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

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

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

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

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. נכנסים לדף Model Armor במסוף Google Cloud .

    כניסה לדף Model Armor

  2. מוודאים שאתם צופים בפרויקט שבו הפעלתם את Model Armor. בדף 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.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 כוללים את השדות הבאים:

מטא-נתונים סוג ערך ברירת המחדל תיאור
enforcement_type טיפוסים בני מנייה (enum) INSPECT_AND_BLOCK

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

  • ‫INSPECT_ONLY: המערכת בודקת בקשות שמפירות את ההגדרות שנקבעו, אבל לא חוסמת אותן.
  • ‫INSPECT_AND_BLOCK: המערכת חוסמת בקשות שמפירות את ההגדרות שנקבעו.
log_template_operations בוליאני לא נכון הפעלת הרישום ביומן של פעולות בתבניות.
log_sanitize_operations בוליאני לא נכון הפעלת הרישום ביומן של פעולות הסרת תוכן זדוני או רגיש.
multiLanguageDetection בוליאני לא נכון הפעלת זיהוי של כמה שפות.
מודאליות (גרסת טרום-השקה (Preview)) טיפוסים בני מנייה (enum) ריק ההגדרה קובעת אם לסרוק טקסט, תמונות או את שניהם. אם משאירים את השדה הזה ריק, המערכת סורקת רק טקסט.

משתמשים באחד מהערכים הבאים:

data_residency_compliant בוליאני True

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

  • ‫True: השבתת תכונות שלא נתמכות באופן מקומי בתחום השיפוט של אזור התבנית, כדי למנוע מהנתונים לצאת מתחום השיפוט המקומי.
  • ‫False: השבתת הבדיקות של תאימות מיקום אחסון הנתונים, ומתן הרשאה לניתוב הנתונים בין תחומי שיפוט שונים כשפיצ'ר מסוים לא זמין באופן מקומי בתחום השיפוט.

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

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

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