指定底限設定

本文說明如何查看及更新 Model Armor 底限設定,並提供違反底限設定的範例。

底限設定有兩個主要用途:

  • 範本一致性:確保新範本的限制至少等同於底限設定中定義的限制。範本遵循度是在組織和資料夾層級定義。

  • 內嵌強制執行:將 Model Armor 防護機制套用至 Gemini 模型和 Google Cloud MCP 伺服器。內嵌強制執行功能是在專案層級設定。如果您使用底限設定進行內嵌違規處置,則在專案中建立的所有範本都必須符合這些底限設定。

底限設定的使用時機

以下是一些常見用途:

  • 強制執行範本法規遵循,並防止政策倒退:在組織、資料夾或專案層級定義最低篩選器門檻,確保新建立和更新的範本符合安全性標準,且防護等級不會低於既定基準。
  • 為模型和工具啟用內嵌強制執行功能:在專案層級保護支援的 Gemini 模型和 Google Cloud 遠端 MCP 伺服器,無須修改應用程式程式碼。
  • 管理分散式團隊設定:允許自主專案團隊建立自訂範本,同時確保其設定符合組織管理政策。

事前準備

開始前,請先完成下列工作。

取得必要權限

如要取得管理底限設定所需的權限,請要求管理員授予您 Model Armor 底限設定的 Model Armor 底限設定管理員 (roles/modelarmor.floorSettingsAdmin) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

啟用 API

您必須先啟用 Model Armor API,才能使用 Model Armor。

控制台

  1. 啟用 Model Armor API (如果尚未啟用)。

    啟用 API 所需的角色

    您必須具備 serviceusage.services.enable 權限,才能啟用 API。如果您建立了專案,可能已透過擁有者角色 (roles/owner) 取得這項權限。否則,您可以透過 Service Usage 管理員角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。

    啟用 API

  2. 選取要啟用 Model Armor 的專案。

gcloud

開始之前,請按照下列步驟,搭配使用 Google Cloud CLI 和 Model Armor API:

  1. 在 Google Cloud 控制台啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

  2. 啟用 Model Armor API (如果尚未啟用):

    啟用 API 所需的角色

    您必須具備 serviceusage.services.enable 權限,才能啟用 API。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「Service Usage 管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。

    gcloud services enable modelarmor.googleapis.com

  3. 使用 gcloud CLI 設定 API 端點覆寫。

使用 gcloud CLI 設定 API 端點覆寫

只有在搭配 Model Armor 使用 gcloud CLI,且想使用預設 us 多區域以外的區域或多區域時,才需要執行這個步驟。您必須手動設定 API 端點覆寫,確保 gcloud CLI 正確將要求轉送至 Model Armor 服務。

執行下列指令,使用全域 API 端點:

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

底限設定應用

系統一律會套用本機設定。舉例來說,如果底限設定發生衝突,系統會優先採用資源階層中較低層級的設定。同樣地,專案層級底限設定會覆寫衝突的資料夾層級底限設定。

下表列出底價設定在不同層級的套用方式:

底限設定層級 應用程式
組織層級 適用於組織內的所有項目。
資料夾層級 適用於該特定資料夾中的所有專案。
專案層級 僅適用於該特定專案。

以下舉例說明在不同層級設定底價時,系統會如何套用底價設定。舉例來說,假設您設定的底限如下:

  • 資料夾層級 (較不具體) 底限設定:這個資料夾中的所有內容都必須啟用惡意 URI 篩選器。
  • 專案層級 (更具體) 的底限設定:資料夾中的專案必須使用提示詞注入和越獄偵測功能,且信賴度為中等。

在這個情境中,設定會產生下列結果:

  • 在專案中建立的任何範本,都必須包含提示詞注入和越獄偵測篩選器,因為專案層級設定一律優先於資料夾層級設定。

  • 在其他專案或資料夾中建立的範本,不會受到第一個資料夾的惡意 URI 篩選器規則影響。

底價設定只會套用至階層中的特定層級,除非是在組織層級設定,才會套用至整個組織。

範本和底限設定一致性

建立或更新 Model Armor 範本時,Model Armor 會檢查範本設定是否符合底限設定。您無法建立或更新限制比底限設定寬鬆的範本。

您可以在組織、資料夾和專案層級設定底限。使用者介面僅適用於專案層級,可讓您沿用組織層級或資料夾層級的設定。如要在組織或資料夾層級設定底限,請務必使用 API。

範本一致性會驗證範本設定。資料檢查會使用符合規範的範本中定義的設定,在執行階段分析提示或回覆。下表說明範本遵循和資料檢查如何套用至範本和底價設定。

檢查 底限設定 範本
範本一致性 在組織、資料夾或專案層級設定。

注意:您可以設定 Sensitive Data Protection,對範本強制執行資料安全性政策。但不會驗證範本一致性。

只能在專案層級設定。
資料檢查 僅在專案層級強制執行,並使用檢查和封鎖模式。 透過 REST API、Service Extensions、Gemini Enterprise 和 Agent Runtime 執行。

與 Gemini Enterprise Agent Platform 和 Google Cloud MCP 伺服器整合

Model Armor 與 Agent Platform 和 Google Cloud MCP 伺服器整合,可根據您定義的底限設定,篩選 Gemini 模型和Google Cloud 遠端 MCP 伺服器的要求和回覆。您必須啟用 Cloud Logging,才能查看提示和回覆。詳情請參閱「Model Armor 與 Gemini Enterprise Agent Platform 整合」和「Model Armor 與 Google Cloud MCP 伺服器整合」。

底限設定篩選器版本

底價設定預設會使用Stable 篩選器版本。以下清單說明篩選器版本與各項整合功能的搭配運作方式:

指定底限設定

設定底限,定義 Model Armor 範本的最低偵測門檻。這些設定可確保所有新範本和修改過的範本都符合特定規定。

如要調整樓層設定,請選擇下列其中一個選項:

控制台

  1. 前往 Google Cloud 控制台的「Model Armor」頁面。

    前往 Model Armor

  2. 選取專案。
  3. 在「Model Armor」頁面中,前往「Floor settings」(底限設定) 分頁標籤,然後按一下「Configure floor settings」(設定底限設定)。
  4. 在「設定底價」頁面,選取設定選項。
  5. 在「偵測」部分,設定偵測設定。
  6. 選用:如果選取 Sensitive Data Protection 偵測功能,請調整 Sensitive Data Protection 設定。
  7. 在「負責任的 AI」部分,設定各個內容篩選器的信心水準。

  8. 在「服務」部分,選取要套用這些底限設定的服務。

  9. 在「記錄」部分,選取「啟用 Cloud Logging」,記錄所有使用者提示詞、模型回覆和底限設定偵測工具結果。

  10. 選取「Enable multi-language support」(啟用多語言支援),即可使用多語言偵測設定。

  11. 按一下「儲存樓層設定」。

Terraform

如要以宣告方式在整個組織、資料夾或專案階層中強制執行最低安全門檻,請使用 google 供應商 (>= 6.13.0) 設定 google_model_armor_floorsetting 資源:

resource "google_model_armor_floorsetting" "floor_setting" {
  parent   = RESOURCE_PARENT
  location = "global"

  filter_config {
    rai_settings {
      rai_filters {
        filter_type      = "HATE_SPEECH"
        confidence_level = "MEDIUM_AND_ABOVE"
      }
      rai_filters {
        filter_type      = "HARASSMENT"
        confidence_level = "HIGH"
      }
      rai_filters {
        filter_type      = "DANGEROUS"
        confidence_level = "MEDIUM_AND_ABOVE"
      }
      rai_filters {
        filter_type      = "SEXUALLY_EXPLICIT"
        confidence_level = "MEDIUM_AND_ABOVE"
      }
    }

    sdp_settings {
      basic_config {
        filter_enforcement = "ENABLED"
      }
    }

    pi_and_jailbreak_filter_settings {
      filter_enforcement = "ENABLED"
      confidence_level   = "HIGH"
    }

    malicious_uri_filter_settings {
      filter_enforcement = "ENABLED"
    }
  }

  enable_floor_setting_enforcement = true

  integrated_services = [
    "AI_PLATFORM",
    "GOOGLE_MCP_SERVER",
  ]

  ai_platform_floor_setting {
    inspect_and_block    = true
    enable_cloud_logging = true
  }

  google_mcp_server_floor_setting {
    inspect_and_block    = true
    enable_cloud_logging = true
  }

  floor_setting_metadata {
    multi_language_detection {
      enable_multi_language_detection = true
    }
  }
}

將 RESOURCE_PARENT 替換為底價設定適用的階層範圍:

  • 組織層級:organizations/ORGANIZATION_ID,控管組織中的所有資料夾和專案。

  • 資料夾層級:folders/FOLDER_ID,控管資料夾中的所有專案。

  • 專案層級:projects/PROJECT_ID,控管單一專案。

樓層設定變更會在幾分鐘後生效。

定義底限設定的繼承方式

設定底限時,請選取設定選項。

  • 繼承上層項目的底限設定:繼承資源階層中先前設定的底限。按一下「儲存底價設定」,然後略過其餘步驟。如要查看沿用的設定,請前往「底價設定」分頁。

  • 自訂:定義這項專案的底限設定。您為專案定義的自訂設定會覆寫任何沿用的底限設定。

  • 停用:停用所有繼承的底限設定。這表示 Gemini 工作負載的 Model Armor 範本和 Agent Platform 不會套用任何偵測規則。按一下「儲存底價設定」,然後略過其餘步驟。在「底價設定」分頁中查看停用狀態。

定義底限設定的套用位置

選取下列其中一項服務,套用設定的底限。

  • Model Armor - 建立及更新範本:Model Armor 會檢查專案中每個新建立和修改過的 Model Armor 範本,確保最低設定符合底限設定。

  • Google MCP 伺服器:底限設定會檢查與 Google 或 Google Cloud 遠端 MCP 伺服器之間的往來要求,確認是否達到底限設定門檻。詳情請參閱「Model Armor 與 Google Cloud MCP 伺服器整合」(預先發布版)。

  • Agent Platform:篩選傳送至 Gemini 模型的請求,並記錄或封鎖符合底限設定門檻的請求。

    如果選取「Agent Platform」,系統會顯示「Agent Platform」部分,您可以在此選擇底限設定的強制執行方式。

    • 僅檢查:偵測不符合底限設定的要求,但不加以封鎖。
    • 檢查並封鎖不符合門檻的要求:偵測並封鎖不符合底限設定的要求。

查看 Model Armor 底限設定

查看 Model Armor 底限設定,確認現有設定、找出 AI 應用程式的最低需求,或在範本未正常運作時排解問題。

執行下列指令,查看 Model Armor 底限設定。

控制台

  1. 前往 Google Cloud 控制台的「Model Armor」頁面。

    前往 Model Armor

  2. 確認您查看的是已啟用 Model Armor 的專案。

  3. 在「Model Armor」頁面,前往「底限設定」分頁。如果底價設定是在組織層級設定,您就可以查看。如果未定義任何底價設定,則必須進行設定。詳情請參閱「設定底價」。

gcloud

  • 查看專案的 Model Armor 底限設定。

      gcloud model-armor floorsettings describe \
          --full-uri='projects/PROJECT_ID/locations/global/floorSetting'
  • 查看組織的 Model Armor 底限設定。

      gcloud model-armor floorsettings describe \
          --full-uri='organizations/ORGANIZATION_ID/locations/global/floorSetting'
  • 查看資料夾的 Model Armor 底限設定。

       gcloud model-armor floorsettings describe \
           --full-uri='folders/FOLDER_ID/locations/global/floorSetting'

    更改下列內容:

    • 底限設定的專案 ID。
    • 底限設定的資料夾 ID。
    • 底限設定的組織 ID。

REST

  • 查看專案的 Model Armor 底限設定。

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://modelarmor.googleapis.com/v1/projects/PROJECT_ID/locations/global/floorSetting"
  • 查看資料夾的 Model Armor 底限設定。

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://modelarmor.googleapis.com/v1/folders/FOLDER_ID/locations/global/floorSetting"
  • 查看組織的 Model Armor 底限設定。

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://modelarmor.googleapis.com/v1/organizations/ORGANIZATION_ID/locations/global/floorSetting"

更改下列內容:

  • 底限設定的專案 ID。
  • 底限設定的資料夾 ID。
  • 底限設定的組織 ID。

C#

如要執行這段程式碼,請先設定 C# 開發環境,並安裝 Model Armor C# SDK。

Go

如要執行這段程式碼,請先設定 Go 開發環境,並安裝 Model Armor Go SDK。

  • 查看特定專案的 Model Armor 底限設定。

    
    import (
    	"context"
    	"fmt"
    	"io"
    
    	modelarmor "cloud.google.com/go/modelarmor/apiv1"
    	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
    )
    
    // getProjectFloorSettings gets details of a single floor setting of a project.
    //
    // This method retrieves the details of a single floor setting of a project.
    //
    // w io.Writer: The writer to use for logging.
    // projectID string: The ID of the project.
    func getProjectFloorSettings(w io.Writer, projectID string) error {
    	ctx := context.Background()
    
    	// Create the Model Armor client.
    	client, err := modelarmor.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("failed to create client: %w", err)
    	}
    	defer client.Close()
    
    	floorSettingsName := fmt.Sprintf("projects/%s/locations/global/floorSetting", projectID)
    
    	// Get the project floor setting.
    	req := &modelarmorpb.GetFloorSettingRequest{
    		Name: floorSettingsName,
    	}
    
    	response, err := client.GetFloorSetting(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to get floor setting: %w", err)
    	}
    
    	// Print the retrieved floor setting using fmt.Fprintf with the io.Writer.
    	fmt.Fprintf(w, "Retrieved floor setting: %v\n", response)
    
    	return nil
    }
    
  • 查看特定資料夾的 Model Armor 底限設定。

    
    import (
    	"context"
    	"fmt"
    	"io"
    
    	modelarmor "cloud.google.com/go/modelarmor/apiv1"
    	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
    )
    
    // getFolderFloorSettings gets details of a single floor setting of a folder.
    //
    // This method retrieves the details of a single floor setting of a folder.
    //
    // w io.Writer: The writer to use for logging.
    // folderID string: The ID of the folder.
    func getFolderFloorSettings(w io.Writer, folderID string) error {
    	ctx := context.Background()
    
    	// Create the Model Armor client.
    	client, err := modelarmor.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("failed to create client: %w", err)
    	}
    	defer client.Close()
    
    	// Prepare folder floor setting path/name
    	floorSettingsName := fmt.Sprintf("folders/%s/locations/global/floorSetting", folderID)
    
    	// Get the folder floor setting.
    	req := &modelarmorpb.GetFloorSettingRequest{
    		Name: floorSettingsName,
    	}
    
    	response, err := client.GetFloorSetting(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to get floor setting: %w", err)
    	}
    
    	// Print the retrieved floor setting using fmt.Fprintf with the io.Writer.
    	fmt.Fprintf(w, "Retrieved folder floor setting: %v\n", response)
    
    	return nil
    }
    
  • 查看特定組織的 Model Armor 底限設定。

    
    import (
    	"context"
    	"fmt"
    	"io"
    
    	modelarmor "cloud.google.com/go/modelarmor/apiv1"
    	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
    )
    
    // getOrganizationFloorSettings gets details of a single floor setting of an organization.
    //
    // This method retrieves the details of a single floor setting of an organization.
    //
    // w io.Writer: The writer to use for logging.
    // organizationID string: The ID of the organization.
    func getOrganizationFloorSettings(w io.Writer, organizationID string) error {
    	ctx := context.Background()
    
    	// Create the Model Armor client.
    	client, err := modelarmor.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("failed to create client: %w", err)
    	}
    	defer client.Close()
    
    	floorSettingsName := fmt.Sprintf("organizations/%s/locations/global/floorSetting", organizationID)
    
    	// Get the organization floor setting.
    	req := &modelarmorpb.GetFloorSettingRequest{
    		Name: floorSettingsName,
    	}
    
    	response, err := client.GetFloorSetting(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to get floor setting: %w", err)
    	}
    
    	// Print the retrieved floor setting using fmt.Fprintf with the io.Writer.
    	fmt.Fprintf(w, "Retrieved org floor setting: %v\n", response)
    
    	return nil
    }
    

Java

如要執行這段程式碼,請先設定 Java 開發環境,並安裝 Model Armor Java SDK。

  • 查看特定專案的 Model Armor 底限設定。

    
    import com.google.cloud.modelarmor.v1.FloorSetting;
    import com.google.cloud.modelarmor.v1.FloorSettingName;
    import com.google.cloud.modelarmor.v1.GetFloorSettingRequest;
    import com.google.cloud.modelarmor.v1.ModelArmorClient;
    import java.io.IOException;
    
    public class GetProjectFloorSetting {
    
      public static void main(String[] args) throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
    
        getProjectFloorSetting(projectId);
      }
    
      public static FloorSetting getProjectFloorSetting(String projectId) throws IOException {
    
        // Initialize 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()) {
          String name = FloorSettingName.of(projectId, "global").toString();
    
          GetFloorSettingRequest request = GetFloorSettingRequest.newBuilder().setName(name).build();
    
          FloorSetting floorSetting = client.getFloorSetting(request);
          System.out.println("Fetched floor setting for project: " + projectId);
    
          return floorSetting;
        }
      }
    }
  • 查看特定資料夾的 Model Armor 底限設定。

    
    import com.google.cloud.modelarmor.v1.FloorSetting;
    import com.google.cloud.modelarmor.v1.FloorSettingName;
    import com.google.cloud.modelarmor.v1.GetFloorSettingRequest;
    import com.google.cloud.modelarmor.v1.ModelArmorClient;
    import java.io.IOException;
    
    public class GetFolderFloorSetting {
    
      public static void main(String[] args) throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String folderId = "your-folder-id";
    
        getFolderFloorSetting(folderId);
      }
    
      public static FloorSetting getFolderFloorSetting(String folderId) throws IOException {
    
        // Initialize 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()) {
          String name = FloorSettingName.ofFolderLocationName(folderId, "global").toString();
    
          GetFloorSettingRequest request = GetFloorSettingRequest.newBuilder().setName(name).build();
    
          FloorSetting floorSetting = client.getFloorSetting(request);
          System.out.println("Fetched floor setting for folder: " + folderId);
    
          return floorSetting;
        }
      }
    }
  • 查看特定組織的 Model Armor 底限設定。

    
    import com.google.cloud.modelarmor.v1.FloorSetting;
    import com.google.cloud.modelarmor.v1.FloorSettingName;
    import com.google.cloud.modelarmor.v1.GetFloorSettingRequest;
    import com.google.cloud.modelarmor.v1.ModelArmorClient;
    import java.io.IOException;
    
    public class GetOrganizationFloorSetting {
    
      public static void main(String[] args) throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String organizationId = "your-organization-id";
    
        getOrganizationFloorSetting(organizationId);
      }
    
      public static FloorSetting getOrganizationFloorSetting(String organizationId) throws IOException {
    
        // Initialize 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()) {
          String name = FloorSettingName.ofOrganizationLocationName(organizationId, "global")
              .toString();
    
          GetFloorSettingRequest request = GetFloorSettingRequest.newBuilder().setName(name).build();
    
          FloorSetting floorSetting = client.getFloorSetting(request);
          System.out.println("Fetched floor setting for organization: " + organizationId);
    
          return floorSetting;
        }
      }
    }

Node.js

如要執行這段程式碼,請先設定 Node.js 開發環境,並安裝 Model Armor Node.js SDK。

  • 查看特定專案的 Model Armor 底限設定。

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const projectId = 'your-project-id';
    
    const name = `projects/${projectId}/locations/global/floorSetting`;
    
    // Imports the Modelarmor library
    const {ModelArmorClient} = require('@google-cloud/modelarmor').v1;
    
    // Instantiates a client
    const modelarmorClient = new ModelArmorClient();
    
    async function getProjectFloorSettings() {
      // Construct request
      const request = {
        name,
      };
    
      // Run request
      const [response] = await modelarmorClient.getFloorSetting(request);
      return response;
    }
    
    return await getProjectFloorSettings();
  • 查看特定資料夾的 Model Armor 底限設定。

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const folderId = 'your-folder-id';
    
    const name = `folders/${folderId}/locations/global/floorSetting`;
    
    // Imports the Modelarmor library
    const {ModelArmorClient} = require('@google-cloud/modelarmor').v1;
    
    // Instantiates a client
    const modelarmorClient = new ModelArmorClient();
    
    async function getFolderFloorSettings() {
      // Construct request
      const request = {
        name,
      };
    
      const [response] = await modelarmorClient.getFloorSetting(request);
      return response;
    }
    
    return await getFolderFloorSettings();
  • 查看特定組織的 Model Armor 底限設定。

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const organizationId = 'your-organization-id';
    const name = `organizations/${organizationId}/locations/global/floorSetting`;
    
    // Imports the Modelarmor library
    const {ModelArmorClient} = require('@google-cloud/modelarmor').v1;
    
    // Instantiates a client
    const modelarmorClient = new ModelArmorClient();
    
    async function getOrganizationFloorSettings() {
      // Construct request
      const request = {
        name,
      };
    
      // Run request
      const [response] = await modelarmorClient.getFloorSetting(request);
      return response;
    }
    
    return await getOrganizationFloorSettings();

PHP

如要執行這段程式碼,請先設定 PHP 開發環境,並安裝 Model Armor PHP SDK。

  • 查看特定專案的 Model Armor 底限設定。

    use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
    use Google\Cloud\ModelArmor\V1\GetFloorSettingRequest;
    
    /**
     * Gets the floor settings for a given project.
     *
     * @param string $projectId The project Id for which the floor settings is to be retrieved.
     *
     */
    function get_project_floor_settings(string $projectId): void
    {
        $client = new ModelArmorClient();
    
        $floorSettingsName = sprintf('projects/%s/locations/global/floorSetting', $projectId);
    
        $response = $client->getFloorSetting((new GetFloorSettingRequest())->setName($floorSettingsName));
    
        printf("Floor settings retrieved successfully: %s\n", $response->serializeToJsonString());
    }
  • 查看特定資料夾的 Model Armor 底限設定。

    use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
    use Google\Cloud\ModelArmor\V1\GetFloorSettingRequest;
    
    /**
     * Gets the floor settings for a given folder.
     *
     * @param string $folderId The folder Id for which the floor settings is to be retrieved.
     *
     */
    function get_folder_floor_settings(string $folderId): void
    {
        $client = new ModelArmorClient();
    
        $floorSettingsName = sprintf('folders/%s/locations/global/floorSetting', $folderId);
    
        $response = $client->getFloorSetting((new GetFloorSettingRequest())->setName($floorSettingsName));
    
        printf("Floor settings retrieved successfully: %s\n", $response->serializeToJsonString());
    }
  • 查看特定組織的 Model Armor 底限設定。

    use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
    use Google\Cloud\ModelArmor\V1\GetFloorSettingRequest;
    
    /**
     * Gets the floor settings for a given organization.
     *
     * @param string $organizationId The organization Id for which the floor settings is to be retrieved.
     *
     */
    function get_organization_floor_settings(string $organizationId): void
    {
        $client = new ModelArmorClient();
    
        $floorSettingsName = sprintf('organizations/%s/locations/global/floorSetting', $organizationId);
    
        $response = $client->getFloorSetting((new GetFloorSettingRequest())->setName($floorSettingsName));
    
        printf("Floor settings retrieved successfully: %s\n", $response->serializeToJsonString());
    }

Python

如要執行這段程式碼,請先設定 Python 開發環境,並安裝 Model Armor Python SDK。

  • 查看特定專案的 Model Armor 底限設定。

    
    from google.cloud import modelarmor_v1
    
    # Create the Model Armor client.
    client = modelarmor_v1.ModelArmorClient(transport="rest")
    
    # TODO(Developer): Uncomment below variable.
    # project_id = "YOUR_PROJECT_ID"
    
    floor_settings_name = f"projects/{project_id}/locations/global/floorSetting"
    
    # Get the project floor setting.
    response = client.get_floor_setting(
        request=modelarmor_v1.GetFloorSettingRequest(name=floor_settings_name)
    )
    
    # Print the retrieved floor setting.
    print(response)
    
  • 查看特定資料夾的 Model Armor 底限設定。

    
    from google.cloud import modelarmor_v1
    
    # Create the Model Armor client.
    client = modelarmor_v1.ModelArmorClient(transport="rest")
    
    # TODO(Developer): Uncomment below variable.
    # folder_id = "YOUR_FOLDER_ID"
    
    # Prepare folder floor setting path/name
    floor_settings_name = f"folders/{folder_id}/locations/global/floorSetting"
    
    # Get the folder floor setting.
    response = client.get_floor_setting(
        request=modelarmor_v1.GetFloorSettingRequest(name=floor_settings_name)
    )
    
    # Print the retrieved floor setting.
    print(response)
    
  • 查看特定組織的 Model Armor 底限設定。

    
    from google.cloud import modelarmor_v1
    
    # Create the Model Armor client.
    client = modelarmor_v1.ModelArmorClient(transport="rest")
    
    # TODO(Developer): Uncomment below variable.
    # organization_id = "YOUR_ORGANIZATION_ID"
    
    floor_settings_name = (
        f"organizations/{organization_id}/locations/global/floorSetting"
    )
    
    # Get the organization floor setting.
    response = client.get_floor_setting(
        request=modelarmor_v1.GetFloorSettingRequest(name=floor_settings_name)
    )
    
    # Print the retrieved floor setting.
    print(response)
    

更新 Model Armor 底限設定

更新 Model Armor 底限設定,變更範本的最低要求、反映安全政策異動、修正錯誤設定,或解決底限設定之間的衝突。

執行下列指令,更新 Model Armor 底限設定。

控制台

  1. 前往 Google Cloud 控制台的「Model Armor」頁面。

    前往 Model Armor

  2. 確認您查看的是已啟用 Model Armor 的專案。

  3. 在「Model Armor」頁面中,前往「Floor settings」(底限設定) 分頁標籤,然後按一下「Configure floor settings」(設置底限設定)。

  4. 更新必填欄位,然後按一下「儲存底價設定」。

gcloud

   gcloud model-armor floorsettings update --full-uri=<full-uri-of-the-floorsetting>

指令範例:

       gcloud model-armor floorsettings update \
           --malicious-uri-filter-settings-enforcement=ENABLED \
           --pi-and-jailbreak-filter-settings-enforcement=DISABLED \
           --pi-and-jailbreak-filter-settings-confidence-level=LOW_AND_ABOVE \
           --basic-config-filter-enforcement=ENABLED \
           --add-rai-settings-filters='[{"confidenceLevel": "low_and_above", "filterType": "HARASSMENT"}, {"confidenceLevel": "high", "filterType": "SEXUALLY_EXPLICIT"}]' \
           --full-uri='folders/FOLDER_ID/locations/global/floorSetting' \
           --enable-floor-setting-enforcement=true

如要設定樓層,並啟用多語言偵測功能,請執行下列指令:

    gcloud model-armor floorsettings update \
        --full-uri=projects/PROJECT_ID/locations/global/floorSetting \
        --enable-multi-language-detection

更改下列內容:

  • PROJECT_ID:樓層設定的專案 ID。
  • FOLDER_ID:底限設定的資料夾 ID。

REST

  • 更新特定專案的 Model Armor 底限設定。

    curl -X PATCH
      -d '{"filterConfig" :{"piAndJailbreakFilterSettings": { "filterEnforcement": "ENABLED"}, "maliciousUriFilterSettings": { "filterEnforcement": "ENABLED" }, "rai_settings":{"rai_filters":{"filter_type":"DANGEROUS", "confidence_level":"LOW_AND_ABOVE" }, \
      "rai_filters":{"filter_type":"HATE_SPEECH", "confidence_level":"LOW_AND_ABOVE" }, "rai_filters":{"filter_type":"HARASSMENT", "confidence_level":"LOW_AND_ABOVE" }, "rai_filters":{"filter_type":"SEXUALLY_EXPLICIT", "confidence_level":"LOW_AND_ABOVE" }}},"enableFloorSettingEnforcement":"true"}' \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $(gcloud auth print-access-token) \
      "https://modelarmor.googleapis.com/v1/projects/PROJECT_ID/locations/global/floorSetting"
  • 更新指定資料夾的 Model Armor 底限設定。

    curl -X PATCH \
      -d '{"filterConfig" :{"piAndJailbreakFilterSettings": { "filterEnforcement": "ENABLED"}, "maliciousUriFilterSettings": {"filterEnforcement": "ENABLED" }},"enableFloorSettingEnforcement":"true"}' \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://modelarmor.googleapis.com/v1/folders/FOLDER_ID/locations/global/floorSetting"
  • 更新特定組織的 Model Armor 底限設定。

    curl -X PATCH \
      -d '{"filterConfig" :{"piAndJailbreakFilterSettings": { "filterEnforcement": "ENABLED"}, "maliciousUriFilterSettings": {
          "filterEnforcement": "ENABLED" }},"enableFloorSettingEnforcement":"true"}' \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
          "https://modelarmor.googleapis.com/v1/organizations/ORGANIZATION_ID/locations/global/floorSetting"

更改下列內容:

  • PROJECT_ID:樓層設定的專案 ID。
  • FOLDER_ID:底限設定的資料夾 ID。
  • ORGANIZATION_ID:底限設定的組織 ID。

更新指令會傳回下列回應:

{
"name": "projects/PROJECT_ID/locations/global/floorSetting",
"updateTime": "2024-12-19T15:36:21.318191Z",
"filterConfig": {
  "piAndJailbreakFilterSettings": {
    "filterEnforcement": "ENABLED"
  },
"maliciousUriFilterSettings": {
  "filterEnforcement": "ENABLED"
 }
}
}

C#

如要執行這段程式碼,請先設定 C# 開發環境,並安裝 Model Armor C# SDK。

  • 更新特定專案的 Model Armor 底限設定。

    using Google.Cloud.ModelArmor.V1;
    using System;
    
    public class UpdateProjectFloorSettings
    {
        public FloorSetting UpdateProjectFloorSetting(string projectId)
        {
            // Create the client
            ModelArmorClient client = ModelArmorClient.Create();
    
            // Construct the floor settings name
            string floorSettingsName = $"projects/{projectId}/locations/global/floorSetting";
    
            // Build the floor settings 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
            var raiFilter = new RaiFilterSettings.Types.RaiFilter
            {
                FilterType = RaiFilterType.HateSpeech,
                ConfidenceLevel = DetectionConfidenceLevel.High,
            };
    
            var raiFilterSettings = new RaiFilterSettings();
            raiFilterSettings.RaiFilters.Add(raiFilter);
    
            var filterConfig = new FilterConfig { RaiSettings = raiFilterSettings };
    
            var floorSetting = new FloorSetting
            {
                Name = floorSettingsName,
                FilterConfig = filterConfig,
                EnableFloorSettingEnforcement = true,
            };
    
            // Create the update request
            var updateRequest = new UpdateFloorSettingRequest { FloorSetting = floorSetting };
    
            // Update the floor settings
            FloorSetting response = client.UpdateFloorSetting(updateRequest);
    
            Console.WriteLine($"Floor setting updated: {response.Name}");
    
            return response;
        }
    }
  • 更新指定資料夾的 Model Armor 底限設定。

    using Google.Cloud.ModelArmor.V1;
    using System;
    
    public class UpdateFolderFloorSettings
    {
        public FloorSetting UpdateFolderFloorSetting(string folderId)
        {
            // Create the client
            ModelArmorClient client = ModelArmorClient.Create();
    
            // Construct the floor settings name
            string floorSettingsName = $"folders/{folderId}/locations/global/floorSetting";
    
            // Build the floor settings 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
            var raiFilter = new RaiFilterSettings.Types.RaiFilter
            {
                FilterType = RaiFilterType.HateSpeech,
                ConfidenceLevel = DetectionConfidenceLevel.High,
            };
    
            var raiFilterSettings = new RaiFilterSettings();
            raiFilterSettings.RaiFilters.Add(raiFilter);
    
            var filterConfig = new FilterConfig { RaiSettings = raiFilterSettings };
    
            var floorSetting = new FloorSetting
            {
                Name = floorSettingsName,
                FilterConfig = filterConfig,
                EnableFloorSettingEnforcement = true,
            };
    
            // Create the update request
            var updateRequest = new UpdateFloorSettingRequest { FloorSetting = floorSetting };
    
            // Update the floor settings
            FloorSetting response = client.UpdateFloorSetting(updateRequest);
    
            Console.WriteLine($"Floor setting updated: {response.Name}");
    
            return response;
        }
    }
  • 更新特定組織的 Model Armor 底限設定。

    using Google.Cloud.ModelArmor.V1;
    using System;
    
    public class UpdateOrganizationFloorSettings
    {
        public FloorSetting UpdateOrganizationFloorSetting(string organizationId)
        {
            // Create the client
            ModelArmorClient client = ModelArmorClient.Create();
    
            // Construct the floor settings name
            string floorSettingsName = $"organizations/{organizationId}/locations/global/floorSetting";
    
            // Build the floor settings 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
            var raiFilter = new RaiFilterSettings.Types.RaiFilter
            {
                FilterType = RaiFilterType.HateSpeech,
                ConfidenceLevel = DetectionConfidenceLevel.High,
            };
    
            var raiFilterSettings = new RaiFilterSettings();
            raiFilterSettings.RaiFilters.Add(raiFilter);
    
            var filterConfig = new FilterConfig { RaiSettings = raiFilterSettings };
    
            var floorSetting = new FloorSetting
            {
                Name = floorSettingsName,
                FilterConfig = filterConfig,
                EnableFloorSettingEnforcement = true,
            };
    
            // Create the update request
            var updateRequest = new UpdateFloorSettingRequest { FloorSetting = floorSetting };
    
            // Update the floor settings
            FloorSetting response = client.UpdateFloorSetting(updateRequest);
    
            Console.WriteLine($"Floor setting updated: {response.Name}");
    
            return response;
        }
    }

Go

如要執行這段程式碼,請先設定 Go 開發環境,並安裝 Model Armor Go SDK。

  • 更新特定專案的 Model Armor 底限設定。

    
    import (
    	"context"
    	"fmt"
    	"io"
    
    	modelarmor "cloud.google.com/go/modelarmor/apiv1"
    	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
    )
    
    // updateProjectFloorSettings updates the floor settings of a project.
    //
    // This method updates the floor settings of a project.
    //
    // w io.Writer: The writer to use for logging.
    // projectID string: The ID of the project.
    func updateProjectFloorSettings(w io.Writer, projectID string) error {
    	ctx := context.Background()
    
    	// Create the Model Armor client.
    	client, err := modelarmor.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("failed to create client: %w", err)
    	}
    	defer client.Close()
    
    	// Prepare project floor setting path/name
    	floorSettingsName := fmt.Sprintf("projects/%s/locations/global/floorSetting", projectID)
    
    	// Update the project floor setting
    	// 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)
    	enableEnforcement := true
    	req := &modelarmorpb.UpdateFloorSettingRequest{
    		FloorSetting: &modelarmorpb.FloorSetting{
    			Name: floorSettingsName,
    			FilterConfig: &modelarmorpb.FilterConfig{
    				RaiSettings: &modelarmorpb.RaiFilterSettings{
    					RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{
    						{
    							FilterType:      modelarmorpb.RaiFilterType_HATE_SPEECH,
    							ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH,
    						},
    					},
    				},
    			},
    			EnableFloorSettingEnforcement: &enableEnforcement,
    		},
    	}
    
    	response, err := client.UpdateFloorSetting(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to update floor setting: %w", err)
    	}
    
    	// Print the updated config
    	fmt.Fprintf(w, "Updated project floor setting: %+v\n", response)
    
    	return nil
    }
    
  • 更新指定資料夾的 Model Armor 底限設定。

    
    import (
    	"context"
    	"fmt"
    	"io"
    
    	modelarmor "cloud.google.com/go/modelarmor/apiv1"
    	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
    )
    
    // updateFolderFloorSettings updates floor settings of a folder.
    //
    // This method updates the floor settings of a folder.
    //
    // w io.Writer: The writer to use for logging.
    // folderID string: The ID of the folder.
    func updateFolderFloorSettings(w io.Writer, folderID string) error {
    	ctx := context.Background()
    
    	// Create the Model Armor client.
    	client, err := modelarmor.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("failed to create client: %w", err)
    	}
    	defer client.Close()
    
    	// Prepare folder floor settings path/name
    	floorSettingsName := fmt.Sprintf("folders/%s/locations/global/floorSetting", folderID)
    
    	// Prepare the floor setting update
    	enableEnforcement := true
    	floorSetting := &modelarmorpb.FloorSetting{
    		Name: floorSettingsName,
    		FilterConfig: &modelarmorpb.FilterConfig{
    			RaiSettings: &modelarmorpb.RaiFilterSettings{
    				RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{
    					{
    						FilterType:      modelarmorpb.RaiFilterType_HATE_SPEECH,
    						ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH,
    					},
    				},
    			},
    		},
    		EnableFloorSettingEnforcement: &enableEnforcement,
    	}
    
    	// Prepare request for updating the floor setting.
    	req := &modelarmorpb.UpdateFloorSettingRequest{
    		FloorSetting: floorSetting,
    	}
    
    	// Update the floor setting.
    	response, err := client.UpdateFloorSetting(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to update floor setting: %w", err)
    	}
    
    	// Print the updated config
    	fmt.Fprintf(w, "Updated folder floor setting: %v\n", response)
    
    	return nil
    
    }
    
  • 更新特定組織的 Model Armor 底限設定。

    
    import (
    	"context"
    	"fmt"
    	"io"
    
    	modelarmor "cloud.google.com/go/modelarmor/apiv1"
    	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
    )
    
    // updateOrganizationFloorSettings updates floor settings of an organization.
    //
    // This method updates the floor settings of an organization.
    //
    // w io.Writer: The writer to use for logging.
    // organizationID string: The ID of the organization.
    func updateOrganizationFloorSettings(w io.Writer, organizationID string) error {
    	ctx := context.Background()
    
    	// Create the Model Armor client.
    	client, err := modelarmor.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("failed to create client: %w", err)
    	}
    	defer client.Close()
    
    	// Prepare organization floor setting path/name
    	floorSettingsName := fmt.Sprintf("organizations/%s/locations/global/floorSetting", organizationID)
    
    	// Update the organization floor setting
    	// 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)
    	enableEnforcement := true
    	req := &modelarmorpb.UpdateFloorSettingRequest{
    		FloorSetting: &modelarmorpb.FloorSetting{
    			Name: floorSettingsName,
    			FilterConfig: &modelarmorpb.FilterConfig{
    				RaiSettings: &modelarmorpb.RaiFilterSettings{
    					RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{
    						{
    							FilterType:      modelarmorpb.RaiFilterType_HATE_SPEECH,
    							ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH,
    						},
    					},
    				},
    			},
    			EnableFloorSettingEnforcement: &enableEnforcement,
    		},
    	}
    
    	response, err := client.UpdateFloorSetting(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to update floor setting: %w", err)
    	}
    
    	// Print the updated config
    	fmt.Fprintf(w, "Updated org floor setting: %+v\n", response)
    

Java

如要執行這段程式碼,請先設定 Java 開發環境,並安裝 Model Armor Java SDK。

Node.js

如要執行這段程式碼,請先設定 Node.js 開發環境,並安裝 Model Armor Node.js SDK。

  • 更新特定專案的 Model Armor 底限設定。

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const projectId = 'your-project-id';
    
    const modelarmor = require('@google-cloud/modelarmor');
    const {ModelArmorClient} = modelarmor.v1;
    const {protos} = modelarmor;
    
    // Initiate client
    const client = new ModelArmorClient();
    
    async function updateProjectFloorSettings() {
      const floorSettingsName = `projects/${projectId}/locations/global/floorSetting`;
    
      // Build the floor settings 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 floorSetting = {
        name: floorSettingsName,
        filterConfig: {
          raiSettings: {
            raiFilters: [
              {
                filterType:
                  protos.google.cloud.modelarmor.v1.RaiFilterType.HARASSMENT,
                confidenceLevel:
                  protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                    .LOW_AND_ABOVE,
              },
              {
                filterType:
                  protos.google.cloud.modelarmor.v1.RaiFilterType
                    .SEXUALLY_EXPLICIT,
                confidenceLevel:
                  protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                    .LOW_AND_ABOVE,
              },
            ],
          },
        },
        enableFloorSettingEnforcement: true,
      };
    
      const request = {
        floorSetting: floorSetting,
      };
    
      const [response] = await client.updateFloorSetting(request);
      return response;
    }
    
    return await updateProjectFloorSettings();
  • 更新指定資料夾的 Model Armor 底限設定。

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const folderId = 'your-folder-id';
    
    // 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();
    
    async function updateFolderFloorSettings() {
      const floorSettingsName = `folders/${folderId}/locations/global/floorSetting`;
    
      // Build the floor settings 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 floorSetting = {
        name: floorSettingsName,
        filterConfig: {
          raiSettings: {
            raiFilters: [
              {
                filterType:
                  protos.google.cloud.modelarmor.v1.RaiFilterType.HARASSMENT,
                confidenceLevel:
                  protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                    .LOW_AND_ABOVE,
              },
              {
                filterType:
                  protos.google.cloud.modelarmor.v1.RaiFilterType
                    .SEXUALLY_EXPLICIT,
                confidenceLevel:
                  protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                    .LOW_AND_ABOVE,
              },
            ],
          },
        },
        enableFloorSettingEnforcement: true,
      };
    
      const request = {
        floorSetting: floorSetting,
      };
    
      const [response] = await client.updateFloorSetting(request);
      return response;
    }
    
    return await updateFolderFloorSettings();
  • 更新特定組織的 Model Armor 底限設定。

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const organizationId = 'your-organization-id';
    
    const modelarmor = require('@google-cloud/modelarmor');
    const {ModelArmorClient} = modelarmor.v1;
    const {protos} = modelarmor;
    
    const client = new ModelArmorClient();
    
    async function updateOrganizationFloorSettings() {
      const floorSettingsName = `organizations/${organizationId}/locations/global/floorSetting`;
    
      // Build the floor settings 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 floorSetting = {
        name: floorSettingsName,
        filterConfig: {
          raiSettings: {
            raiFilters: [
              {
                filterType:
                  protos.google.cloud.modelarmor.v1.RaiFilterType.HARASSMENT,
                confidenceLevel:
                  protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                    .LOW_AND_ABOVE,
              },
              {
                filterType:
                  protos.google.cloud.modelarmor.v1.RaiFilterType
                    .SEXUALLY_EXPLICIT,
                confidenceLevel:
                  protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                    .LOW_AND_ABOVE,
              },
            ],
          },
        },
        enableFloorSettingEnforcement: true,
      };
    
      const request = {
        floorSetting: floorSetting,
      };
    
      const [response] = await client.updateFloorSetting(request);
      return response;
    }
    
    return await updateOrganizationFloorSettings();

PHP

如要執行這段程式碼,請先設定 PHP 開發環境,並安裝 Model Armor PHP SDK。

  • 更新特定專案的 Model Armor 底限設定。

    use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
    use Google\Cloud\ModelArmor\V1\RaiFilterType;
    use Google\Cloud\ModelArmor\V1\DetectionConfidenceLevel;
    use Google\Cloud\ModelArmor\V1\UpdateFloorSettingRequest;
    use Google\Cloud\ModelArmor\V1\FilterConfig;
    use Google\Cloud\ModelArmor\V1\FloorSetting;
    use Google\Cloud\ModelArmor\V1\RaiFilterSettings;
    use Google\Cloud\ModelArmor\V1\RaiFilterSettings\RaiFilter;
    
    /**
     * Updates the floor settings for a given project.
     *
     * @param string $projectId The project Id for which the floor settings is to be updated.
     *
     */
    function update_project_floor_settings(string $projectId): void
    {
        $client = new ModelArmorClient();
    
        $floorSettingsName = sprintf('projects/%s/locations/global/floorSetting', $projectId);
    
        // Build the floor settings 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
    
        $raiFilterSetting = (new RaiFilterSettings())
            ->setRaiFilters([
                (new RaiFilter())
                    ->setFilterType(RaiFilterType::HATE_SPEECH)
                    ->setConfidenceLevel(DetectionConfidenceLevel::HIGH)
            ]);
    
        $filterConfig = (new FilterConfig())->setRaiSettings($raiFilterSetting);
        $floorSetting = (new FloorSetting())
            ->setName($floorSettingsName)
            ->setFilterConfig($filterConfig)
            ->setEnableFloorSettingEnforcement(true);
    
        $updateRequest = (new UpdateFloorSettingRequest())->setFloorSetting($floorSetting);
    
        $response = $client->updateFloorSetting($updateRequest);
    
        printf("Floor setting updated: %s\n", $response->getName());
    }
  • 更新指定資料夾的 Model Armor 底限設定。

    use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
    use Google\Cloud\ModelArmor\V1\RaiFilterType;
    use Google\Cloud\ModelArmor\V1\DetectionConfidenceLevel;
    use Google\Cloud\ModelArmor\V1\UpdateFloorSettingRequest;
    use Google\Cloud\ModelArmor\V1\FilterConfig;
    use Google\Cloud\ModelArmor\V1\FloorSetting;
    use Google\Cloud\ModelArmor\V1\RaiFilterSettings;
    use Google\Cloud\ModelArmor\V1\RaiFilterSettings\RaiFilter;
    
    /**
     * Updates the floor settings for a given folder.
     *
     * @param string $folderId The folder Id for which the floor settings is to be updated.
     *
     */
    function update_folder_floor_settings(string $folderId): void
    {
        $client = new ModelArmorClient();
    
        $floorSettingsName = sprintf('folders/%s/locations/global/floorSetting', $folderId);
    
        // Build the floor settings 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
    
        $raiFilterSetting = (new RaiFilterSettings())
            ->setRaiFilters([
                (new RaiFilter())
                    ->setFilterType(RaiFilterType::HATE_SPEECH)
                    ->setConfidenceLevel(DetectionConfidenceLevel::HIGH)
            ]);
    
        $filterConfig = (new FilterConfig())->setRaiSettings($raiFilterSetting);
        $floorSetting = (new FloorSetting())
            ->setName($floorSettingsName)
            ->setFilterConfig($filterConfig)
            ->setEnableFloorSettingEnforcement(true);
    
        $updateRequest = (new UpdateFloorSettingRequest())->setFloorSetting($floorSetting);
    
        $response = $client->updateFloorSetting($updateRequest);
    
        printf("Floor setting updated: %s\n", $response->getName());
    }
  • 更新特定組織的 Model Armor 底限設定。

    use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
    use Google\Cloud\ModelArmor\V1\RaiFilterType;
    use Google\Cloud\ModelArmor\V1\DetectionConfidenceLevel;
    use Google\Cloud\ModelArmor\V1\UpdateFloorSettingRequest;
    use Google\Cloud\ModelArmor\V1\FilterConfig;
    use Google\Cloud\ModelArmor\V1\FloorSetting;
    use Google\Cloud\ModelArmor\V1\RaiFilterSettings;
    use Google\Cloud\ModelArmor\V1\RaiFilterSettings\RaiFilter;
    
    /**
     * Updates the floor settings for a given organization.
     *
     * @param string $organizationId The organization Id for which the floor settings is to be updated.
     *
     */
    function update_organization_floor_settings(string $organizationId)
    {
        $client = new ModelArmorClient();
    
        $floorSettingsName = sprintf('organizations/%s/locations/global/floorSetting', $organizationId);
    
        // Build the floor settings 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
    
        $raiFilterSetting = (new RaiFilterSettings())
            ->setRaiFilters([
                (new RaiFilter())
                    ->setFilterType(RaiFilterType::HATE_SPEECH)
                    ->setConfidenceLevel(DetectionConfidenceLevel::HIGH)
            ]);
    
        $filterConfig = (new FilterConfig())->setRaiSettings($raiFilterSetting);
        $floorSetting = (new FloorSetting())
            ->setName($floorSettingsName)
            ->setFilterConfig($filterConfig)
            ->setEnableFloorSettingEnforcement(true);
    
        $updateRequest = (new UpdateFloorSettingRequest())->setFloorSetting($floorSetting);
    
        $response = $client->updateFloorSetting($updateRequest);
    
        printf("Floor setting updated: %s\n", $response->getName());
    }

Python

如要執行這段程式碼,請先設定 Python 開發環境,並安裝 Model Armor Python SDK。

查看底限設定違規事項的發現項目

每項 Model Armor 發現項目都會指出違反底限設定的情況。如果 Model Armor 範本未達資源階層底限設定定義的最低安全標準,就會發生違規情況。底限設定會定義範本的最低要求。

如果發生下列任何違反底限設定的情況,系統就會產生發現項目:

  • 在設定底限前,先建立限制較少的範本。
  • 範本缺少必要篩選器。
  • 範本未達篩選器的最低信賴水準。

系統偵測到違規事項時,會在 Security Command Center 中產生高嚴重性的發現項目 (如果您使用 Security Command Center 的 Premium 或 Enterprise 服務級別)。發現項目會指出違反的底限設定、不符合規定的範本,以及違規事項的詳細資料。

以下範例顯示發現項目的 sourceProperties 欄位。這項違規與惡意 URI 篩選器有關,原因是 maliciousUriFilterSettings 的範本設定為「停用」,但基準設定要求為「啟用」。

{
  "filterConfig": {
    "raiSettings": {
      "raiFilters": [
        {
          "filterType": "HATE_SPEECH",
          "confidenceLevel": {
            "floorSettings": "LOW_AND_ABOVE",
            "template": "MEDIUM_AND_ABOVE"
          }
        },
        {
          "filterType": "HARASSMENT",
          "confidenceLevel": {
            "floorSettings": "MEDIUM_AND_ABOVE",
            "template": "HIGH"
          }
        }
      ]
    },
    "piAndJailbreakFilterSettings": {
      "confidenceLevel": {
        "floorSettings": "LOW_AND_ABOVE",
        "template": "HIGH"
      }
    },
    "maliciousUriFilterSettings": {
      "floorSettings": "ENABLED",
      "template": "DISABLED"
    }
  }
}

後續步驟