Model Armor 템플릿 만들기 및 관리

Model Armor 템플릿을 사용하여 AI 애플리케이션의 프롬프트와 응답 검사를 구성합니다. 템플릿은 여러 안전 및 보안 카테고리에 맞춤설정된 필터와 기준점을 제공합니다. 이 문서에서는 Model Armor 템플릿을 만들고 관리하는 방법을 설명합니다. 자세한 내용은 Model Armor 템플릿을 참고하세요.

시작하기 전에

시작하기 전에 다음 작업을 완료하세요.

필수 권한 얻기

Model Armor 템플릿을 관리하는 데 필요한 권한을 얻으려면 관리자에게 Model Armor 템플릿에 대한 Model Armor 관리자 (roles/modelarmor.admin) IAM 역할을 부여해 달라고 요청하세요. 역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

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

API 사용 설정

Model Armor를 사용하려면 먼저 Model Armor API를 사용 설정해야 합니다.

콘솔

  1. Enable the Model Armor API.

    Enable the API

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

gcloud

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

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 다음 명령어를 실행하여 Model Armor 서비스의 API 엔드포인트를 설정합니다.

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

    LOCATION을 Model Armor를 사용하려는 리전으로 바꿉니다.

  3. 다음 명령어를 실행하여 Model Armor를 사용 설정합니다.

      gcloud services enable modelarmor.googleapis.com --project=PROJECT_ID
       

    PROJECT_ID를 프로젝트의 ID로 바꿉니다.

    Model Armor 템플릿 만들기

    Model Armor 템플릿은 Model Armor가 안전 및 보안 위험에 대해 프롬프트와 대답을 검사하는 데 사용하는 구체적인 필터와 기준점을 정의합니다. 모델 아머 템플릿을 만들려면 다음 단계를 따르세요.

    콘솔

    1. Google Cloud 콘솔에서 Model Armor 페이지로 이동합니다.

      Model Armor로 이동

    2. Model Armor를 활성화한 프로젝트가 표시되었는지 확인합니다.

    3. Model Armor 페이지에서 템플릿 만들기를 클릭합니다. 템플릿 만들기 페이지가 표시됩니다.

    4. 템플릿 ID를 지정합니다. 템플릿 ID에는 문자, 숫자, 하이픈을 사용할 수 있습니다. 63자를 초과하거나 공백을 포함하거나 하이픈으로 시작할 수 없습니다.

    5. Model Armor 템플릿이 실행될 리전을 선택합니다. 리전은 나중에 변경할 수 없습니다.

    6. 선택사항: 라벨을 추가합니다. 라벨은 관련 템플릿을 그룹으로 묶는 데 사용할 수 있는 키-값 쌍입니다.

    7. 감지 섹션에서 감지 설정을 구성합니다.

    8. (선택사항) Sensitive Data Protection 감지를 선택한 경우 Sensitive Data Protection 설정을 구성해야 합니다.

    9. 책임감 있는 AI 섹션에서 각 콘텐츠 필터의 신뢰도 수준을 설정합니다.

    10. 선택사항: 로깅 구성 섹션에서 로깅을 구성할 작업을 선택합니다.

    11. 선택사항: 다국어 감지 설정을 사용하려면 다국어 지원 사용 설정을 선택합니다.

    12. 만들기를 클릭합니다.

    gcloud

    다음 명령어를 실행합니다.

     gcloud model-armor templates create TEMPLATE_ID --project=PROJECT_ID --location=LOCATION \
         --rai-settings-filters='[{ "filterType": "HATE_SPEECH", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "HARASSMENT", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "SEXUALLY_EXPLICIT", "confidenceLevel": "MEDIUM_AND_ABOVE" }]' \
         --basic-config-filter-enforcement=enabled  \
         --pi-and-jailbreak-filter-settings-enforcement=enabled \
         --pi-and-jailbreak-filter-settings-confidence-level=LOW_AND_ABOVE \
         --malicious-uri-filter-settings-enforcement=enabled \
         --template-metadata-custom-llm-response-safety-error-code=798 \
         --template-metadata-custom-llm-response-safety-error-message="test template llm response evaluation failed" \
         --template-metadata-custom-prompt-safety-error-code=799 \
         --template-metadata-custom-prompt-safety-error-message="test template prompt evaluation failed" \
         --template-metadata-ignore-partial-invocation-failures \
         --template-metadata-log-operations \
         --template-metadata-log-sanitize-operations
    

    다음을 바꿉니다.

    • LOCATION: 템플릿의 위치입니다.
    • TEMPLATE_ID: 템플릿의 ID입니다.
    • PROJECT_ID: 템플릿이 속한 프로젝트의 ID입니다.

    REST

    다음 명령어를 사용하여 새 Model Armor 템플릿을 만듭니다.

      curl -X POST \
        -d "{'FILTER_CONFIG': {} }" \
        -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=TEMPLATE_ID"
    

    다음을 바꿉니다.

    • FILTER_CONFIG: 템플릿의 필터 구성입니다.
    • PROJECT_ID: 템플릿이 속한 프로젝트의 ID입니다.
    • TEMPLATE_ID: 생성할 템플릿의 ID입니다.
    • LOCATION: 템플릿의 위치입니다.

    다음 예시는 Model Armor 템플릿 구성을 보여줍니다. 이 예에서는 다양한 신뢰도 수준으로 증오심 표현, 괴롭힘, 위험한 콘텐츠, 음란물에 대해 책임감 있는 AI 필터가 구성되어 있습니다. 프롬프트 인젝션 및 탈옥 감지 필터가 LOW_AND_ABOVE 신뢰도 수준으로 사용 설정되어 있으므로 가능성이 낮음, 중간 또는 높음인 콘텐츠가 플래그 처리됩니다. 악성 URI 필터가 사용 설정되어 있습니다.

      export FILTER_CONFIG='{
       "filterConfig": {
        "raiSettings": {
         "raiFilters": [{
           "filterType": "HATE_SPEECH",
           "confidenceLevel": "MEDIUM_AND_ABOVE"
          }, {
          "filterType": "HARASSMENT",
          "confidenceLevel": "HIGH"
        }, {
          "filterType": "DANGEROUS",
          "confidenceLevel": "MEDIUM_AND_ABOVE"
        },{
          "filterType": "SEXUALLY_EXPLICIT",
          "confidenceLevel": "MEDIUM_AND_ABOVE"
        }]
      },
    
      "piAndJailbreakFilterSettings": {
        "filterEnforcement": "ENABLED",
        "confidenceLevel": "LOW_AND_ABOVE"
      },
      "maliciousUriFilterSettings": {
        "filterEnforcement": "ENABLED"
      }
     }
    }'
    
    curl -X POST \
     -d "$FILTER_CONFIG" \
     -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_ID/templates?template_id=TEMPLATE_ID"
    

    다국어 감지를 사용 설정한 상태로 Model Armor 템플릿을 만들려면 명령어에 TEMPLATE_CONFIG 파라미터를 전달해야 합니다. 이 파라미터는 언어 감지 설정에 대한 구성을 정의합니다.

    다음 명령어를 사용하여 다국어 감지가 사용 설정된 새로운 Model Armor 템플릿을 만듭니다.

    curl -X POST \
        -d "{'TEMPLATE_CONFIG': {} }" \
        -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=TEMPLATE_ID"
    

    다음 예시는 다국어 감지가 사용 설정된 Model Armor 템플릿 구성을 보여줍니다.

      export TEMPLATE_CONFIG='{
       "filterConfig": {
        "raiSettings": {
         "raiFilters": [{
           "filterType": "HATE_SPEECH",
           "confidenceLevel": "MEDIUM_AND_ABOVE"
          }, {
          "filterType": "HARASSMENT",
          "confidenceLevel": "HIGH"
        }, {
          "filterType": "DANGEROUS",
          "confidenceLevel": "MEDIUM_AND_ABOVE"
        },{
          "filterType": "SEXUALLY_EXPLICIT",
          "confidenceLevel": "MEDIUM_AND_ABOVE"
        }]
      },
    
      "piAndJailbreakFilterSettings": {
        "filterEnforcement": "ENABLED",
        "confidenceLevel": "LOW_AND_ABOVE"
      },
      "maliciousUriFilterSettings": {
        "filterEnforcement": "ENABLED"
      }
     },
     "templateMetadata": {
        "multiLanguageDetectionMetadata": {
          "enableMultiLanguageDetection": true
        }
      }
    }'
    
    curl -X POST \
     -d "$TEMPLATE_CONFIG"  \
     -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_ID/templates?template_id=TEMPLATE_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"
    )
    
    // createModelArmorTemplate method creates a new
    // Model Armor template with the provided 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 createModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error {
    	ctx := context.Background()
    
    	// Create the call options
    	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()
    
    	// 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{
    			PiAndJailbreakFilterSettings: &modelarmorpb.PiAndJailbreakFilterSettings{
    				FilterEnforcement: modelarmorpb.PiAndJailbreakFilterSettings_ENABLED,
    				ConfidenceLevel:   modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE,
    			},
    			MaliciousUriFilterSettings: &modelarmorpb.MaliciousUriFilterSettings{
    				FilterEnforcement: modelarmorpb.MaliciousUriFilterSettings_ENABLED,
    			},
    		},
    	}
    	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)
    
    	// 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: %v", err)
    	}
    
    	// Print the new template name using fmt.Fprintf with the io.Writer.
    	fmt.Fprintf(w, "Created template: %s\n", response.Name)
    
    	return err
    }
    

    자바

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

    
    import com.google.cloud.modelarmor.v1.CreateTemplateRequest;
    import com.google.cloud.modelarmor.v1.DetectionConfidenceLevel;
    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.RaiFilterSettings;
    import com.google.cloud.modelarmor.v1.RaiFilterSettings.RaiFilter;
    import com.google.cloud.modelarmor.v1.RaiFilterType;
    import com.google.cloud.modelarmor.v1.Template;
    import java.io.IOException;
    import java.util.List;
    
    public class CreateTemplate {
    
      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";
    
        createTemplate(projectId, locationId, templateId);
      }
    
      public static Template createTemplate(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 Responsible AI filter with multiple categories and their confidence
          // levels.
          RaiFilterSettings raiFilterSettings = RaiFilterSettings.newBuilder()
              .addAllRaiFilters(
                  List.of(
                      RaiFilter.newBuilder()
                          .setFilterType(RaiFilterType.DANGEROUS)
                          .setConfidenceLevel(DetectionConfidenceLevel.HIGH)
                          .build(),
                      RaiFilter.newBuilder()
                          .setFilterType(RaiFilterType.HATE_SPEECH)
                          .setConfidenceLevel(DetectionConfidenceLevel.HIGH)
                          .build(),
                      RaiFilter.newBuilder()
                          .setFilterType(RaiFilterType.SEXUALLY_EXPLICIT)
                          .setConfidenceLevel(DetectionConfidenceLevel.LOW_AND_ABOVE)
                          .build(),
                      RaiFilter.newBuilder()
                          .setFilterType(RaiFilterType.HARASSMENT)
                          .setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
                          .build()))
              .build();
    
          FilterConfig modelArmorFilter = FilterConfig.newBuilder()
              .setRaiSettings(raiFilterSettings)
              .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: " + 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 = 'your-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;
    
    // Instantiates a client
    const client = new ModelArmorClient({
      apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`,
    });
    
    /**  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
     */
    const templateConfig = {
      filterConfig: {
        raiSettings: {
          raiFilters: [
            {
              filterType:
                protos.google.cloud.modelarmor.v1.RaiFilterType.HATE_SPEECH,
              confidenceLevel:
                protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel.HIGH,
            },
            {
              filterType:
                protos.google.cloud.modelarmor.v1.RaiFilterType.SEXUALLY_EXPLICIT,
              confidenceLevel:
                protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                  .MEDIUM_AND_ABOVE,
            },
          ],
        },
      },
    };
    
    // 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\Template;
    use Google\Cloud\ModelArmor\V1\CreateTemplateRequest;
    use Google\Cloud\ModelArmor\V1\FilterConfig;
    use Google\Cloud\ModelArmor\V1\RaiFilterType;
    use Google\Cloud\ModelArmor\V1\RaiFilterSettings;
    use Google\Cloud\ModelArmor\V1\RaiFilterSettings\RaiFilter;
    use Google\Cloud\ModelArmor\V1\DetectionConfidenceLevel;
    
    /**
     * Create a Model Armor template.
     *
     * @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(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 preferred filters.
         * For more details on filters, refer to:
         * https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
         */
    
        $raiFilters = [
            (new RaiFilter())
                ->setFilterType(RaiFilterType::DANGEROUS)
                ->setConfidenceLevel(DetectionConfidenceLevel::HIGH),
            (new RaiFilter())
                ->setFilterType(RaiFilterType::HATE_SPEECH)
                ->setConfidenceLevel(DetectionConfidenceLevel::HIGH),
            (new RaiFilter())
                ->setFilterType(RaiFilterType::SEXUALLY_EXPLICIT)
                ->setConfidenceLevel(DetectionConfidenceLevel::LOW_AND_ABOVE),
            (new RaiFilter())
                ->setFilterType(RaiFilterType::HARASSMENT)
                ->setConfidenceLevel(DetectionConfidenceLevel::MEDIUM_AND_ABOVE),
        ];
    
        $raiFilterSetting = (new RaiFilterSettings())->setRaiFilters($raiFilters);
    
        $templateFilterConfig = (new FilterConfig())->setRaiSettings($raiFilterSetting);
    
        $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-google-cloud-project-id"
    # location_id = "us-central1"
    # template_id = "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"
        ),
    )
    
    # 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(
            pi_and_jailbreak_filter_settings=modelarmor_v1.PiAndJailbreakFilterSettings(
                filter_enforcement=modelarmor_v1.PiAndJailbreakFilterSettings.PiAndJailbreakFilterEnforcement.ENABLED,
                confidence_level=modelarmor_v1.DetectionConfidenceLevel.MEDIUM_AND_ABOVE,
            ),
            malicious_uri_filter_settings=modelarmor_v1.MaliciousUriFilterSettings(
                filter_enforcement=modelarmor_v1.MaliciousUriFilterSettings.MaliciousUriFilterEnforcement.ENABLED,
            ),
        ),
    )
    
    # Prepare the request for creating the template.
    request = modelarmor_v1.CreateTemplateRequest(
        parent=f"projects/{project_id}/locations/{location_id}",
        template_id=template_id,
        template=template,
    )
    
    # Create the template.
    response = client.create_template(request=request)
    
    # Print the new template name.
    print(f"Created template: {response.name}")
    

    감지 구성

    감지는 Model Armor가 프롬프트와 대답에 대해 실행하는 구체적인 검사입니다. Model Armor는 탐지를 구성할 수 있는 유연한 시스템을 제공하므로 AI 애플리케이션의 보호 수준을 맞춤설정할 수 있습니다. 템플릿을 만들 때 감지를 구성합니다. Model Armor는 프롬프트와 대답에 대해 다음과 같은 감지 검사를 실행합니다.

    • 악의적인 URL 감지: 사용자 또는 시스템에 피해를 주도록 설계된 웹 주소(URL)를 식별합니다. 이러한 URL은 피싱 사이트, 멀웨어 다운로드 또는 기타 사이버 공격으로 연결될 수 있습니다. 자세한 내용은 악의적인 URL 감지를 참조하세요.

    • 프롬프트 인젝션 및 탈옥 감지: 프롬프트에서 악의적인 콘텐츠 및 탈옥 시도를 감지합니다. 더 엄격하게 적용하려는 경우 신뢰도 수준을 낮음 이상으로 설정하면 프롬프트 인젝션 및 탈옥 시도일 가능성이 높은 대부분의 콘텐츠를 감지할 수 있습니다. 자세한 내용은 프롬프트 인젝션 및 탈옥 감지를 참조하세요.

    • Sensitive Data Protection: 민감한 정보를 탐지하며 프롬프트 인젝션과 같은 공격으로 인한 우발적인 노출을 방지할 수 있습니다. 자세한 내용은 Sensitive Data Protection을 참조하세요.

    Sensitive Data Protection 설정

    Model Armor는 민감한 정보 보호를 활용하여 LLM 상호작용에서 민감한 정보의 노출을 식별하고 방지합니다. 자세한 내용은 Sensitive Data Protection을 참고하세요.

    Model Armor는 민감한 정보 보호를 구성하기 위한 두 가지 모드를 제공합니다.

    • 기본: 사전 정의된 infoType을 사용하여 민감한 정보를 감지하는 간단한 접근 방식입니다. 사전 정의된 infoType에 대한 자세한 내용은 기본 Sensitive Data Protection 구성을 참고하세요.

    • 고급: Sensitive Data Protection 서비스에 정의된 검사 템플릿을 민감한 정보 infoType의 단일 소스로 사용하는 구성 가능한 옵션입니다.

    고급 모드를 선택한 경우 다음 파라미터를 지정해야 합니다.

    • 검사 템플릿: 사용할 사전 정의된 또는 커스텀 감지기를 포함하여 검사 스캔 작업의 구성 정보를 저장하는 템플릿입니다. 템플릿 이름을 다음 형식으로 입력합니다. projects/projectName/locations/locationID/inspectTemplates/templateName

    • 선택 사항: 익명화 템플릿: infoType 및 구조화된 데이터 세트 변환을 포함하여 익명화 작업의 구성 정보를 저장하는 템플릿입니다. 익명화 템플릿의 식별자를 다음 형식으로 입력합니다. projects/projectName/locations/locationID/deidentifyTemplates/templateName

    Sensitive Data Protection에 검사 템플릿익명화 템플릿이 있는지 확인합니다. 템플릿이 다른 프로젝트에 있는 경우 Model Armor 서비스 에이전트에 해당 프로젝트에 대한 DLP 사용자 역할(roles/dlp.user) 및 DLP 리더 역할(roles/dlp.reader)이 부여되어야 합니다.

    신뢰도 수준 설정

    신뢰도 수준은 발견 사항이 콘텐츠 필터 유형과 일치할 가능성을 나타냅니다. 각 콘텐츠 필터의 신뢰도 수준을 설정할 수 있습니다. 가능한 값은 다음과 같습니다.

    • 없음: 콘텐츠 유형이 감지되지 않습니다.
    • 낮음 이상: 신뢰도 수준이 낮음, 중간 또는 높음인 콘텐츠가 감지됩니다.
    • 중간 이상: 신뢰도 수준이 중간 또는 높음인 콘텐츠가 감지됩니다.
    • 높음: 신뢰도 수준이 높은 콘텐츠가 감지됩니다.

    더 엄격하게 적용하려면 신뢰도 수준을 낮음 이상으로 설정하여 콘텐츠 필터 유형에 해당하는 대부분의 콘텐츠를 탐지하세요. 신뢰도 수준을 선택할 수도 있습니다.

    템플릿에서 포괄적인 로깅을 사용 설정하려면 Model Armor 감사 및 플랫폼 로깅을 참조하세요.

    Model Armor 템플릿 보기

    기존 템플릿을 확인하여 사용 가능한 구성을 파악하고 프롬프트 및 응답 검사 문제를 해결합니다.

    콘솔

    1. Google Cloud 콘솔에서 Model Armor 페이지로 이동합니다.

      Model Armor로 이동

    2. Model Armor를 활성화한 프로젝트가 표시되었는지 확인합니다. 프로젝트에 대해 생성된 템플릿이 나열된 Model Armor 페이지가 표시됩니다.

    3. 목록에서 템플릿을 클릭하여 세부정보를 확인합니다.

    gcloud

    다음 명령어를 실행합니다.

    gcloud model-armor templates describe TEMPLATE_ID --project=PROJECT_ID --location=LOCATION

    다음을 바꿉니다.

    • LOCATION: 템플릿의 위치입니다.
    • TEMPLATE_ID: 템플릿의 ID입니다.
    • PROJECT_ID: 템플릿이 속한 프로젝트의 ID입니다.

    REST

    다음 명령어를 실행합니다.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://modelarmor.LOCATION_ID.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID"

    다음을 바꿉니다.

    • PROJECT_ID: 템플릿이 속한 프로젝트의 ID입니다.
    • TEMPLATE_ID: 볼 템플릿의 ID입니다.
    • LOCATION: 템플릿의 위치입니다.

    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"
    )
    
    // getModelArmorTemplate method retrieves a Model Armor template.
    //
    // w io.Writer: The writer to use for logging.
    // projectID string: The ID of the project.
    // locationID string: The location of the template.
    // templateID string: The ID of the template.
    func getModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error {
    	ctx := context.Background()
    
    	// Create options for the 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()
    
    	// Initialize request arguments.
    	req := &modelarmorpb.GetTemplateRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID),
    	}
    
    	// Get the template.
    	response, err := client.GetTemplate(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to get template: %w", err)
    	}
    
    	// Print the template name using fmt.Fprintf with the io.Writer.
    	fmt.Fprintf(w, "Retrieved template: %s\n", response.Name)
    
    	return nil
    }
    

    자바

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

    
    import com.google.cloud.modelarmor.v1.ModelArmorClient;
    import com.google.cloud.modelarmor.v1.ModelArmorSettings;
    import com.google.cloud.modelarmor.v1.Template;
    import com.google.cloud.modelarmor.v1.TemplateName;
    import java.io.IOException;
    
    public class GetTemplate {
    
      public static void main(String[] args) throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String locationId = "your-location-id";
        String templateId = "your-template-id";
    
        getTemplate(projectId, locationId, templateId);
      }
    
      public static Template getTemplate(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)) {
          // Build the template name.
          String name = TemplateName.of(projectId, locationId, templateId).toString();
    
          // Get the template.
          Template template = client.getTemplate(name);
    
          // Find more details about Template object here:
          // https://cloud.google.com/security-command-center/docs/reference/model-armor/rest/v1/projects.locations.templates#Template
          System.out.printf("Retrieved template: %s\n", template.getName());
    
          return template;
        }
      }
    }
    

    Node.js

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

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const projectId = 'my-project';
    // const locationId = 'my-location';
    // const templateId = 'my-template';
    
    const name = `projects/${projectId}/locations/${locationId}/templates/${templateId}`;
    
    // Imports the Model Armor library
    const {ModelArmorClient} = require('@google-cloud/modelarmor').v1;
    
    // Instantiates a client
    const client = new ModelArmorClient({
      apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`,
    });
    
    const request = {
      name: name,
    };
    
    // Run request
    const [response] = await client.getTemplate(request);
    return response;

    PHP

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

    use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
    use Google\Cloud\ModelArmor\V1\GetTemplateRequest;
    
    /**
     * Gets a Model Armor 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').
     */
    function get_template(string $projectId, string $locationId, string $templateId): void
    {
        $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
        $client = new ModelArmorClient($options);
        $name = sprintf('projects/%s/locations/%s/templates/%s', $projectId, $locationId, $templateId);
    
        $getTemplateRequest = (new GetTemplateRequest())->setName($name);
    
        $response = $client->getTemplate($getTemplateRequest);
    
        printf('Template retrieved: %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(
        transport="rest",
        client_options=ClientOptions(
            api_endpoint=f"modelarmor.{location_id}.rep.googleapis.com"
        ),
    )
    
    # Initialize request arguments.
    request = modelarmor_v1.GetTemplateRequest(
        name=f"projects/{project_id}/locations/{location_id}/templates/{template_id}",
    )
    
    # Get the template.
    response = client.get_template(request=request)
    print(response.name)
    

    Model Armor 템플릿 업데이트

    AI 애플리케이션의 강력하고 효과적인 보안 태세를 유지하려면 템플릿을 정기적으로 업데이트하세요.

    콘솔

    1. Google Cloud 콘솔에서 Model Armor 페이지로 이동합니다.

      Model Armor로 이동

    2. Model Armor를 활성화한 프로젝트가 표시되었는지 확인합니다. 조직에 대해 생성된 템플릿이 나열된 Model Armor 페이지가 표시됩니다.

    3. 목록에서 업데이트하려는 템플릿을 클릭합니다. 템플릿 세부정보 페이지가 표시됩니다.

    4. 수정을 클릭합니다.

    5. 필요한 파라미터를 업데이트하고 저장을 클릭합니다.

    gcloud

    다음 명령어를 실행합니다.

    gcloud model-armor templates update TEMPLATE_ID --project=PROJECT_ID --location=LOCATION

    다음을 바꿉니다.

    • LOCATION: 템플릿의 위치입니다.
    • TEMPLATE_ID: 템플릿의 ID입니다.
    • PROJECT_ID: 템플릿이 속한 프로젝트의 ID입니다.

    REST

    다음 명령어를 실행합니다.

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    -d "$FILTER_CONFIG" \
      "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID?updateMask=FILTER_CONFIG"

    다음을 바꿉니다.

    • PROJECT_ID: 템플릿이 속한 프로젝트의 ID입니다.
    • LOCATION: 템플릿의 위치입니다.
    • TEMPLATE_ID: 템플릿의 ID입니다.
    • FILTER_CONFIG: 필터 구성의 JSON 표현입니다.

    다른 모든 필드는 변경할 수 없습니다. 템플릿 이름 업데이트 시도와 같이 다른 필드를 업데이트하려고 하면 오류가 발생합니다.

    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"
    )
    
    // updateModelArmorTemplate updates a Model Armor template.
    //
    // updateModelArmorTemplate method updates a Model Armor template.
    //
    // 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.
    func updateModelArmorTemplate(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()
    
    	// 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)
    	updatedTemplate := &modelarmorpb.Template{
    		Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID),
    		FilterConfig: &modelarmorpb.FilterConfig{
    			PiAndJailbreakFilterSettings: &modelarmorpb.PiAndJailbreakFilterSettings{
    				FilterEnforcement: modelarmorpb.PiAndJailbreakFilterSettings_ENABLED,
    				ConfidenceLevel:   modelarmorpb.DetectionConfidenceLevel_LOW_AND_ABOVE,
    			},
    			MaliciousUriFilterSettings: &modelarmorpb.MaliciousUriFilterSettings{
    				FilterEnforcement: modelarmorpb.MaliciousUriFilterSettings_ENABLED,
    			},
    		},
    	}
    
    	// Initialize request argument(s).
    	req := &modelarmorpb.UpdateTemplateRequest{
    		Template: updatedTemplate,
    	}
    
    	// Update the template.
    	response, err := client.UpdateTemplate(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to update template: %w", err)
    	}
    
    	// Print the updated filters in the template.
    	fmt.Fprintf(w, "Updated Filter Config: %+v\n", response.FilterConfig)
    
    	return nil
    }
    

    자바

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

    
    import com.google.cloud.modelarmor.v1.DetectionConfidenceLevel;
    import com.google.cloud.modelarmor.v1.FilterConfig;
    import com.google.cloud.modelarmor.v1.ModelArmorClient;
    import com.google.cloud.modelarmor.v1.ModelArmorSettings;
    import com.google.cloud.modelarmor.v1.RaiFilterSettings;
    import com.google.cloud.modelarmor.v1.RaiFilterSettings.RaiFilter;
    import com.google.cloud.modelarmor.v1.RaiFilterType;
    import com.google.cloud.modelarmor.v1.Template;
    import com.google.cloud.modelarmor.v1.TemplateName;
    import com.google.cloud.modelarmor.v1.UpdateTemplateRequest;
    import com.google.protobuf.FieldMask;
    import java.io.IOException;
    import java.util.List;
    
    public class UpdateTemplate {
    
      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";
    
        updateTemplate(projectId, locationId, templateId);
      }
    
      public static Template updateTemplate(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)) {
          // Get the template name.
          String name = TemplateName.of(projectId, locationId, templateId).toString();
    
          // Build the updated Model Armor template with modified 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
          RaiFilterSettings raiFilterSettings =
              RaiFilterSettings.newBuilder()
                  .addAllRaiFilters(
                      List.of(
                          RaiFilter.newBuilder()
                              .setFilterType(RaiFilterType.DANGEROUS)
                              .setConfidenceLevel(DetectionConfidenceLevel.HIGH)
                              .build(),
                          RaiFilter.newBuilder()
                              .setFilterType(RaiFilterType.HATE_SPEECH)
                              .setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
                              .build(),
                          RaiFilter.newBuilder()
                              .setFilterType(RaiFilterType.HARASSMENT)
                              .setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
                              .build(),
                          RaiFilter.newBuilder()
                              .setFilterType(RaiFilterType.SEXUALLY_EXPLICIT)
                              .setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
                              .build()))
                  .build();
    
          FilterConfig modelArmorFilter = FilterConfig.newBuilder()
              .setRaiSettings(raiFilterSettings)
              .build();
    
          Template template = Template.newBuilder()
              .setName(name)
              .setFilterConfig(modelArmorFilter)
              .build();
    
          // Create a field mask to specify which fields to update.
          // Ref: https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask
          FieldMask updateMask = FieldMask.newBuilder()
              .addPaths("filter_config.rai_settings")
              .build();
    
          UpdateTemplateRequest request = UpdateTemplateRequest.newBuilder()
              .setTemplate(template)
              .setUpdateMask(updateMask)
              .build();
    
          Template updatedTemplate = client.updateTemplate(request);
          System.out.println("Updated template: " + updatedTemplate.getName());
    
          return updatedTemplate;
        }
      }
    }
    

    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 modelarmor = require('@google-cloud/modelarmor');
    const {ModelArmorClient} = modelarmor.v1;
    const {protos} = modelarmor;
    
    const DetectionConfidenceLevel =
      protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel;
    const PiAndJailbreakFilterEnforcement =
      protos.google.cloud.modelarmor.v1.PiAndJailbreakFilterSettings
        .PiAndJailbreakFilterEnforcement;
    const MaliciousUriFilterEnforcement =
      protos.google.cloud.modelarmor.v1.MaliciousUriFilterSettings
        .MaliciousUriFilterEnforcement;
    
    // Instantiates a client
    const client = new ModelArmorClient({
      apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`,
    });
    
    // Build the updated template configuration
    const updatedTemplate = {
      name: `projects/${projectId}/locations/${locationId}/templates/${templateId}`,
      filterConfig: {
        piAndJailbreakFilterSettings: {
          filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED,
          confidenceLevel: DetectionConfidenceLevel.LOW_AND_ABOVE,
        },
        maliciousUriFilterSettings: {
          filterEnforcement: MaliciousUriFilterEnforcement.ENABLED,
        },
      },
    };
    
    const request = {
      template: updatedTemplate,
    };
    
    const [response] = await client.updateTemplate(request);
    return response;

    PHP

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

    use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
    use Google\Cloud\ModelArmor\V1\DetectionConfidenceLevel;
    use Google\Cloud\ModelArmor\V1\PiAndJailbreakFilterSettings\PiAndJailbreakFilterEnforcement;
    use Google\Cloud\ModelArmor\V1\PiAndJailbreakFilterSettings;
    use Google\Cloud\ModelArmor\V1\MaliciousUriFilterSettings;
    use Google\Cloud\ModelArmor\V1\UpdateTemplateRequest;
    use Google\Cloud\ModelArmor\V1\FilterConfig;
    use Google\Cloud\ModelArmor\V1\Template;
    
    /**
     * Updates a Model Armor template with the specified configuration.
     *
     * @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 update_template(string $projectId, string $locationId, string $templateId): void
    {
        $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
        $client = new ModelArmorClient($options);
    
        $templateFilterConfig = (new FilterConfig())
            ->setPiAndJailbreakFilterSettings(
                (new PiAndJailbreakFilterSettings())
                    ->setFilterEnforcement(PiAndJailbreakFilterEnforcement::ENABLED)
                    ->setConfidenceLevel(DetectionConfidenceLevel::LOW_AND_ABOVE)
            )
            ->setMaliciousUriFilterSettings(
                (new MaliciousUriFilterSettings())
                    ->setFilterEnforcement(PiAndJailbreakFilterEnforcement::ENABLED)
            );
    
        $template = (new Template())
            ->setFilterConfig($templateFilterConfig)
            ->setName("projects/$projectId/locations/$locationId/templates/$templateId");
    
        $updateTemplateRequest = (new UpdateTemplateRequest())->setTemplate($template);
    
        $response = $client->updateTemplate($updateTemplateRequest);
    
        printf('Template updated: %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(
        transport="rest",
        client_options=ClientOptions(
            api_endpoint=f"modelarmor.{location_id}.rep.googleapis.com"
        ),
    )
    
    # 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
    updated_template = modelarmor_v1.Template(
        name=f"projects/{project_id}/locations/{location_id}/templates/{template_id}",
        filter_config=modelarmor_v1.FilterConfig(
            pi_and_jailbreak_filter_settings=modelarmor_v1.PiAndJailbreakFilterSettings(
                filter_enforcement=modelarmor_v1.PiAndJailbreakFilterSettings.PiAndJailbreakFilterEnforcement.ENABLED,
                confidence_level=modelarmor_v1.DetectionConfidenceLevel.LOW_AND_ABOVE,
            ),
            malicious_uri_filter_settings=modelarmor_v1.MaliciousUriFilterSettings(
                filter_enforcement=modelarmor_v1.MaliciousUriFilterSettings.MaliciousUriFilterEnforcement.ENABLED,
            ),
        ),
    )
    
    # Initialize request argument(s).
    request = modelarmor_v1.UpdateTemplateRequest(template=updated_template)
    
    # Update the template.
    response = client.update_template(request=request)
    
    # Print the updated filters in the template.
    print(response.filter_config)
    

    Model Armor 템플릿 삭제

    더 이상 사용하지 않거나 새 템플릿으로 대체되거나 보안 정책이 변경된 경우 템플릿을 삭제합니다.

    콘솔

    1. Google Cloud 콘솔에서 Model Armor 페이지로 이동합니다.

      Model Armor로 이동

    2. Model Armor를 활성화한 프로젝트가 표시되었는지 확인합니다. 조직에 대해 생성된 템플릿이 나열된 Model Armor 페이지가 표시됩니다.

    3. 목록에서 삭제하려는 템플릿을 클릭합니다. 템플릿 세부정보 페이지가 표시됩니다.

    4. 삭제를 클릭합니다. 확인 대화상자가 표시됩니다.

    5. 템플릿 이름을 입력하여 삭제를 확인하고 삭제를 클릭합니다.

    gcloud

    다음 명령어를 실행합니다.

    gcloud model-armor templates delete TEMPLATE_ID --project=PROJECT_ID --location=LOCATION

    다음을 바꿉니다.

    • LOCATION: 템플릿의 위치입니다.
    • TEMPLATE_ID: 템플릿의 ID입니다.
    • PROJECT_ID: 템플릿이 속한 프로젝트의 ID입니다.

    REST

    다음 명령어를 실행합니다.

    curl -X DELETE \
    -H "Authorization: Bearer $(gcloud auth print-access-token)"  \
      "https://modelarmor.LOCATION_ID.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID"

    다음을 바꿉니다.

    • 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"
    )
    
    // deleteModelArmorTemplate method deletes a Model Armor template with the provided ID.
    //
    // 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 delete.
    func deleteModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error {
    	ctx := context.Background()
    
    	// Create option 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()
    
    	// Build the request for deleting the template.
    	req := &modelarmorpb.DeleteTemplateRequest{
    		Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID),
    	}
    
    	// Delete the template.
    	if err := client.DeleteTemplate(ctx, req); err != nil {
    		return fmt.Errorf("failed to delete template: %w", err)
    	}
    
    	// Print the success message using fmt.Fprintf with the io.Writer.
    	fmt.Fprintf(w, "Successfully deleted Model Armor template: %s\n", req.Name)
    
    	return err
    }
    

    자바

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

    
    import com.google.cloud.modelarmor.v1.ModelArmorClient;
    import com.google.cloud.modelarmor.v1.ModelArmorSettings;
    import com.google.cloud.modelarmor.v1.TemplateName;
    import java.io.IOException;
    
    public class DeleteTemplate {
    
      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";
    
        deleteTemplate(projectId, locationId, templateId);
      }
    
      public static void deleteTemplate(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 name = TemplateName.of(projectId, locationId, templateId).toString();
    
          // Note: Ensure that the template you are deleting isn't used by any models.
          client.deleteTemplate(name);
          System.out.println("Deleted template: " + name);
        }
      }
    }

    Node.js

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

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const projectId = 'my-project';
    // const locationId = 'us-central1';
    // const templateId = 'my-template';
    
    const name = `projects/${projectId}/locations/${locationId}/templates/${templateId}`;
    
    // Imports the Model Armor library
    const {ModelArmorClient} = require('@google-cloud/modelarmor');
    
    // Instantiates a client
    const client = new ModelArmorClient({
      apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`,
    });
    
    const response = await client.deleteTemplate({
      name: name,
    });
    return response;

    PHP

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

    use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
    use Google\Cloud\ModelArmor\V1\DeleteTemplateRequest;
    
    /**
     * Deletes a Model Armor template.
     *
     * @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 delete_template(string $projectId, string $locationId, string $templateId): void
    {
        $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
        $client = new ModelArmorClient($options);
        $templateName = sprintf('projects/%s/locations/%s/templates/%s', $projectId, $locationId, $templateId);
    
        $dltTemplateRequest = (new DeleteTemplateRequest())->setName($templateName);
    
        $client->deleteTemplate($dltTemplateRequest);
    
        printf('Deleted template: %s' . PHP_EOL, $templateName);
    }

    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(
        transport="rest",
        client_options=ClientOptions(
            api_endpoint=f"modelarmor.{location_id}.rep.googleapis.com"
        ),
    )
    
    # Build the request for deleting the template.
    request = modelarmor_v1.DeleteTemplateRequest(
        name=f"projects/{project_id}/locations/{location_id}/templates/{template_id}",
    )
    
    # Delete the template.
    client.delete_template(request=request)
    

    템플릿 메타데이터

    Model Armor 템플릿 메타데이터는 안전 및 보안 검사 처리, 오류 처리, 로깅 동작을 비롯한 Model Armor의 동작을 구성하는 데 도움이 됩니다.

    Model Armor의 템플릿 메타데이터에는 다음 필드가 포함됩니다.

    메타데이터 유형 설명
    multiLanguageDetection 불리언 다국어 감지를 사용 설정합니다.
    enforcement_type Enum

    강제 시행 유형을 정의합니다. 다음 중 한 가지 값을 사용합니다.

    • INSPECT_ONLY: 구성된 설정을 위반하는 요청을 검사하지만 차단하지는 않습니다.
    • INSPECT_AND_BLOCK: 구성된 설정을 위반하는 요청을 차단합니다.
    log_template_operations 불리언 템플릿 작업의 로깅을 사용 설정합니다.
    log_sanitize_operations 불리언 정리 작업의 로깅을 사용 설정합니다.

    다음 단계