本页面详细介绍了如何清理提示和回答。 Model Armor 提供了一组过滤条件来保护您的 AI 应用。Model Armor 会根据所配置的筛选置信度来检查提示和回答。
准备工作
按照创建模板中的说明创建模板。
获取所需的权限
如需获得清理提示和回答所需的权限,请让您的管理员为您授予 Model Armor 的以下 IAM 角色:
- Model Armor User (
roles/modelarmor.user) - Model Armor Viewer (
roles/modelarmor.viewer)
如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限。
在包含 Sensitive Data Protection 模板的项目中,将 DLP User 角色 (roles/dlp.user) 和 DLP Reader 角色 (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 且已为当前项目设置值的 Shell 环境。该会话可能需要几秒钟时间来完成初始化。
使用 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 可帮助您筛查一组固定的 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 位数号码。此检测器不会与任何数字群组中全为零的数字(即 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 设置中提供的 infoType 之外的 Sensitive Data Protection 功能。
如要在 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 有时会生成有害的回答。为了降低在应用中使用 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 安全管理,组织通常会将 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 问题。