本頁面詳細說明如何清除提示詞和回覆。Model Armor 提供一系列篩選器,可保護您的 AI 應用程式。Model Armor 會根據設定的篩選信心水準檢查提示詞和回覆。
事前準備
按照「建立範本」一文中的操作說明建立範本。
取得必要權限
如要取得清除提示和回應所需的權限,請要求管理員授予您 Model Armor 的下列 IAM 角色:
- Model Armor 使用者 (
roles/modelarmor.user) - Model Armor 檢視器 (
roles/modelarmor.viewer)
如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。
在包含 Sensitive Data Protection 範本的專案中,將 DLP 使用者角色 (roles/dlp.user) 和 DLP 讀取者角色 (roles/dlp.reader) 授予在「建立範本」的「進階 Sensitive Data Protection」步驟中建立的服務代理程式。如果 Sensitive Data Protection 範本與 Model Armor 範本位於同一個專案,請略過這個步驟。
gcloud projects add-iam-policy-binding SDP_PROJECT_ID \ --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-modelarmor.iam.gserviceaccount.com --role=roles/dlp.user gcloud projects add-iam-policy-binding SDP_PROJECT_ID \ --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-modelarmor.iam.gserviceaccount.com --role=roles/dlp.reader
更改下列內容:
SDP_PROJECT_ID:進階 Sensitive Data Protection 範本所屬的專案 ID。PROJECT_NUMBER:範本所屬專案的編號。
啟用 API
您必須先啟用 Model Armor API,才能使用 Model Armor。
控制台
gcloud
開始前,請使用 Google Cloud CLI 搭配 Model Armor API 執行下列步驟:
在 Google Cloud 控制台中啟用 Cloud Shell。
Google Cloud 主控台底部會開啟一個 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已針對您目前的專案設定好相關值。工作階段可能需要幾秒鐘的時間才能完成初始化。
使用 gcloud CLI 設定 API 端點覆寫
如果您使用 gcloud CLI 啟用 Model Armor API,才需要執行這個步驟。您必須手動設定 API 端點覆寫,確保 gcloud CLI 正確將要求轉送至 Model Armor 服務。
執行下列指令,為 Model Armor 服務設定 API 端點。
gcloud config set api_endpoint_overrides/modelarmor "https://modelarmor.LOCATION.rep.googleapis.com/"
將 LOCATION 替換為要使用 Model Armor 的區域。
清理提示詞
清除提示,防止惡意輸入,並確保傳送至 LLM 的提示安全無虞且適當。
文字提示
Model Armor 會分析文字並套用不同篩選器,找出並防範潛在威脅,藉此清除文字提示。
REST
使用下列指令,在 Model Armor 中清除文字提示。
curl -X POST \
-d '{"userPromptData":{"text":"[UNSAFE TEXT]"}}' \
-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:sanitizeUserPrompt"
更改下列內容:
PROJECT_ID:範本的專案 ID。LOCATION:範本的位置。TEMPLATE_ID:範本 ID。
這會產生下列回應。請注意,MATCH_FOUND 屬於「危險」類別。
{ "sanitizationResult": { "filterMatchState": "MATCH_FOUND", "invocationResult": "SUCCESS", "filterResults": { "csam": { "csamFilterFilterResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "NO_MATCH_FOUND" } }, "malicious_uris": { "maliciousUriFilterResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "NO_MATCH_FOUND" } }, "rai": { "raiFilterResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "MATCH_FOUND", "raiFilterTypeResults": { "sexually_explicit": { "matchState": "NO_MATCH_FOUND" }, "hate_speech": { "matchState": "NO_MATCH_FOUND" }, "harassment": { "matchState": "NO_MATCH_FOUND" }, "dangerous": { "matchState": "MATCH_FOUND" } } } }, "pi_and_jailbreak": { "piAndJailbreakFilterResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "MATCH_FOUND" } }, "sdp": { "sdpFilterResult": { "inspectResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "NO_MATCH_FOUND" } } } } } }
Go
如要執行這段程式碼,請先設定 Go 開發環境,然後安裝 Model Armor Go SDK。
C#
如要執行這段程式碼,請先設定 C# 開發環境,然後安裝 Model Armor C# SDK。
Java
如要執行這段程式碼,請先設定 Java 開發環境,然後安裝 Model Armor Java SDK。
Node.js
如要執行這段程式碼,請先設定 Node.js 開發環境, 然後安裝 Model Armor Node.js SDK。
PHP
如要執行這段程式碼,請先設定 PHP 開發環境,然後安裝 Model Armor PHP SDK。
Python
如要執行這段程式碼,請設定 Python 開發環境,並安裝 Model Armor Python SDK。
這會產生下列回應。
sanitization_result { filter_match_state: MATCH_FOUND filter_results { key: "rai" value { rai_filter_result { execution_state: EXECUTION_SUCCESS match_state: MATCH_FOUND rai_filter_type_results { key: "dangerous" value { confidence_level: HIGH match_state: MATCH_FOUND } } } } } filter_results { key: "pi_and_jailbreak" value { pi_and_jailbreak_filter_result { execution_state: EXECUTION_SUCCESS match_state: MATCH_FOUND confidence_level: HIGH } } } filter_results { key: "malicious_uris" value { malicious_uri_filter_result { execution_state: EXECUTION_SUCCESS match_state: NO_MATCH_FOUND } } } filter_results { key: "csam" value { csam_filter_filter_result { execution_state: EXECUTION_SUCCESS match_state: NO_MATCH_FOUND } } } invocation_result: SUCCESS }
在對話式 AI 中清除提示的最佳做法
在對話式 AI 應用程式中使用 Model Armor 清理輸入內容時,請務必瞭解 SanitizeUserPrompt 方法的 userPromptData 欄位應包含哪些內容。
分別清除每項使用者輸入內容:針對使用者傳送的每則新訊息呼叫
SanitizeUserPromptAPI。這樣可確保系統在 LLM 處理每項使用者輸入內容前,都會先分析潛在威脅。userPromptData欄位只能包含目前對話中,使用者傳送的最新訊息內容。請勿加入對話記錄:避免將整個對話記錄串連至
userPromptData欄位。不要加入系統提示:從「
userPromptData」欄位排除系統提示。Model Armor 只會偵測使用者提供的輸入內容中的威脅。
啟用多語言偵測功能,清除文字提示
如要針對個別要求啟用多語言偵測功能,請為每項要求將 enableMultiLanguageDetection 旗標設為 true。如要取得更準確的結果,可以指定原文語言。
- 如未指定原文語言,Model Armor 會自動偵測語言,提供多語言支援。
- 如果您指定原文語言,Model Armor 會使用該語言評估文字提示,不會自動偵測語言。
使用下列指令,在 Model Armor 中清除文字提示,並在要求層級啟用多語言偵測功能。
curl -X POST \ -d '{"userPromptData":{"text":"[UNSAFE TEXT]"}, "multiLanguageDetectionMetadata": { "enableMultiLanguageDetection": true , "sourceLanguage": "jp"}}' \ -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:sanitizeUserPrompt"
更改下列內容:
PROJECT_ID:範本的專案 ID。LOCATION:範本的位置。TEMPLATE_ID:範本 ID。
清理串流文字提示
Model Armor 的串流方法會即時清除提示和回覆中的敏感資訊,並以文字串流形式提供,不必等待完整內容。這項功能特別適合處理大型文字酬載的應用程式,或需要與 LLM 進行低延遲互動的應用程式。
請使用下列方法啟用串流功能:
- StreamSanitizeUserPrompt:串流處理並清除使用者提供的文字。
- StreamSanitizeModelResponse:串流及清除 LLM 生成的文字。
Model Armor 提供下列串流模式:
- 緩衝模式:收集所有串流區塊,並將其視為單一單元一起處理。
- 即時模式:收到每個區塊時,系統會個別處理,並提供持續的回饋。
使用即時串流模式時,Model Armor 支援無限量的權杖,但緩衝模式會受到權杖限制。
串流的運作方式如下:
- 分塊輸入:應用程式會將文字分成較小的片段 (分塊),再傳送至 Model Armor,而不是一次傳送整個文字主體。
- 即時處理:Model Armor 會在這些區塊抵達時處理,並套用範本中設定的安全篩選機制。
- 持續回饋:視模式 (即時模式或緩衝模式) 而定,Model Armor 會在處理每個區塊後傳回結果,或在收到所有區塊後傳回結果。
使用下列指令清除串流文字提示。
Go
如要執行這段程式碼,請先設定 Go 開發環境,然後安裝 Model Armor Go SDK。
package main
import (
"context"
"fmt"
"io"
"log"
modelarmor "cloud.google.com/go/modelarmor/apiv1beta"
modelarmorpb "cloud.google.com/go/modelarmor/apiv1beta/modelarmorpb"
"google.golang.org/api/option"
"google.golang.org/protobuf/encoding/protojson"
)
func main() {
ctx := context.Background()
// Define variables for project, location, and template ID
projectID := "your-project-id"
location := "your-location-id"
templateID := "your-template-id"
// 1. Create the client with the custom regional endpoint.
opts := option.WithEndpoint("modelarmor.us-central1.rep.googleapis.com:443")
c, err := modelarmor.NewClient(ctx, opts)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
defer c.Close()
// 2. Start the StreamSanitizeUserPrompt bidirectional stream.
stream, err := c.StreamSanitizeUserPrompt(ctx)
if err != nil {
log.Fatalf("failed to initialize stream: %v", err)
}
// 3. Use a goroutine to send the requests.
go func() {
// Define the user prompt data
userPromptData := &modelarmorpb.DataItem{
DataItem: &modelarmorpb.DataItem_Text{
// Specify the user prompt.
Text: "This is a sample user prompt",
},
}
// Create the request object
req := &modelarmorpb.SanitizeUserPromptRequest{ // Use fmt.Sprintf to construct the resource name
Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, location, templateID),
UserPromptData: userPromptData,
}
reqs := []*modelarmorpb.SanitizeUserPromptRequest{req}
for _, r := range reqs {
if err := stream.Send(r); err != nil {
log.Printf("Failed to send request: %v", err)
return
}
}
stream.CloseSend()
}()
// 4. Iterate over the responses from the stream.
for {
resp, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
log.Fatalf("failed to receive response: %v", err)
}
// Marshal the proto message to a formatted JSON string
b, _ := protojson.MarshalOptions{
Multiline: true,
Indent: " ",
}.Marshal(resp)
// Results can be consumed or assigned here in production workflows
}
}
Java
如要執行這段程式碼,請先設定 Java 開發環境,然後安裝 Model Armor Java SDK。
package com.example.armor;
import com.google.api.gax.rpc.BidiStream;
import com.google.cloud.modelarmor.v1beta.DataItem;
import com.google.cloud.modelarmor.v1beta.ModelArmorClient;
import com.google.cloud.modelarmor.v1beta.ModelArmorSettings;
import com.google.cloud.modelarmor.v1beta.SanitizationResult;
import com.google.cloud.modelarmor.v1beta.SanitizeUserPromptRequest;
import com.google.cloud.modelarmor.v1beta.SanitizeUserPromptResponse;
import com.google.cloud.modelarmor.v1beta.StreamingMode;
import com.google.cloud.modelarmor.v1beta.TemplateName;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class StreamSanitizeUserPrompt {
public static void main(String[] args) {
try {
streamSanitizeUserPromptExample();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void streamSanitizeUserPromptExample()
throws IOException, InterruptedException, ExecutionException {
// 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";
String customApiEndpoint = "modelarmor.us-central1.rep.googleapis.com:443";
List<String> promptChunks = Arrays.asList(
"This is the first part of the user prompt. ",
"This is the second part. ",
"And this is the final part."
);
// ModelArmorSettings is now properly imported and recognized here
try (
ModelArmorClient modelArmorClient = ModelArmorClient.create(
ModelArmorSettings.newBuilder()
.setEndpoint(customApiEndpoint)
.build()
)
) {
BidiStream<SanitizeUserPromptRequest, SanitizeUserPromptResponse> stream =
modelArmorClient.streamSanitizeUserPromptCallable().call();
String resourceName = TemplateName.of(projectId, locationId, templateId).toString();
// --- Send First Request ---
SanitizeUserPromptRequest firstRequest = SanitizeUserPromptRequest.newBuilder()
.setName(resourceName)
.setUserPromptData(DataItem.newBuilder().setText(promptChunks.get(0)))
.setStreamingMode(StreamingMode.STREAMING_MODE_BUFFERED)
.build();
stream.send(firstRequest);
// --- Send Subsequent Requests ---
for (int i = 1; i < promptChunks.size(); i++) {
SanitizeUserPromptRequest subsequentRequest = SanitizeUserPromptRequest.newBuilder()
.setName(resourceName)
.setUserPromptData(DataItem.newBuilder().setText(promptChunks.get(i)))
.build();
stream.send(subsequentRequest);
}
stream.closeSend();
// --- Receive Responses ---
for (SanitizeUserPromptResponse response : stream) {
if (response.hasSanitizationResult()) {
SanitizationResult result = response.getSanitizationResult();
// Results can be consumed or assigned here in production workflows
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Python
如要執行這段程式碼,請設定 Python 開發環境,並安裝 Model Armor Python SDK。
from google.cloud import modelarmor_v1beta
def sample_stream_sanitize_user_prompt():
# Create a client
client = modelarmor_v1beta.ModelArmorClient(transport="grpc", client_options = {"api_endpoint" : "modelarmor.us-central1.rep.googleapis.com"})
# Specify the Google Project ID.
project_id = "your-project-id"
# Specify the location ID. For example, us-central1.
location = "your-location-id"
# Specify the template ID.
template_id = "your-template-id"
template_name = client.template_path(project_id, location, template_id)
# Initialize request argument(s)
user_prompt_data = modelarmor_v1beta.DataItem()
# Specify the user prompt.
user_prompt_data.text = "This is a sample user prompt"
request = modelarmor_v1beta.SanitizeUserPromptRequest(
name=template_name,
user_prompt_data=user_prompt_data,
)
# This method expects an iterator which contains
# 'modelarmor_v1beta.SanitizeUserPromptRequest' objects
# Here we create a generator that yields a single `request` for
# demonstrative purposes.
requests = [request]
def request_generator():
for request in requests:
yield request
# Make the request
stream = client.stream_sanitize_user_prompt(requests=request_generator())
# Handle the response
for response in stream:
# Results can be consumed or assigned here in production workflows
sample_stream_sanitize_user_prompt()
在清除串流文字提示或回應時,請注意下列事項:
- 為有效清除內容,請確保個別區塊不超過權杖限制。
- Model Armor 串流方法僅支援文字輸入,不支援圖片和檔案等附件。
- 使用關聯性 ID 追蹤特定要求的串流清除記錄。
- Model Armor 串流方法不支援 Sensitive Data Protection 去識別。
以檔案為基礎的提示
如要清除儲存在檔案中的提示,請以 base64 格式提供檔案內容。Model Armor 不會自動偵測檔案類型,您必須明確設定 byteDataType 欄位,指出檔案格式。如果缺少或未指定這個欄位,要求就會失敗。byteDataType 可能的值為 PLAINTEXT_UTF8、PDF、WORD_DOCUMENT、EXCEL_DOCUMENT、POWERPOINT_DOCUMENT、TXT 和 CSV。系統不支援對檔案型提示進行 Sensitive Data Protection 去識別化。
REST
curl -X POST \ -d "$(jq -n \ --arg data "$(base64 -w 0 -i sample.pdf)" \ '{userPromptData: {byteItem: {byteDataType: "FILE_TYPE", byteData: $data}}}')" \ -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:sanitizeUserPrompt"
更改下列內容:
PROJECT_ID:範本所屬的專案 ID。LOCATION:範本的位置。TEMPLATE_ID:範本 ID。FILE_TYPE:輸入檔案的格式。
Go
如要執行這段程式碼,請先設定 Go 開發環境,然後安裝 Model Armor Go SDK。
C#
如要執行這段程式碼,請先設定 C# 開發環境,然後安裝 Model Armor C# SDK。
Java
如要執行這段程式碼,請先設定 Java 開發環境,然後安裝 Model Armor Java SDK。
Node.js
如要執行這段程式碼,請先設定 Node.js 開發環境, 然後安裝 Model Armor Node.js SDK。
PHP
如要執行這段程式碼,請先設定 PHP 開發環境,然後安裝 Model Armor PHP SDK。
Python
如要執行這段程式碼,請設定 Python 開發環境,並安裝 Model Armor Python SDK。
基本 Sensitive Data Protection 設定
Model Armor 會與 Sensitive Data Protection 整合,協助防範私人資訊意外曝光。建立範本並啟用基本 Sensitive Data Protection 設定。基本私密/機密資料保護功能可協助您篩選一組固定的 Sensitive Data Protection infoType。
系統會在提示中掃描下列 Sensitive Data Protection infoType,適用於所有區域:
CREDIT_CARD_NUMBER:信用卡號碼是長度介於 12 到 19 位數的一組號碼,可用於全球付款交易。FINANCIAL_ACCOUNT_NUMBER:指特定金融帳戶的號碼,例如銀行帳號或退休金帳號。GCP_CREDENTIALS: Google Cloud 服務帳戶憑證。憑證可以用來驗證 {api_client_lib_name} 和服務帳戶。GCP_API_KEY: Google Cloud API 金鑰。呼叫 Google Cloud 不需要存取私人使用者資料的 API 時,使用的加密字串。PASSWORD:設定、程式碼和其他文字中的明文密碼。
在美國地區的提示中,系統會掃描下列額外的 Sensitive Data Protection infoType:
US_SOCIAL_SECURITY_NUMBER:美國社會安全號碼 (SSN) 是長度共 9 碼的數字,核發對象為美國的公民、永久居民和臨時居民。這項偵測工具不會比對出任何均為 0 的數字群組 (即 000-##-####、###-00-#### 或 ###-##-0000)、第一個數字群組為 666 的號碼,或是第一碼為 9 的號碼。US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER:美國個人納稅識別號碼 (ITIN) 是由美國國稅局 (IRS) 核發的一種稅務識別碼 (TIN)。ITIN 這類稅務處理號碼僅適用於無法取得社會安全號碼 (SSN) 的特定非居民和外籍居民、其配偶和眷屬。
以下是基本的 Sensitive Data Protection 設定範例:
gcloud
gcloud model-armor templates create TEMPLATE_ID \ --location=LOCATION \ --project=PROJECT_ID \ --basic-config-filter-enforcement=enabled
更改下列內容:
TEMPLATE_ID:範本 ID。LOCATION:範本的位置。
REST
export FILTER_CONFIG_SDP_BASIC='{ "filterConfig": { "sdpSettings": { "basicConfig": { "filterEnforcement": "ENABLED" } } } }' curl -X PATCH \ -d "$FILTER_CONFIG_SDP_BASIC" \ -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?updateMask=filterConfig.sdpSettings.basicConfig.filterEnforcement"
更改下列內容:
PROJECT_ID:範本所屬的專案 ID。LOCATION:範本的位置。TEMPLATE_ID:範本 ID。
Go
如要執行這段程式碼,請先設定 Go 開發環境,然後安裝 Model Armor Go SDK。
C#
如要執行這段程式碼,請先設定 C# 開發環境,然後安裝 Model Armor C# SDK。
Java
如要執行這段程式碼,請先設定 Java 開發環境,然後安裝 Model Armor Java SDK。
Node.js
如要執行這段程式碼,請先設定 Node.js 開發環境, 然後安裝 Model Armor Node.js SDK。
PHP
如要執行這段程式碼,請先設定 PHP 開發環境,然後安裝 Model Armor PHP SDK。
Python
如要執行這段程式碼,請設定 Python 開發環境,並安裝 Model Armor Python SDK。
使用建立的範本篩選提示。範例如下:
curl -X POST \ -d '{"userPromptData":{"text":"can you remember my ITIN : ###-##-####"}}' \ -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:sanitizeUserPrompt"
更改下列內容:
PROJECT_ID:範本所屬的專案 ID。LOCATION:範本的位置。TEMPLATE_ID:範本 ID。
這個範例會傳回下列回應:
{ "sanitizationResult": { "filterMatchState": "MATCH_FOUND", "invocationResult": "SUCCESS", "filterResults": [ { "csamFilterFilterResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "NO_MATCH_FOUND" } }, { "sdpFilterResult": { "inspectResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "MATCH_FOUND", "findings": [ { "infoType": "US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER", "likelihood": "LIKELY", "location": { "byteRange": { "start": "26", "end": "37" }, "codepointRange": { "start": "26", "end": "37" } } } ] } } } ] } }
進階 Sensitive Data Protection 設定
Model Armor 會使用進階的 Sensitive Data Protection 設定,篩選 LLM 提示詞和回覆。這樣一來,您就能使用 Sensitive Data Protection 功能,而不僅限於基本 Sensitive Data Protection 設定提供的 infoType。
如要在 Model Armor 中使用 Sensitive Data Protection 進階篩選器,Sensitive Data Protection 範本必須與 Model Armor 範本位於同一個雲端位置。
gcloud
gcloud model-armor templates create TEMPLATE_ID \ --location=LOCATION \ --advanced-config-inspect-template="path/to/template" \
更改下列內容:
TEMPLATE_ID:範本 ID。LOCATION:範本的位置。
REST
export FILTER_CONFIG_SDP_ADV='{ "filterConfig": { "sdpSettings": { "advancedConfig": { "deidentifyTemplate": "projects/PROJECT_ID/locations/LOCATION/deidentifyTemplates/deidentify-ip-address", "inspectTemplate": "projects/PROJECT_ID/locations/LOCATION/inspectTemplates/inspect-ip-address" } } } }' curl -X POST \ -d "$FILTER_CONFIG_SDP_ADV" \ -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?updateMask=filterConfig.sdpSettings.advancedConfig"
更改下列內容:
PROJECT_ID:範本所屬的專案 ID。LOCATION:範本的位置。TEMPLATE_ID:範本 ID。
這個範例會傳回下列回應:
{ "name": "projects/PROJECT_ID/locations/LOCATION/templates/all-filters-test", "createTime": "2024-12-16T17:08:19.626693819Z", "updateTime": "2024-12-16T17:08:19.626693819Z", "filterConfig": { "sdpSettings": { "advancedConfig": { "deidentifyTemplate": "projects/PROJECT_ID/locations/LOCATION/deidentifyTemplates/deidentify-ip-address", "inspectTemplate": "projects/PROJECT_ID/locations/LOCATION/inspectTemplates/inspect-ip-address" } } } }
C#
如要執行這段程式碼,請先設定 C# 開發環境,然後安裝 Model Armor C# SDK。
Go
如要執行這段程式碼,請先設定 Go 開發環境,然後安裝 Model Armor Go SDK。
Java
如要執行這段程式碼,請先設定 Java 開發環境,然後安裝 Model Armor Java SDK。
Node.js
如要執行這段程式碼,請先設定 Node.js 開發環境, 然後安裝 Model Armor Node.js SDK。
PHP
如要執行這段程式碼,請先設定 PHP 開發環境,然後安裝 Model Armor PHP SDK。
Python
如要執行這段程式碼,請設定 Python 開發環境,並安裝 Model Armor Python SDK。
使用建立的範本篩選提示。範例如下:
curl -X POST \ -d '{"userPromptData":{"text":"is there anything malicious running on 1.1.1.1?"}}' \ -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:sanitizeUserPrompt"
更改下列內容:
PROJECT_ID:範本所屬的專案 ID。LOCATION:範本的位置。TEMPLATE_ID:範本 ID。
這個範例會傳回下列回應:
{ "sanitizationResult": { "filterMatchState": "MATCH_FOUND", "invocationResult": "SUCCESS", "filterResults": [ { "csamFilterFilterResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "NO_MATCH_FOUND" } }, { "sdpFilterResult": { "deidentifyResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "MATCH_FOUND", "data": { "text": "is there anything malicious running on [IP_ADDRESS]?" }, "transformedBytes": "7", "infoTypes": ["IP_ADDRESS"] } } } ] } }
清理模型回覆
大型語言模型有時會生成有害的回覆。為降低在應用程式中使用大型語言模型時的相關風險,請務必清除模型回覆中的有害內容。
以下是在 Model Armor 中清理模型回覆的指令範例。
REST
curl -X POST \
-d '{"modelResponseData":{"text":"IP address of the current network is ##.##.##.##"}}' \
-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:sanitizeModelResponse"
更改下列內容:
PROJECT_ID:範本所屬的專案 ID。LOCATION:範本的位置。TEMPLATE_ID:範本 ID。這個範例會傳回下列回應:
{ "sanitizationResult": { "filterMatchState": "MATCH_FOUND", "invocationResult": "SUCCESS", "filterResults": { "rai": { "raiFilterResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "MATCH_FOUND", "raiFilterTypeResults": { "dangerous": { "confidenceLevel": "MEDIUM_AND_ABOVE", "matchState": "MATCH_FOUND" }, "sexually_explicit": { "matchState": "NO_MATCH_FOUND" }, "hate_speech": { "matchState": "NO_MATCH_FOUND" }, "harassment": { "matchState": "NO_MATCH_FOUND" } } } }, "pi_and_jailbreak": { "piAndJailbreakFilterResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "NO_MATCH_FOUND" } }, "csam": { "csamFilterFilterResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "NO_MATCH_FOUND" } }, "malicious_uris": { "maliciousUriFilterResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "NO_MATCH_FOUND" } }, } } }
C#
如要執行這段程式碼,請先設定 C# 開發環境,然後安裝 Model Armor C# SDK。
Go
如要執行這段程式碼,請先設定 Go 開發環境,然後安裝 Model Armor Go SDK。
Java
如要執行這段程式碼,請先設定 Java 開發環境,然後安裝 Model Armor Java SDK。
Node.js
如要執行這段程式碼,請先設定 Node.js 開發環境, 然後安裝 Model Armor Node.js SDK。
PHP
如要執行這段程式碼,請先設定 PHP 開發環境,然後安裝 Model Armor PHP SDK。
Python
如要執行這段程式碼,請設定 Python 開發環境,並安裝 Model Armor Python SDK。
啟用多語言偵測功能,清理模型回覆
如要針對每個要求啟用多語言偵測功能,請為每個個別回應將 enableMultiLanguageDetection 旗標設為 true。如要取得更準確的結果,可以指定原文語言。
- 如未指定原文語言,Model Armor 會自動偵測語言,提供多語言支援。
- 如果指定原文語言,Model Armor 會使用該語言評估模型回應,不會執行自動偵測語言。
curl -X POST \ -d '{"modelResponseData":{"text":"[UNSAFE TEXT]"}, "multiLanguageDetectionMetadata": { "enableMultiLanguageDetection": true , "sourceLanguage": "jp"}}' \ -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:sanitizeModelResponse"
更改下列內容:
PROJECT_ID:範本所屬的專案 ID。LOCATION:範本的位置。TEMPLATE_ID:範本 ID。
清理各專案的模型回覆
如要啟用集中式 AI 安全管理功能,機構通常會將 Model Armor 範本儲存在專案 A (TEMPLATE_PROJECT_ID) 中,應用程式則在專案 B 中執行。
如要允許專案 B 的服務帳戶 (CALLER_SERVICE_ACCOUNT) 存取專案 A 中的範本,您必須將 IAM 政策繫結新增至範本專案。
如要授予必要的跨專案權限,請執行下列指令:
gcloud projects add-iam-policy-binding TEMPLATE_PROJECT_ID \ --member='serviceAccount:CALLER_SERVICE_ACCOUNT' \ --role='roles/modelarmor.user'
更改下列內容:
TEMPLATE_PROJECT_ID:範本代管專案的 ID。CALLER_SERVICE_ACCOUNT:發出 API 要求的專案中的服務帳戶。
後續步驟
- 進一步瞭解 Model Armor。
- 瞭解 Model Armor 底限設定。
- 瞭解 Model Armor 範本。
- 排解 Model Armor 問題。