本頁詳細說明如何清除提示和回覆。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。
控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。 Google Cloud 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。
含有圖片的提示
如要啟用圖片篩選,請在範本中繼資料中設定模態。
您可以在新範本和現有範本中設定模式。
如果您指定單一模態 (IMAGE 或 TEXT),Model Armor 會略過其他模態並傳回 EXECUTION_SKIPPED。您必須將 byteDataType 欄位明確設為 IMAGE,並在 byteData 欄位中提供 支援格式的 Base64 編碼圖片。
使用下列指令,清除含有圖片的提示。
curl -X POST \ -d "$(jq -n \ --arg data "$(base64 -w 0 -i IMAGE)" \ '{userPromptData: {byteItem: {byteDataType: "IMAGE", 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。IMAGE:支援格式的圖片。
回覆內容大致如下:
{ "sanitizationResult": { "filterMatchState": "MATCH_FOUND", "invocationResult": "SUCCESS", "filterResults": { "csam": { "csamFilterFilterResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "NO_MATCH_FOUND" } }, "sdp": { "sdpFilterResult": { "inspectResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "MATCH_FOUND" } } } }, } }
遮蓋圖片
如果是 Sensitive Data Protection 進階模式,只有在您使用 Sensitive Data Protection 檢查範本和 Sensitive Data Protection 去識別化範本設定 Model Armor 篩選器時,Model Armor 才會遮蓋圖片。詳情請參閱「設定 Sensitive Data Protection 設定」。請務必在去識別化範本中設定圖片遮蓋。
使用 Sensitive Data Protection 進階模式時,即使設定的檢查範本未明確納入 BASIC_AUTH_HEADERinfoType,偵測結果仍可能會回報該 infoType。
以下範例顯示已啟用 Sensitive Data Protection 遮蓋功能的篩選器設定。
{ "filterConfig": { "sdpSettings": { "advancedConfig": { "inspectTemplate": "projects/PROJECT_ID/locations/LOCATION/inspectTemplates/TEMPLATE_ID", "deidentifyTemplate": "projects/PROJECT_ID/locations/LOCATION/deidentifyTemplates/TEMPLATE_ID" } } } }
更改下列內容:
PROJECT_ID:包含範本的專案 ID。LOCATION:範本的位置。TEMPLATE_ID:範本 ID。
這會產生下列回應。
{ "sanitizationResult": { "filterMatchState": "MATCH_FOUND", "invocationResult": "SUCCESS", "filterResults": { "csam": { "csamFilterFilterResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "NO_MATCH_FOUND" } }, "sdp": { "sdpFilterResult": { "redactResult": { "executionState": "EXECUTION_SUCCESS", "matchState": "MATCH_FOUND", "redactedImage": "[REDACTED_IMAGE]", "findings": [ { "infoType": "EMAIL_ADDRESS", "likelihood": "LIKELY", "location": { "contentLocations": [ { "imageFindingLocation": { "boundingBox": { "top": 16, "left": 121, "width": 620, "height": 90 } } } ] } } ] } } } } } }
清理串流文字提示
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 := "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
}
}
C#
如要執行這段程式碼,請先設定 C# 開發環境,並安裝 Model Armor C# SDK。
using Google.Api.Gax.Grpc;
using Google.Cloud.ModelArmor.V1Beta;
using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class StreamSanitizeUserPromptExample
{
public static async Task Main(string[] args)
{
try
{
await RunStreamSanitizeUserPromptExample();
}
catch (Exception e)
{
Console.WriteLine($"An error occurred: {e}");
}
}
public static async Task RunStreamSanitizeUserPromptExample()
{
string projectId = "YOUR_PROJECT_ID";
string location = "LOCATION_ID";
string templateId = "YOUR_TEMPLATE_ID";
var promptChunks = new List<string>
{
"This is the first part of the user prompt. ",
"This is the second part. ",
"And this is the final part."
};
// Construct the regional REP endpoint (without port)
string regionalEndpoint = $"modelarmor.{location}.rep.googleapis.com";
Console.WriteLine($"Using endpoint: {regionalEndpoint}");
// Initialize the Model Armor client using Application Default Credentials.
var client = new ModelArmorClientBuilder
{
Endpoint = regionalEndpoint
}.Build();
// Construct the resource name.
var resourceName = TemplateName.FromProjectLocationTemplate(projectId, location, templateId);
// Get the bi-directional streaming call object
using var stream = client.StreamSanitizeUserPrompt();
Console.WriteLine("Sending requests...");
// --- Send First Request ---
var firstRequest = new SanitizeUserPromptRequest
{
Name = resourceName.ToString(),
UserPromptData = new DataItem { Text = promptChunks[0] },
StreamingMode = StreamingMode.Buffered // Or StreamingMode.Realtime
};
await stream.WriteAsync(firstRequest);
Console.WriteLine($"Sent chunk 1: \"{promptChunks[0]}\"");
// --- Send Subsequent Requests ---
for (int i = 1; i < promptChunks.Count; i++)
{
var subsequentRequest = new SanitizeUserPromptRequest
{
Name = resourceName.ToString(),
UserPromptData = new DataItem { Text = promptChunks[i] }
};
await stream.WriteAsync(subsequentRequest);
Console.WriteLine($"Sent chunk {i + 1}: \"{promptChunks[i]}\"");
}
// Signal that the client has finished sending requests.
await stream.WriteCompleteAsync();
Console.WriteLine("Client finished sending.");
// --- Receive Responses ---
Console.WriteLine("Receiving responses...");
// This loop waits for responses until the server closes the stream.
while (await stream.GetResponseStream().MoveNextAsync())
{
SanitizeUserPromptResponse response = stream.GetResponseStream().Current;
if (response.SanitizationResult != null)
{
var result = response.SanitizationResult;
Console.WriteLine("Received response:");
Console.WriteLine($" Match State: {result.FilterMatchState}");
Console.WriteLine($" Invocation Result: {result.InvocationResult}");
}
else
{
Console.WriteLine("Received empty response.");
}
}
Console.WriteLine("Stream finished and closed.");
}
}
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 = "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();
}
}
}
Node.js
如要執行這段程式碼,請先設定 Node.js 開發環境, 然後安裝 Model Armor Node.js SDK。
const { ModelArmorClient } = require('@google-cloud/modelarmor').v1beta;
async function streamSanitizeUserPromptExample() {
const projectId = 'YOUR_PROJECT_ID';
const location = 'LOCATION_ID';
const templateId = 'YOUR_TEMPLATE_ID';
const promptChunks = [
'This is the first part of the user prompt. ',
'This is the second part. ',
'And this is the final part.'
];
// Construct the regional REP endpoint
const regionalEndpoint = `modelarmor.${location}.rep.googleapis.com`;
console.log(`Using endpoint: ${regionalEndpoint}`);
// Initialize the Model Armor client with options
const modelArmorClient = new ModelArmorClient({
apiEndpoint: regionalEndpoint,
});
const resourceName = `projects/${projectId}/locations/${location}/templates/${templateId}`;
try {
// Obtain the bidirectional stream object
const stream = modelArmorClient.streamSanitizeUserPrompt();
// Setup events for receiving responses
stream.on('data', (response) => {
if (response.sanitizationResult) {
const result = response.sanitizationResult;
console.log('Received response:');
console.log(` Match State: ${result.filterMatchState}`);
console.log(` Invocation Result: ${result.invocationResult}`);
} else {
console.log('Received empty response.');
}
});
stream.on('error', (err) => {
console.error('Stream error occurred:', err);
});
stream.on('end', () => {
console.log('Stream finished and closed.');
});
console.log('Sending requests...');
// --- Send First Request ---
const firstRequest = {
name: resourceName,
userPromptData: {
text: promptChunks[0]
},
streamingMode: 'STREAMING_MODE_BUFFERED' // Or 'STREAMING_MODE_REALTIME'
};
stream.write(firstRequest);
console.log(`Sent chunk 1: "${promptChunks[0]}"`);
// --- Send Subsequent Requests ---
for (let i = 1; i < promptChunks.length; i++) {
const subsequentRequest = {
name: resourceName,
userPromptData: {
text: promptChunks[i]
}
};
stream.write(subsequentRequest);
console.log(`Sent chunk ${i + 1}: "${promptChunks[i]}"`);
}
// Signals gRPC end-of-writing from client
stream.end();
console.log('Client finished sending.');
} catch (e) {
console.error('Error during stream initialization:', e);
}
}
// Execute logic
streamSanitizeUserPromptExample();
```
PHP
如要執行這段程式碼,請先設定 PHP 開發環境,然後安裝 Model Armor PHP SDK。
use Google\ApiCore\ApiException;
use Google\ApiCore\BidiStream;
use Google\Cloud\ModelArmor\V1beta\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1beta\DataItem;
use Google\Cloud\ModelArmor\V1beta\SanitizeUserPromptRequest;
use Google\Cloud\ModelArmor\V1beta\SanitizeUserPromptResponse;
use Google\Cloud\ModelArmor\V1beta\StreamingMode;
use Google\Cloud\ModelArmor\V1beta\FilterMatchState;
use Google\Cloud\ModelArmor\V1beta\InvocationResult;
function stream_sanitize_user_prompt_example()
{
$projectId = 'YOUR_PROJECT_ID';
$location = 'LOCATION_ID';
$templateId = 'YOUR_TEMPLATE_ID';
$promptChunks = [
"This is the first part of the user prompt. ",
"This is the second part. ",
"And this is the final part."
];
// Construct the regional REP endpoint (without port)
$regionalEndpoint = sprintf('modelarmor.%s.rep.googleapis.com', $location);
echo "Using endpoint: " . $regionalEndpoint . PHP_EOL;
try {
// Initialize the Model Armor client
$modelArmorClient = new ModelArmorClient([
'apiEndpoint' => $regionalEndpoint,
]);
// Construct the resource name.
$resourceName = sprintf('projects/%s/locations/%s/templates/%s', $projectId, $location, $templateId);
// Get a stream object for the StreamSanitizeUserPrompt API method.
$stream = $modelArmorClient->streamSanitizeUserPrompt();
echo "Sending requests..." . PHP_EOL;
// --- Send First Request ---
$firstRequest = (new SanitizeUserPromptRequest())
->setName($resourceName)
->setUserPromptData((new DataItem())->setText($promptChunks[0]))
->setStreamingMode(StreamingMode::STREAMING_MODE_BUFFERED); // Or STREAMING_MODE_REALTIME
$stream->write($firstRequest);
echo "Sent chunk 1: \"" . $promptChunks[0] . "\"" . PHP_EOL;
// --- Send Subsequent Requests ---
for ($i = 1; $i < count($promptChunks); $i++) {
$subsequentRequest = (new SanitizeUserPromptRequest())
->setName($resourceName)
->setUserPromptData((new DataItem())->setText($promptChunks[$i]));
$stream->write($subsequentRequest);
echo "Sent chunk " . ($i + 1) . ": \"" . $promptChunks[$i] . "\"" . PHP_EOL;
}
// Signal that the client has finished sending requests.
$stream->closeWrite();
echo "Client finished sending." . PHP_EOL;
// --- Receive Responses ---
echo "Receiving responses..." . PHP_EOL;
/** @var SanitizeUserPromptResponse $response */
foreach ($stream->closeWriteAndReadAll() as $response) {
if ($response->hasSanitizationResult()) {
$result = $response->getSanitizationResult();
echo "Received response:" . PHP_EOL;
echo " Match State: " . FilterMatchState::name($result->getFilterMatchState()) . PHP_EOL;
echo " Invocation Result: " . InvocationResult::name($result->getInvocationResult()) . PHP_EOL;
} else {
echo "Received empty response." . PHP_EOL;
}
}
echo "Stream finished and closed." . PHP_EOL;
} catch (ApiException $e) {
echo "Error during streaming: " . $e->getMessage() . PHP_EOL;
foreach ($e->getMetadata() as $key => $value) {
echo $key . ": " . print_r($value, true) . PHP_EOL;
}
} catch (Exception $e) {
echo "An unexpected error occurred: " . $e->getMessage() . PHP_EOL;
} finally {
if (isset($modelArmorClient)) {
$modelArmorClient->close();
}
}
}
stream_sanitize_user_prompt_example();
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 = "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"] } } } ] } }
如要瞭解圖片遮蓋要求和回應,請參閱「遮蓋圖片」一文。
清理模型回覆
大型語言模型有時會生成有害的回覆。為降低在應用程式中使用 LLM 的相關風險,請務必清除模型回覆中的有害內容。
以下是使用 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 安全管理功能,機構通常會在專案 A (TEMPLATE_PROJECT_ID) 中儲存 Model Armor 範本,應用程式則在專案 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 問題。