프롬프트 및 응답 정리

이 페이지에서는 프롬프트와 응답을 정리하는 방법을 자세히 설명합니다. Model Armor는 AI 애플리케이션을 보호하기 위한 필터를 제공합니다. Model Armor는 구성된 검사 신뢰도 수준에 따라 프롬프트와 응답을 확인합니다.

시작하기 전에

템플릿 만들기의 안내에 따라 템플릿을 만듭니다.

필수 권한 얻기

프롬프트와 응답을 삭제하는 데 필요한 권한을 얻으려면 관리자에게 Model Armor에 대한 다음 IAM 역할을 부여해 달라고 요청하세요.

역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

Sensitive Data Protection 템플릿이 포함된 프로젝트에서 템플릿 만들기의 고급 Sensitive Data Protection 단계의 일부로 생성된 서비스 에이전트에 DLP 사용자 역할 (roles/dlp.user) 및 DLP 리더 역할 (roles/dlp.reader)을 부여합니다. 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를 사용하려면 먼저 Model Armor API를 사용 설정해야 합니다.

콘솔

  1. Model Armor API를 사용 설정합니다.

    API 사용 설정에 필요한 역할

    API를 사용 설정하려면 serviceusage.services.enable 권한이 포함된 서비스 사용량 관리자 IAM 역할(roles/serviceusage.serviceUsageAdmin)이 필요합니다. 역할 부여 방법 알아보기

    API 사용 설정하기

  2. Model Armor를 활성화할 프로젝트를 선택합니다.

gcloud

시작하기 전에 Model Armor API와 함께 Google Cloud CLI를 사용하여 다음 단계를 따르세요.

  1. Google Cloud 콘솔에서 Cloud Shell을 활성화합니다.

    Cloud Shell 활성화

    Google Cloud 콘솔 하단에 Cloud Shell 세션이 시작되고 명령줄 프롬프트가 표시됩니다. Cloud Shell은 Google Cloud CLI가 사전 설치된 셸 환경으로, 현재 프로젝트의 값이 이미 설정되어 있습니다. 세션이 초기화되는 데 몇 초 정도 걸릴 수 있습니다.

  2. gcloud CLI를 사용하여 API 엔드포인트 재정의 설정

gcloud CLI를 사용하여 API 엔드포인트 재정의 설정

이 단계는 gcloud CLI를 사용하여 Model Armor API를 사용 설정하는 경우에만 필요합니다. gcloud CLI가 Model Armor 서비스로 요청을 올바르게 라우팅하도록 API 엔드포인트 재정의를 수동으로 설정해야 합니다.

다음 명령어를 실행하여 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를 설치합니다.


import (
	"context"
	"fmt"
	"io"

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

// sanitizeUserPrompt sanitizes a user prompt based on the project, location, and template settings.
//
// w io.Writer: The writer to use for logging.
// projectID string: The ID of the project.
// locationID string: The ID of the location.
// templateID string: The ID of the template.
// userPrompt string: The user prompt to sanitize.
func sanitizeUserPrompt(w io.Writer, projectID, locationID, templateID, userPrompt string) error {
	ctx := context.Background()

	//Create options for Model Armor client.
	opts := option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID))

	// Create the Model Armor client.
	client, err := modelarmor.NewClient(ctx, opts)
	if err != nil {
		return fmt.Errorf("failed to create client for location %s: %w", locationID, err)
	}
	defer client.Close()

	// Initialize request argument(s)
	userPromptData := &modelarmorpb.DataItem{
		DataItem: &modelarmorpb.DataItem_Text{
			Text: userPrompt,
		},
	}

	// Prepare request for sanitizing user prompt.
	req := &modelarmorpb.SanitizeUserPromptRequest{
		Name:           fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID),
		UserPromptData: userPromptData,
	}

	// Sanitize the user prompt.
	response, err := client.SanitizeUserPrompt(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to sanitize user prompt for template %s: %w", templateID, err)
	}

	// Sanitization Result.
	fmt.Fprintf(w, "Sanitization Result: %v\n", response)

	return nil
}

C#

이 코드를 실행하려면 먼저 C# 개발 환경을 설정하고 Model Armor C# SDK를 설치합니다.

using Google.Api.Gax.ResourceNames;
using Google.Cloud.ModelArmor.V1;
using Newtonsoft.Json;
using System;

namespace ModelArmor.Samples
{
    public class SanitizeUserPromptSample
    {
        public SanitizeUserPromptResponse SanitizeUserPrompt(
            string projectId = "my-project",
            string locationId = "us-central1",
            string templateId = "my-template",
            string userPrompt = "Unsafe user prompt"
        )
        {
            // Endpoint to call the Model Armor server.
            ModelArmorClientBuilder clientBuilder = new ModelArmorClientBuilder
            {
                Endpoint = $"modelarmor.{locationId}.rep.googleapis.com",
            };

            // Create the client.
            ModelArmorClient client = clientBuilder.Build();

            // Build the resource name of the template.
            TemplateName templateName = TemplateName.FromProjectLocationTemplate(projectId, locationId, templateId);

            // Prepare the request.
            SanitizeUserPromptRequest request = new SanitizeUserPromptRequest
            {
                TemplateName = templateName,
                UserPromptData = new DataItem { Text = userPrompt },
            };

            // Send the request and get the response.
            SanitizeUserPromptResponse response = client.SanitizeUserPrompt(request);

            return response;
        }
    }
}

자바

이 코드를 실행하려면 먼저 Java 개발 환경을 설정하고 Model Armor Java SDK를 설치합니다.


import com.google.cloud.modelarmor.v1.DataItem;
import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.SanitizeUserPromptRequest;
import com.google.cloud.modelarmor.v1.SanitizeUserPromptResponse;
import com.google.cloud.modelarmor.v1.TemplateName;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;

public class SanitizeUserPrompt {

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

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

    sanitizeUserPrompt(projectId, locationId, templateId, userPrompt);
  }

  public static SanitizeUserPromptResponse sanitizeUserPrompt(String projectId, String locationId,
      String templateId, String userPrompt) throws IOException {

    // Endpoint to call the Model Armor server.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);
    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder()
        .setEndpoint(apiEndpoint)
        .build();

    try (ModelArmorClient client = ModelArmorClient.create(modelArmorSettings)) {
      // Build the resource name of the template.
      String templateName = TemplateName.of(projectId, locationId, templateId).toString();

      // Prepare the request.
      SanitizeUserPromptRequest request = SanitizeUserPromptRequest.newBuilder()
          .setName(templateName)
          .setUserPromptData(DataItem.newBuilder().setText(userPrompt).build())
          .build();

      SanitizeUserPromptResponse response = client.sanitizeUserPrompt(request);
      System.out.println("Result for the provided user prompt: "
          + JsonFormat.printer().print(response.getSanitizationResult()));

      return response;
    }
  }
}

Node.js

이 코드를 실행하려면 먼저 Node.js 개발 환경을 설정하고 Model Armor Node.js SDK를 설치합니다.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = process.env.PROJECT_ID || 'your-project-id';
// const locationId = process.env.LOCATION_ID || 'us-central1';
// const templateId = process.env.TEMPLATE_ID || 'template-id';
// const userPrompt = 'unsafe user prompt';
const {ModelArmorClient} = require('@google-cloud/modelarmor').v1;

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

const request = {
  name: `projects/${projectId}/locations/${locationId}/templates/${templateId}`,
  userPromptData: {
    text: userPrompt,
  },
};

const [response] = await client.sanitizeUserPrompt(request);
console.log(JSON.stringify(response, null, 2));
return response;

PHP

이 코드를 실행하려면 먼저 PHP 개발 환경을 설정하고 Model Armor PHP SDK를 설치합니다.

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\SanitizeUserPromptRequest;
use Google\Cloud\ModelArmor\V1\DataItem;

/**
 * Sanitizes a user prompt using the specified template.
 *
 * @param string $projectId The ID of your Google Cloud Platform project (e.g. 'my-project').
 * @param string $locationId The ID of the location where the template is stored (e.g. 'us-central1').
 * @param string $templateId The ID of the template (e.g. 'my-template').
 * @param string $userPrompt The user prompt to sanitize (e.g. 'my-user-prompt').
 */
function sanitize_user_prompt(
    string $projectId,
    string $locationId,
    string $templateId,
    string $userPrompt
): void {
    $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
    $client = new ModelArmorClient($options);

    $userPromptRequest = (new SanitizeUserPromptRequest())
        ->setName("projects/$projectId/locations/$locationId/templates/$templateId")
        ->setUserPromptData((new DataItem())->setText($userPrompt));

    $response = $client->sanitizeUserPrompt($userPromptRequest);

    printf('Result for Sanitize User Prompt: %s' . PHP_EOL, $response->serializeToJsonString());
}

Python

이 코드를 실행하려면 Python 개발 환경을 설정하고 Model Armor Python SDK를 설치합니다.


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

# TODO(Developer): Uncomment these variables.
# project_id = "YOUR_PROJECT_ID"
# location_id = "us-central1"
# template_id = "template_id"
# user_prompt = "Prompt entered by the user"

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

# Initialize request argument(s).
user_prompt_data = modelarmor_v1.DataItem(text=user_prompt)

# Prepare request for sanitizing the defined prompt.
request = modelarmor_v1.SanitizeUserPromptRequest(
    name=f"projects/{project_id}/locations/{location_id}/templates/{template_id}",
    user_prompt_data=user_prompt_data,
)

# Sanitize the user prompt.
response = client.sanitize_user_prompt(request=request)

# Sanitization Result.
print(response)

그러면 다음과 같은 응답이 반환됩니다.

  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에서 프롬프트를 정리하기 위한 권장사항

Model Armor를 사용하여 대화형 AI 애플리케이션에서 입력을 정리할 때는 SanitizeUserPrompt 메서드의 userPromptData 필드에 무엇을 포함해야 하는지 이해하는 것이 중요합니다.

  • 각 사용자 입력을 별도로 정리: 사용자로부터 수신된 각 새 메시지에 대해 SanitizeUserPrompt API를 호출합니다. 이렇게 하면 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는 실시간 스트리밍 모드를 사용할 때 무제한 토큰을 지원하는 반면 버퍼링 모드에는 토큰 한도가 적용됩니다.

스트리밍은 다음과 같이 작동합니다.

  1. 청크 입력: 애플리케이션이 전체 텍스트 본문을 한 번에 전송하는 대신 더 작은 조각 (청크)으로 텍스트를 Model Armor에 전송합니다.
  2. 실시간 처리: Model Armor는 이러한 청크가 도착하면 처리하고 템플릿에 구성된 보안 및 안전 필터를 적용합니다.
  3. 지속적인 피드백: 모드 (실시간 모드 또는 버퍼링 모드)에 따라 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 개발 환경을 설정하고 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를 설치합니다.


import (
	"context"
	"fmt"
	"io"
	"os"

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

// screenPDFFile screens a PDF file.
//
// This method screens a PDF file based on the project, location, and template settings.
//
// w io.Writer: The writer to use for logging.
// projectID string: The ID of the project.
// locationID string: The ID of the location.
// templateID string: The ID of the template.
// pdfFilePath string: The path to the PDF file to be screened.
func screenPDFFile(w io.Writer, projectID, locationID, templateID, pdfFilePath string) error {
	ctx := context.Background()

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

	// Read PDF file content into bytes
	pdfBytes, err := os.ReadFile(pdfFilePath)
	if err != nil {
		return fmt.Errorf("failed to read PDF file: %w", err)
	}

	// Initialize request argument(s)
	userPromptData := &modelarmorpb.DataItem{
		DataItem: &modelarmorpb.DataItem_ByteItem{
			ByteItem: &modelarmorpb.ByteDataItem{
				ByteDataType: modelarmorpb.ByteDataItem_PDF,
				ByteData:     pdfBytes,
			},
		},
	}

	// Prepare request for sanitizing the defined prompt.
	req := &modelarmorpb.SanitizeUserPromptRequest{
		Name:           fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID),
		UserPromptData: userPromptData,
	}

	// Sanitize the user prompt.
	response, err := client.SanitizeUserPrompt(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to sanitize PDF content for template %s: %w", templateID, err)
	}

	// Sanitization Result.
	fmt.Fprintf(w, "PDF screening sanitization result: %v\n", response)

	return nil
}

C#

이 코드를 실행하려면 먼저 C# 개발 환경을 설정하고 Model Armor C# SDK를 설치합니다.

using Google.Api.Gax.ResourceNames;
using Google.Cloud.ModelArmor.V1;
using Google.Protobuf;
using Newtonsoft.Json;
using System;
using System.IO;

namespace ModelArmor.Samples
{
    public class ScanPdfFileSample
    {
        public SanitizeUserPromptResponse ScanPdfFile(
            string projectId = "my-project",
            string locationId = "us-central1",
            string templateId = "my-template",
            string pdfFilePath = "path/to/file.pdf"
        )
        {
            // Endpoint to call the Model Armor server.
            ModelArmorClientBuilder clientBuilder = new ModelArmorClientBuilder
            {
                Endpoint = $"modelarmor.{locationId}.rep.googleapis.com",
            };

            // Create the client.
            ModelArmorClient client = clientBuilder.Build();

            // Build the resource name of the template.
            TemplateName templateName = TemplateName.FromProjectLocationTemplate(projectId, locationId, templateId);

            // Read the PDF file content
            byte[] fileContent = File.ReadAllBytes(pdfFilePath);

            // Prepare the request with PDF data
            SanitizeUserPromptRequest request = new SanitizeUserPromptRequest
            {
                TemplateName = templateName,
                UserPromptData = new DataItem
                {
                    ByteItem = new ByteDataItem
                    {
                        ByteDataType = ByteDataItem.Types.ByteItemType.Pdf,
                        ByteData = ByteString.CopyFrom(fileContent),
                    },
                },
            };

            // Send the request and get the response.
            SanitizeUserPromptResponse response = client.SanitizeUserPrompt(request);

            return response;
        }
    }
}

자바

이 코드를 실행하려면 먼저 Java 개발 환경을 설정하고 Model Armor Java SDK를 설치합니다.


import com.google.cloud.modelarmor.v1.ByteDataItem;
import com.google.cloud.modelarmor.v1.ByteDataItem.ByteItemType;
import com.google.cloud.modelarmor.v1.DataItem;
import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.SanitizeUserPromptRequest;
import com.google.cloud.modelarmor.v1.SanitizeUserPromptResponse;
import com.google.cloud.modelarmor.v1.TemplateName;
import com.google.protobuf.ByteString;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ScreenPdfFile {

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

    // Specify the Google Project ID.
    String projectId = "your-project-id";
    // Specify the location ID. For example, us-central1. 
    String locationId = "your-location-id";
    // Specify the template ID.
    String templateId = "your-template-id";
    // Specify the PDF file path. Replace with your PDF file path.
    String pdfFilePath = "src/main/resources/test_sample.pdf";

    screenPdfFile(projectId, locationId, templateId, pdfFilePath);
  }

  public static SanitizeUserPromptResponse screenPdfFile(String projectId, String locationId,
      String templateId, String pdfFilePath) throws IOException {

    // Endpoint to call the Model Armor server.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);
    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder().setEndpoint(apiEndpoint)
        .build();

    try (ModelArmorClient client = ModelArmorClient.create(modelArmorSettings)) {
      // Build the resource name of the template.
      String name = TemplateName.of(projectId, locationId, templateId).toString();

      // Read the PDF file content and encode it to Base64.
      byte[] fileContent = Files.readAllBytes(Paths.get(pdfFilePath));

      // Prepare the request.
      DataItem userPromptData = DataItem.newBuilder()
          .setByteItem(
            ByteDataItem.newBuilder()
              .setByteDataType(ByteItemType.PDF)
              .setByteData(ByteString.copyFrom(fileContent))
              .build())
          .build();

      SanitizeUserPromptRequest request =
          SanitizeUserPromptRequest.newBuilder()
              .setName(name)
              .setUserPromptData(userPromptData)
              .build();

      // Send the request and get the response.
      SanitizeUserPromptResponse response = client.sanitizeUserPrompt(request);

      // Print the sanitization result.
      System.out.println("Result for the provided PDF file: "
          + JsonFormat.printer().print(response.getSanitizationResult()));

      return response;
    }
  }
}

Node.js

이 코드를 실행하려면 먼저 Node.js 개발 환경을 설정하고 Model Armor Node.js SDK를 설치합니다.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = process.env.PROJECT_ID || 'your-project-id';
// const locationId = process.env.LOCATION_ID || 'us-central1';
// const templateId = process.env.TEMPLATE_ID || 'template-id';
// const pdfContentFilename = 'path/to/file.pdf';

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

const fs = require('fs');

const pdfContent = fs.readFileSync(pdfContentFilename);
const pdfContentBase64 = pdfContent.toString('base64');

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

const request = {
  name: `projects/${projectId}/locations/${locationId}/templates/${templateId}`,
  userPromptData: {
    byteItem: {
      byteDataType: ByteItemType.PDF,
      byteData: pdfContentBase64,
    },
  },
};

const [response] = await client.sanitizeUserPrompt(request);
console.log(JSON.stringify(response, null, 2));
return response;

PHP

이 코드를 실행하려면 먼저 PHP 개발 환경을 설정하고 Model Armor PHP SDK를 설치합니다.

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\SanitizeUserPromptRequest;
use Google\Cloud\ModelArmor\V1\ByteDataItem;
use Google\Cloud\ModelArmor\V1\ByteDataItem\ByteItemType;
use Google\Cloud\ModelArmor\V1\DataItem;

/**
 * Screens a PDF file using the ModelArmor service.
 *
 * @param string $projectId The Google Cloud project ID (e.g. 'my-project').
 * @param string $locationId The location ID of the ModelArmor service (e.g. 'us-central1').
 * @param string $templateId The ID of the template to use for the screener (e.g. 'my-template').
 * @param string $filePath The path to the PDF file to screen (e.g. 'path/to/file.pdf').
 */
function screen_pdf_file(
    string $projectId,
    string $locationId,
    string $templateId,
    string $filePath
): void {
    $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
    $client = new ModelArmorClient($options);

    // Read the file content and encode it in base64.
    $pdfContent = file_get_contents($filePath);
    $pdfContentBase64 = base64_encode($pdfContent);

    $userPromptRequest = (new SanitizeUserPromptRequest())
        ->setName("projects/$projectId/locations/$locationId/templates/$templateId")
        ->setUserPromptData((new DataItem())
            ->setByteItem((new ByteDataItem())->setByteData($pdfContentBase64)
                ->setByteDataType(ByteItemType::PDF)));

    $response = $client->sanitizeUserPrompt($userPromptRequest);

    printf('Result for Screen PDF File: %s' . PHP_EOL, $response->serializeToJsonString());
}

Python

이 코드를 실행하려면 Python 개발 환경을 설정하고 Model Armor Python SDK를 설치합니다.


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

# TODO(Developer): Uncomment these variables.
# project_id = "YOUR_PROJECT_ID"
# location_id = "us-central1"
# template_id = "template_id"
# pdf_content_filename = "path/to/file.pdf"

# Encode the PDF file into base64
with open(pdf_content_filename, "rb") as f:
    pdf_content_base64 = base64.b64encode(f.read())

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

# Initialize request argument(s).
user_prompt_data = modelarmor_v1.DataItem(
    byte_item=modelarmor_v1.ByteDataItem(
        byte_data_type=modelarmor_v1.ByteDataItem.ByteItemType.PDF,
        byte_data=pdf_content_base64,
    )
)

request = modelarmor_v1.SanitizeUserPromptRequest(
    name=f"projects/{project_id}/locations/{location_id}/templates/{template_id}",
    user_prompt_data=user_prompt_data,
)

# Sanitize the user prompt.
response = client.sanitize_user_prompt(request=request)

# Sanitization Result.
print(response)

기본 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자리 번호입니다. 숫자 그룹의 숫자가 모두 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를 설치합니다.


import (
	"context"
	"fmt"
	"io"

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

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

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

	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)

	// Build the Model Armor template with your preferred filters.
	// For more details on filters, please refer to the following doc:
	// [https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters)
	template := &modelarmorpb.Template{
		FilterConfig: &modelarmorpb.FilterConfig{
			RaiSettings: &modelarmorpb.RaiFilterSettings{
				RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{
					{
						FilterType:      modelarmorpb.RaiFilterType_DANGEROUS,
						ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH,
					},
					{
						FilterType:      modelarmorpb.RaiFilterType_HARASSMENT,
						ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE,
					},
					{
						FilterType:      modelarmorpb.RaiFilterType_HATE_SPEECH,
						ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH,
					},
					{
						FilterType:      modelarmorpb.RaiFilterType_SEXUALLY_EXPLICIT,
						ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH,
					},
				},
			},
			SdpSettings: &modelarmorpb.SdpFilterSettings{
				SdpConfiguration: &modelarmorpb.SdpFilterSettings_BasicConfig{
					BasicConfig: &modelarmorpb.SdpBasicConfig{
						FilterEnforcement: modelarmorpb.SdpBasicConfig_ENABLED,
					},
				},
			},
		},
	}

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

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

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

	return err
}

C#

이 코드를 실행하려면 먼저 C# 개발 환경을 설정하고 Model Armor C# SDK를 설치합니다.

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

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

        LocationName parent = LocationName.FromProjectLocation(projectId, locationId);

        // Build the Model Armor template with Basic SDP Filter.
        // For more details on filters, please refer to:
        // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
        SdpBasicConfig basicSdpConfig = new SdpBasicConfig
        {
            FilterEnforcement = SdpBasicConfig.Types.SdpBasicConfigEnforcement.Enabled,
        };

        SdpFilterSettings sdpSettings = new SdpFilterSettings { BasicConfig = basicSdpConfig };

        FilterConfig filterConfig = new FilterConfig { SdpSettings = sdpSettings };

        CreateTemplateRequest request = new CreateTemplateRequest
        {
            ParentAsLocationName = parent,
            TemplateId = templateId,
            Template = new Template { FilterConfig = filterConfig },
        };

        Template createdTemplate = client.CreateTemplate(request);

        Console.WriteLine($"Created template with Basic SDP filter: {createdTemplate.Name}");

        return createdTemplate;
    }
}

자바

이 코드를 실행하려면 먼저 Java 개발 환경을 설정하고 Model Armor Java SDK를 설치합니다.


import com.google.cloud.modelarmor.v1.CreateTemplateRequest;
import com.google.cloud.modelarmor.v1.FilterConfig;
import com.google.cloud.modelarmor.v1.LocationName;
import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.SdpBasicConfig;
import com.google.cloud.modelarmor.v1.SdpBasicConfig.SdpBasicConfigEnforcement;
import com.google.cloud.modelarmor.v1.SdpFilterSettings;
import com.google.cloud.modelarmor.v1.Template;
import java.io.IOException;

public class CreateTemplateWithBasicSdp {

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

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

    createTemplateWithBasicSdp(projectId, locationId, templateId);
  }

  public static Template createTemplateWithBasicSdp(
      String projectId, String locationId, String templateId) throws IOException {

    // Construct the API endpoint URL.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);
    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder().setEndpoint(apiEndpoint)
        .build();

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

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

      // Configure Basic SDP Filter.
      SdpBasicConfig basicSdpConfig = SdpBasicConfig.newBuilder()
          .setFilterEnforcement(SdpBasicConfigEnforcement.ENABLED)
          .build();

      SdpFilterSettings sdpSettings = SdpFilterSettings.newBuilder()
          .setBasicConfig(basicSdpConfig)
          .build();

      FilterConfig modelArmorFilter = FilterConfig.newBuilder()
          .setSdpSettings(sdpSettings)
          .build();

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

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

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

      return createdTemplate;
    }
  }
}

Node.js

이 코드를 실행하려면 먼저 Node.js 개발 환경을 설정하고 Model Armor Node.js SDK를 설치합니다.

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

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

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

const RaiFilterType = protos.google.cloud.modelarmor.v1.RaiFilterType;
const DetectionConfidenceLevel =
  protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel;
const SdpBasicConfigEnforcement =
  protos.google.cloud.modelarmor.v1.SdpBasicConfig.SdpBasicConfigEnforcement;

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

// Configuration for the template with basic SDP settings
const templateConfig = {
  filterConfig: {
    raiSettings: {
      raiFilters: [
        {
          filterType: RaiFilterType.DANGEROUS,
          confidenceLevel: DetectionConfidenceLevel.HIGH,
        },
        {
          filterType: RaiFilterType.HARASSMENT,
          confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE,
        },
        {
          filterType: RaiFilterType.HATE_SPEECH,
          confidenceLevel: DetectionConfidenceLevel.HIGH,
        },
        {
          filterType: RaiFilterType.SEXUALLY_EXPLICIT,
          confidenceLevel: DetectionConfidenceLevel.HIGH,
        },
      ],
    },
    sdpSettings: {
      basicConfig: {
        filterEnforcement: SdpBasicConfigEnforcement.ENABLED,
      },
    },
  },
};

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

const [response] = await client.createTemplate(request);
return response;

PHP

이 코드를 실행하려면 먼저 PHP 개발 환경을 설정하고 Model Armor PHP SDK를 설치합니다.

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\SdpBasicConfig\SdpBasicConfigEnforcement;
use Google\Cloud\ModelArmor\V1\SdpBasicConfig;
use Google\Cloud\ModelArmor\V1\SdpFilterSettings;
use Google\Cloud\ModelArmor\V1\FilterConfig;
use Google\Cloud\ModelArmor\V1\CreateTemplateRequest;
use Google\Cloud\ModelArmor\V1\Template;

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

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

    // Configure Basic SDP Filter.
    $sdpBasicConfig = (new SdpBasicConfig())->setFilterEnforcement(SdpBasicConfigEnforcement::ENABLED);
    $sdpSettings = (new SdpFilterSettings())->setBasicConfig($sdpBasicConfig);

    $templateFilterConfig = (new FilterConfig())
        ->setSdpSettings($sdpSettings);

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

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

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

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

Python

이 코드를 실행하려면 Python 개발 환경을 설정하고 Model Armor Python SDK를 설치합니다.


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

# TODO(Developer): Uncomment these variables.
# project_id = "YOUR_PROJECT_ID"
# location_id = "us-central1"
# template_id = "template_id"

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

parent = f"projects/{project_id}/locations/{location_id}"

# Build the Model Armor template with your preferred filters.
# For more details on filters, please refer to the following doc:
# https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
template = modelarmor_v1.Template(
    filter_config=modelarmor_v1.FilterConfig(
        rai_settings=modelarmor_v1.RaiFilterSettings(
            rai_filters=[
                modelarmor_v1.RaiFilterSettings.RaiFilter(
                    filter_type=modelarmor_v1.RaiFilterType.DANGEROUS,
                    confidence_level=modelarmor_v1.DetectionConfidenceLevel.HIGH,
                ),
                modelarmor_v1.RaiFilterSettings.RaiFilter(
                    filter_type=modelarmor_v1.RaiFilterType.HARASSMENT,
                    confidence_level=modelarmor_v1.DetectionConfidenceLevel.MEDIUM_AND_ABOVE,
                ),
                modelarmor_v1.RaiFilterSettings.RaiFilter(
                    filter_type=modelarmor_v1.RaiFilterType.HATE_SPEECH,
                    confidence_level=modelarmor_v1.DetectionConfidenceLevel.HIGH,
                ),
                modelarmor_v1.RaiFilterSettings.RaiFilter(
                    filter_type=modelarmor_v1.RaiFilterType.SEXUALLY_EXPLICIT,
                    confidence_level=modelarmor_v1.DetectionConfidenceLevel.HIGH,
                ),
            ]
        ),
        sdp_settings=modelarmor_v1.SdpFilterSettings(
            basic_config=modelarmor_v1.SdpBasicConfig(
                filter_enforcement=modelarmor_v1.SdpBasicConfig.SdpBasicConfigEnforcement.ENABLED
            )
        ),
    ),
)

# Prepare the request for creating the template.
create_template = modelarmor_v1.CreateTemplateRequest(
    parent=parent, template_id=template_id, template=template
)

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

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

만든 템플릿을 사용하여 프롬프트를 검사합니다. 예를 들면 다음과 같습니다.

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를 설치합니다.

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

public class CreateTemplateWithAdvancedSdpSample
{
    public Template CreateTemplateWithAdvancedSdp(
        string projectId = "my-project",
        string locationId = "us-central1",
        string templateId = "my-template",
        string inspectTemplateName =
            "projects/my_project/locations/us-central1/inspectTemplates/inspect_template_id",
        string deidentifyTemplateName =
            "projects/my_project/locations/us-central1/deidentifyTemplates/de-identify_template_id"
    )
    {
        ModelArmorClient client = new ModelArmorClientBuilder
        {
            Endpoint = $"modelarmor.{locationId}.rep.googleapis.com",
        }.Build();

        LocationName parent = LocationName.FromProjectLocation(projectId, locationId);

        // Build the Model Armor template with Advanced SDP Filter.

        // Note: If you specify only Inspect template, Model Armor reports the filter matches if
        // sensitive data is detected. If you specify Inspect template and De-identify template, Model
        // Armor returns the de-identified sensitive data and sanitized version of prompts or
        // responses in the deidentifyResult.data.text field of the finding.
        SdpAdvancedConfig advancedSdpConfig = new SdpAdvancedConfig
        {
            InspectTemplate = inspectTemplateName,
            DeidentifyTemplate = deidentifyTemplateName,
        };

        SdpFilterSettings sdpSettings = new SdpFilterSettings
        {
            AdvancedConfig = advancedSdpConfig,
        };

        FilterConfig filterConfig = new FilterConfig { SdpSettings = sdpSettings };
        Template template = new Template { FilterConfig = filterConfig };

        CreateTemplateRequest request = new CreateTemplateRequest
        {
            ParentAsLocationName = parent,
            TemplateId = templateId,
            Template = template,
        };

        Template createdTemplate = client.CreateTemplate(request);

        Console.WriteLine($"Created template with Advanced SDP filter: {createdTemplate.Name}");

        return createdTemplate;
    }
}

Go

이 코드를 실행하려면 먼저 Go 개발 환경을 설정하고 Model Armor Go SDK를 설치합니다.


import (
	"context"
	"fmt"
	"io"

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

// createModelArmorTemplateWithAdvancedSDP method creates a
// new Model Armor template with advanced SDP settings,
// including inspect and deidentify templates.
//
// w io.Writer: The writer to use for logging.
// projectID string: The ID of the Google Cloud project.
// locationID string: The ID of the Google Cloud location.
// templateID string: The ID of the template to create.
// inspectTemplate string: The ID of the inspect template to use.
// deidentifyTemplate string: The ID of the deidentify template to use.
func createModelArmorTemplateWithAdvancedSDP(w io.Writer, projectID, locationID, templateID, inspectTemplate, deidentifyTemplate string) error {
	ctx := context.Background()

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

	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)

	// Build the Model Armor template with your preferred filters.
	template := &modelarmorpb.Template{
		FilterConfig: &modelarmorpb.FilterConfig{
			RaiSettings: &modelarmorpb.RaiFilterSettings{
				RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{
					{
						FilterType:      modelarmorpb.RaiFilterType_DANGEROUS,
						ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH,
					},
					{
						FilterType:      modelarmorpb.RaiFilterType_HARASSMENT,
						ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE,
					},
					{
						FilterType:      modelarmorpb.RaiFilterType_HATE_SPEECH,
						ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH,
					},
					{
						FilterType:      modelarmorpb.RaiFilterType_SEXUALLY_EXPLICIT,
						ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH,
					},
				},
			},
			SdpSettings: &modelarmorpb.SdpFilterSettings{
				SdpConfiguration: &modelarmorpb.SdpFilterSettings_AdvancedConfig{
					AdvancedConfig: &modelarmorpb.SdpAdvancedConfig{
						InspectTemplate:    inspectTemplate,
						DeidentifyTemplate: deidentifyTemplate,
					},
				},
			},
		},
	}

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

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

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

	return err
}

자바

이 코드를 실행하려면 먼저 Java 개발 환경을 설정하고 Model Armor Java SDK를 설치합니다.


import com.google.cloud.modelarmor.v1.CreateTemplateRequest;
import com.google.cloud.modelarmor.v1.FilterConfig;
import com.google.cloud.modelarmor.v1.LocationName;
import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.SdpAdvancedConfig;
import com.google.cloud.modelarmor.v1.SdpFilterSettings;
import com.google.cloud.modelarmor.v1.Template;
import com.google.privacy.dlp.v2.DeidentifyTemplateName;
import com.google.privacy.dlp.v2.InspectTemplateName;
import java.io.IOException;

public class CreateTemplateWithAdvancedSdp {

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

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

    createTemplateWithAdvancedSdp(projectId, locationId, templateId, inspectTemplateId,
        deidentifyTemplateId);
  }

  public static Template createTemplateWithAdvancedSdp(String projectId, String locationId,
      String templateId, String inspectTemplateId, String deidentifyTemplateId) throws IOException {

    // Construct the API endpoint URL.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);
    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder().setEndpoint(apiEndpoint)
        .build();

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

      String inspectTemplateName = InspectTemplateName
          .ofProjectLocationInspectTemplateName(projectId, locationId, inspectTemplateId)
          .toString();

      String deidentifyTemplateName = DeidentifyTemplateName
          .ofProjectLocationDeidentifyTemplateName(projectId, locationId, deidentifyTemplateId)
          .toString();

      // Build the Model Armor template with Advanced SDP Filter.

      // Note: If you specify only Inspect template, Model Armor reports the filter matches if
      // sensitive data is detected. If you specify Inspect template and De-identify template, Model
      // Armor returns the de-identified sensitive data and sanitized version of prompts or
      // responses in the deidentifyResult.data.text field of the finding.
      SdpAdvancedConfig advancedSdpConfig =
          SdpAdvancedConfig.newBuilder()
              .setInspectTemplate(inspectTemplateName)
              .setDeidentifyTemplate(deidentifyTemplateName)
              .build();

      SdpFilterSettings sdpSettings = SdpFilterSettings.newBuilder()
          .setAdvancedConfig(advancedSdpConfig).build();

      FilterConfig modelArmorFilter = FilterConfig.newBuilder().setSdpSettings(sdpSettings).build();

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

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

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

      return createdTemplate;
    }
  }
}

Node.js

이 코드를 실행하려면 먼저 Node.js 개발 환경을 설정하고 Model Armor Node.js SDK를 설치합니다.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'your-project-id';
// const locationId = 'us-central1';
// const templateId = 'template-id';
// const inspectTemplate = `projects/${projectId}/locations/${locationId}/inspectTemplates/inspect-template-id`;
// const deidentifyTemplate = `projects/${projectId}/locations/${locationId}/deidentifyTemplates/deidentify-template-id`;

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

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

const RaiFilterType = protos.google.cloud.modelarmor.v1.RaiFilterType;
const DetectionConfidenceLevel =
  protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel;

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

// Configuration for the template with advanced SDP settings
const templateConfig = {
  filterConfig: {
    raiSettings: {
      raiFilters: [
        {
          filterType: RaiFilterType.DANGEROUS,
          confidenceLevel: DetectionConfidenceLevel.HIGH,
        },
        {
          filterType: RaiFilterType.HARASSMENT,
          confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE,
        },
        {
          filterType: RaiFilterType.HATE_SPEECH,
          confidenceLevel: DetectionConfidenceLevel.HIGH,
        },
        {
          filterType: RaiFilterType.SEXUALLY_EXPLICIT,
          confidenceLevel: DetectionConfidenceLevel.HIGH,
        },
      ],
    },
    sdpSettings: {
      advancedConfig: {
        inspectTemplate: inspectTemplate,
        deidentifyTemplate: deidentifyTemplate,
      },
    },
  },
};

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

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

PHP

이 코드를 실행하려면 먼저 PHP 개발 환경을 설정하고 Model Armor PHP SDK를 설치합니다.

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\SdpAdvancedConfig;
use Google\Cloud\ModelArmor\V1\Template;
use Google\Cloud\ModelArmor\V1\FilterConfig;
use Google\Cloud\ModelArmor\V1\CreateTemplateRequest;
use Google\Cloud\ModelArmor\V1\SdpFilterSettings;

/**
 * Create a Model Armor template with an Advanced SDP Filter.
 *
 * @param string $projectId The ID of the project (e.g. 'my-project').
 * @param string $locationId The ID of the location (e.g. 'us-central1').
 * @param string $templateId The ID of the template (e.g. 'my-template').
 * @param string $inspectTemplate The resource name of the inspect template.
          (e.g. 'organizations/{organization}/inspectTemplates/{inspect_template}')
 * @param string $deidentifyTemplate The resource name of the de-identify template.
          (e.g. 'organizations/{organization}/deidentifyTemplates/{deidentify_template}')
 */
function create_template_with_advanced_sdp(
    string $projectId,
    string $locationId,
    string $templateId,
    string $inspectTemplate,
    string $deidentifyTemplate
): void {
    $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
    $client = new ModelArmorClient($options);
    $parent = $client->locationName($projectId, $locationId);

    // Build the Model Armor template with Advanced SDP Filter.

    // Note: If you specify only Inspect template, Model Armor reports the filter matches if
    // sensitive data is detected. If you specify Inspect template and De-identify template, Model
    // Armor returns the de-identified sensitive data and sanitized version of prompts or
    // responses in the deidentifyResult.data.text field of the finding.
    $sdpAdvancedConfig = (new SdpAdvancedConfig())
        ->setInspectTemplate($inspectTemplate)
        ->setDeidentifyTemplate($deidentifyTemplate);

    $sdpSettings = (new SdpFilterSettings())->setAdvancedConfig($sdpAdvancedConfig);

    $templateFilterConfig = (new FilterConfig())
        ->setSdpSettings($sdpSettings);

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

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

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

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

Python

이 코드를 실행하려면 Python 개발 환경을 설정하고 Model Armor Python SDK를 설치합니다.


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

# TODO(Developer): Uncomment these variables.
# project_id = "YOUR_PROJECT_ID"
# location_id = "us-central1"
# template_id = "template_id"
# inspect_template = f"projects/{project_id}/inspectTemplates/{inspect_template_id}"
# deidentify_template = f"projects/{project_id}/deidentifyTemplates/{deidentify_template_id}"

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

parent = f"projects/{project_id}/locations/{location_id}"

# Build the Model Armor template with your preferred filters.
# For more details on filters, please refer to the following doc:
# https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
template = modelarmor_v1.Template(
    filter_config=modelarmor_v1.FilterConfig(
        rai_settings=modelarmor_v1.RaiFilterSettings(
            rai_filters=[
                modelarmor_v1.RaiFilterSettings.RaiFilter(
                    filter_type=modelarmor_v1.RaiFilterType.DANGEROUS,
                    confidence_level=modelarmor_v1.DetectionConfidenceLevel.HIGH,
                ),
                modelarmor_v1.RaiFilterSettings.RaiFilter(
                    filter_type=modelarmor_v1.RaiFilterType.HARASSMENT,
                    confidence_level=modelarmor_v1.DetectionConfidenceLevel.MEDIUM_AND_ABOVE,
                ),
                modelarmor_v1.RaiFilterSettings.RaiFilter(
                    filter_type=modelarmor_v1.RaiFilterType.HATE_SPEECH,
                    confidence_level=modelarmor_v1.DetectionConfidenceLevel.HIGH,
                ),
                modelarmor_v1.RaiFilterSettings.RaiFilter(
                    filter_type=modelarmor_v1.RaiFilterType.SEXUALLY_EXPLICIT,
                    confidence_level=modelarmor_v1.DetectionConfidenceLevel.HIGH,
                ),
            ]
        ),
        sdp_settings=modelarmor_v1.SdpFilterSettings(
            advanced_config=modelarmor_v1.SdpAdvancedConfig(
                inspect_template=inspect_template,
                deidentify_template=deidentify_template,
            )
        ),
    ),
)

# Prepare the request for creating the template.
create_template = modelarmor_v1.CreateTemplateRequest(
    parent=parent, template_id=template_id, template=template
)

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

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

만든 템플릿을 사용하여 프롬프트를 검사합니다. 예를 들면 다음과 같습니다.

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을 사용할 때 발생하는 위험을 줄이려면 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를 설치합니다.

using Google.Cloud.ModelArmor.V1;
using System;

namespace ModelArmor.Samples
{
    public class SanitizeModelResponseSample
    {
        public SanitizeModelResponseResponse SanitizeModelResponse(
            string projectId = "my-project",
            string locationId = "us-central1",
            string templateId = "my-template",
            string modelResponse = "Unsanitized model output"
        )
        {
            // Endpoint to call the Model Armor server.
            ModelArmorClientBuilder clientBuilder = new ModelArmorClientBuilder
            {
                Endpoint = $"modelarmor.{locationId}.rep.googleapis.com",
            };

            // Create the client.
            ModelArmorClient client = clientBuilder.Build();

            // Build the resource name of the template.
            TemplateName templateName = TemplateName.FromProjectLocationTemplate(
                projectId,
                locationId,
                templateId
            );

            // Prepare the request.
            SanitizeModelResponseRequest request = new SanitizeModelResponseRequest
            {
                TemplateName = templateName,
                ModelResponseData = new DataItem { Text = modelResponse },
            };

            // Send the request and get the response.
            SanitizeModelResponseResponse response = client.SanitizeModelResponse(request);

            // Print the sanitization result
            Console.WriteLine($"Result for the provided model response: {response}");

            return response;
        }
    }
}

Go

이 코드를 실행하려면 먼저 Go 개발 환경을 설정하고 Model Armor Go SDK를 설치합니다.


import (
	"context"
	"fmt"
	"io"

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

// sanitizeModelResponse method sanitizes a model
// response based on the project, location, and template settings.
//
// w io.Writer: The writer to use for logging.
// projectID string: The ID of the project.
// locationID string: The ID of the location.
// templateID string: The ID of the template.
// modelResponse string: The model response to sanitize.
func sanitizeModelResponse(w io.Writer, projectID, locationID, templateID, modelResponse string) error {
	ctx := context.Background()

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

	// Initialize request argument(s)
	modelResponseData := &modelarmorpb.DataItem{
		DataItem: &modelarmorpb.DataItem_Text{
			Text: modelResponse,
		},
	}

	// Prepare request for sanitizing model response.
	req := &modelarmorpb.SanitizeModelResponseRequest{
		Name:              fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID),
		ModelResponseData: modelResponseData,
	}

	// Sanitize the model response.
	response, err := client.SanitizeModelResponse(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to sanitize model response with user prompt for template %s: %w", templateID, err)
	}

	// Sanitization Result.
	fmt.Fprintf(w, "Sanitization Result: %v\n", response)

	return nil
}

자바

이 코드를 실행하려면 먼저 Java 개발 환경을 설정하고 Model Armor Java SDK를 설치합니다.


import com.google.cloud.modelarmor.v1.DataItem;
import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.SanitizeModelResponseRequest;
import com.google.cloud.modelarmor.v1.SanitizeModelResponseResponse;
import com.google.cloud.modelarmor.v1.TemplateName;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;

public class SanitizeModelResponse {

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

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

    sanitizeModelResponse(projectId, locationId, templateId, modelResponse);
  }

  public static SanitizeModelResponseResponse sanitizeModelResponse(String projectId,
      String locationId, String templateId, String modelResponse) throws IOException {

    // Endpoint to call the Model Armor server.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);
    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder().setEndpoint(apiEndpoint)
        .build();

    try (ModelArmorClient client = ModelArmorClient.create(modelArmorSettings)) {
      // Build the resource name of the template.
      String name = TemplateName.of(projectId, locationId, templateId).toString();

      // Prepare the request.
      SanitizeModelResponseRequest request = 
          SanitizeModelResponseRequest.newBuilder()
            .setName(name)
            .setModelResponseData(
              DataItem.newBuilder().setText(modelResponse)
              .build())
            .build();

      SanitizeModelResponseResponse response = client.sanitizeModelResponse(request);
      System.out.println("Result for the provided model response: "
          + JsonFormat.printer().print(response.getSanitizationResult()));

      return response;
    }
  }
}

Node.js

이 코드를 실행하려면 먼저 Node.js 개발 환경을 설정하고 Model Armor Node.js SDK를 설치합니다.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = process.env.PROJECT_ID || 'your-project-id';
// const locationId = process.env.LOCATION_ID || 'us-central1';
// const templateId = process.env.TEMPLATE_ID || 'template-id';
// const modelResponse = 'unsanitized model output';
const {ModelArmorClient} = require('@google-cloud/modelarmor').v1;

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

const request = {
  name: `projects/${projectId}/locations/${locationId}/templates/${templateId}`,
  modelResponseData: {
    text: modelResponse,
  },
};

const [response] = await client.sanitizeModelResponse(request);
console.log(JSON.stringify(response, null, 2));

PHP

이 코드를 실행하려면 먼저 PHP 개발 환경을 설정하고 Model Armor PHP SDK를 설치합니다.

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\SanitizeModelResponseRequest;
use Google\Cloud\ModelArmor\V1\DataItem;

/**
 * Sanitizes a model response using the specified template.
 *
 * @param string $projectId The ID of your Google Cloud Platform project (e.g. 'my-project').
 * @param string $locationId The ID of the location where the template is stored (e.g. 'us-central1').
 * @param string $templateId The ID of the template (e.g. 'my-template').
 * @param string $modelResponse The model response to sanitize (e.g. 'my-model-response').
 */
function sanitize_model_response(
    string $projectId,
    string $locationId,
    string $templateId,
    string $modelResponse
): void {
    $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
    $client = new ModelArmorClient($options);

    $modelResponseRequest = (new SanitizeModelResponseRequest())
        ->setName("projects/$projectId/locations/$locationId/templates/$templateId")
        ->setModelResponseData((new DataItem())->setText($modelResponse));

    $response = $client->sanitizeModelResponse($modelResponseRequest);

    printf('Result for Model Response Sanitization: %s' . PHP_EOL, $response->serializeToJsonString());
}

Python

이 코드를 실행하려면 Python 개발 환경을 설정하고 Model Armor Python SDK를 설치합니다.


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

# TODO(Developer): Uncomment these variables.
# project_id = "YOUR_PROJECT_ID"
# location_id = "us-central1"
# template_id = "template_id"
# model_response = "The model response data to sanitize"

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

# Initialize request argument(s)
model_response_data = modelarmor_v1.DataItem(text=model_response)

# Prepare request for sanitizing model response.
request = modelarmor_v1.SanitizeModelResponseRequest(
    name=f"projects/{project_id}/locations/{location_id}/templates/{template_id}",
    model_response_data=model_response_data,
)

# Sanitize the model response.
response = client.sanitize_model_response(request=request)

# Sanitization Result.
print(response)

다국어 감지가 사용 설정된 모델 응답 정리

개별 응답마다 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 요청을 하는 프로젝트의 서비스 계정입니다.

다음 단계