안전 속성 구성

Vertex AI Gemini API는 안전 속성 목록과 구성된 차단 기준을 기반으로 안전하지 않은 콘텐츠를 차단합니다. 이 페이지에서는 주요 안전 개념을 간략하게 설명하고 각 안전 속성의 차단 기준을 구성하여 프롬프트와 응답이 차단되는 빈도를 제어하는 방법을 보여줍니다.

안전 속성 신뢰도 점수

Vertex AI Gemini API를 통해 처리된 콘텐츠는 '유해한 카테고리'와 민감하다고 간주될 수 있는 주제가 포함된 안전 속성 목록에 대해 평가됩니다. 이러한 안전 속성은 다음 표에 나와 있습니다.

안전 속성 정의

안전 속성 정의
증오심 표현 ID 또는 보호 속성을 대상으로 하는 부정적이거나 유해한 댓글
괴롭힘 다른 사람을 대상으로 위협하거나 괴롭히거나 모욕하는 악성 댓글
음란물 성행위 또는 기타 외설적인 콘텐츠에 대한 참조가 포함
위험한 콘텐츠 유해한 상품, 서비스, 활동 홍보 및 이에 대한 액세스 지원

안전 속성 가능성

각 안전 속성에는 0.0~1.0(소수점 1자리 반올림) 사이의 지정된 신뢰도 점수가 있으며 이 점수로 특정 카테고리에 속하는 입력이나 응답이 발생할 가능성을 나타냅니다.

다음 표의 신뢰도 점수는 안전 신뢰도 수준으로 반환됩니다.

확률 설명
무시할 수 있음 콘텐츠는 안전하지 않은 가능성이 무시할 만합니다.
낮음 콘텐츠는 안전하지 않을 가능성이 낮습니다.
보통 콘텐츠는 안전하지 않을 가능성이 중간 정도입니다.
높음 콘텐츠는 안전하지 않을 가능성이 매우 높습니다.

안전 속성 심각도

4개의 안전 속성에 각각 안전 등급(심각도 수준)과 0.0~1.0 사이의 심각도 점수(소수점 한 자리로 반올림)가 할당됩니다. 다음 표의 등급과 점수는 특정 카테고리에 속하는 콘텐츠의 예측 심각도를 나타냅니다.

심각도 설명
무시할 수 있음 콘텐츠 심각도는 Google의 안전 정책에 따라 무시할 수 있는 수준으로 예측됩니다.
낮음 콘텐츠 심각도가 Google의 안전 정책에 따라 낮다고 예측됩니다.
보통 콘텐츠 심각도는 Google의 안전 정책에 따라 보통으로 예측됩니다.
높음 콘텐츠 심각도가 Google의 안전 정책에 따라 높은 것으로 예측됩니다.

안전 설정

안전 설정은 API 서비스로 보내는 요청의 일부로, API에 대한 각 요청에 대해 조정할 수 있습니다. 다음 표에서 각 카테고리에 대해 조정할 수 있는 차단 설정을 확인할 수 있습니다. 예를 들어 위험한 콘텐츠 카테고리에 대해 차단 설정을 소수 차단으로 설정하면 위험한 콘텐츠일 가능성이 높은 모든 항목이 차단됩니다. 하지만 가능성이 낮은 모든 항목이 허용됩니다. 설정하지 않으면 기본 차단 설정이 일부 차단이 됩니다.

기준(Studio) 기준(API) 기준(설명)
BLOCK_NONE(제한됨) 콘텐츠의 안전하지 않은 가능성에 관계없이 항상 표시됩니다.
소수 차단 BLOCK_ONLY_HIGH 안전하지 않은 콘텐츠일 가능성이 높은 경우 차단합니다.
일부 차단(기본값) BLOCK_MEDIUM_AND_ABOVE(기본값) 안전하지 않은 콘텐츠일 가능성이 중간 또는 높은 경우 차단
대부분 차단 BLOCK_LOW_AND_ABOVE 안전하지 않은 콘텐츠일 가능성이 중간 또는 높은 경우 차단
HARM_BLOCK_THRESHOLD_UNSPECIFIED 기준점이 지정되지 않았습니다. 기본 기준점을 사용하여 차단합니다.

텍스트 서비스에 전송하는 각 요청마다 이 설정을 변경할 수 있습니다. 자세한 내용은 HarmBlockThreshold API 참조를 확인하세요.

일부 안전 속성에 대한 자동 응답 차단을 삭제하는 방법

'BLOCK_NONE' 안전 설정은 자동 응답 차단(안전 설정에 설명된 안전 속성 관련)을 삭제하고 반환되는 점수로 자체 안전 가이드라인을 구성할 수 있도록 합니다. 'BLOCK_NONE' 설정에 액세스하는 방법에는 두 가지가 있습니다.

(1) Gemini 안전 필터 허용 목록 양식을 통해 허용 목록을 신청할 수 있습니다.

(2) GCP 인보이스 결제 참조를 사용하여 계정 유형을 월별 인보이스 결제로 전환할 수 있습니다.

Gemini와 다른 모델 계열의 주요 차이점

Gemini와 PaLM에는 동일한 안전 분류기가 적용되지만 API에서 반환되는 안전 속성 수는 모델 제품군에 따라 다를 수 있습니다. 차단 로직(예: 신뢰도 임곗값)은 각 모델에 대한 엄격한 평가를 기반으로 합니다. 따라서 한 모델에 적용된 안전 설정이 다른 모델에 적용된 안전 설정의 동작과 완벽하게 일치하지 않을 수 있습니다. 이 점이 우려되는 경우 원시 심각도 점수와 원시 신뢰도 점수로 자체 차단 로직을 구성하여 모델 전체에 동일한 점수 기준점을 적용하는 것이 좋습니다.

기준점 구성

Python

Python을 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참고 문서를 참조하세요.

from vertexai import generative_models

def generate_text(project_id: str, location: str, image: str) -> str:
    # Initialize Vertex AI
    vertexai.init(project=project_id, location=location)

    # Load the model
    model = generative_models.GenerativeModel("gemini-1.0-pro-vision")

    # Generation config
    config = generative_models.GenerationConfig(
        max_output_tokens=2048, temperature=0.4, top_p=1, top_k=32
    )

    # Safety config
    safety_config = {
        generative_models.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: generative_models.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
        generative_models.HarmCategory.HARM_CATEGORY_HARASSMENT: generative_models.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
    }

    # Generate content
    responses = model.generate_content(
        [image, "Add your prompt here"],
        generation_config=config,
        stream=True,
        safety_settings=safety_config,
    )

    text_responses = []
    for response in responses:
        print(response.text)
        text_responses.append(response.text)
    return "".join(text_responses)

Node.js

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Vertex AI Node.js API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

const {
  VertexAI,
  HarmCategory,
  HarmBlockThreshold,
} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function setSafetySettings(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.0-pro'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
    // The following parameters are optional
    // They can also be passed to individual content generation requests
    safety_settings: [
      {
        category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
        threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
      },
    ],
    generation_config: {max_output_tokens: 256},
  });

  const request = {
    contents: [{role: 'user', parts: [{text: 'Tell me something dangerous.'}]}],
  };

  console.log('Prompt:');
  console.log(request.contents[0].parts[0].text);
  console.log('Streaming Response Text:');

  // Create the response stream
  const responseStream = await generativeModel.generateContentStream(request);

  // Log the text response as it streams
  for await (const item of responseStream.stream) {
    if (item.candidates[0].finishReason === 'SAFETY') {
      console.log('This response stream terminated due to safety concerns.');
      break;
    } else {
      process.stdout.write(item.candidates[0].content.parts[0].text);
    }
  }
}

Java

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Vertex AI Java API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.Candidate;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import com.google.cloud.vertexai.api.GenerationConfig;
import com.google.cloud.vertexai.api.HarmCategory;
import com.google.cloud.vertexai.api.SafetySetting;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import java.util.Arrays;
import java.util.List;

public class WithSafetySettings {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-google-cloud-project-id";
    String location = "us-central1";
    String modelName = "gemini-1.0-pro-vision";
    String textPrompt = "your-text-here";

    String output = safetyCheck(projectId, location, modelName, textPrompt);
    System.out.println(output);
  }

  // Use safety settings to avoid harmful questions and content generation.
  public static String safetyCheck(String projectId, String location, String modelName,
      String textPrompt) throws Exception {
    // Initialize client that will be used to send requests. This client only needs
    // to be created once, and can be reused for multiple requests.
    try (VertexAI vertexAI = new VertexAI(projectId, location)) {
      StringBuilder output = new StringBuilder();

      GenerationConfig generationConfig =
          GenerationConfig.newBuilder()
              .setMaxOutputTokens(2048)
              .setTemperature(0.4F)
              .setTopK(32)
              .setTopP(1)
              .build();

      GenerativeModel model = new GenerativeModel(modelName, generationConfig, vertexAI);

      List<SafetySetting> safetySettings = Arrays.asList(
          SafetySetting.newBuilder()
              .setCategory(HarmCategory.HARM_CATEGORY_HATE_SPEECH)
              .setThreshold(SafetySetting.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE)
              .build(),
          SafetySetting.newBuilder()
              .setCategory(HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT)
              .setThreshold(SafetySetting.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE)
              .build()
      );

      GenerateContentResponse response = model.generateContent(
          textPrompt,
          safetySettings
      );
      output.append(response).append("\n");

      // Verifies if the above content has been blocked for safety reasons.
      boolean blockedForSafetyReason = response.getCandidatesList()
          .stream()
          .anyMatch(candidate -> candidate.getFinishReason() == Candidate.FinishReason.SAFETY);
      output.append("Blocked for safety reasons?: ").append(blockedForSafetyReason);

      return output.toString();
    }
  }
}

Go

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Vertex AI Go API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"
	"mime"
	"path/filepath"

	"cloud.google.com/go/vertexai/genai"
)

// generateMultimodalContent generates a response into w, based upon the prompt
// and image provided.
func generateMultimodalContent(w io.Writer, prompt, image, projectID, location, modelName string) error {
	// prompt := "describe this image."
	// location := "us-central1"
	// model := "gemini-1.0-pro-vision"
	// image := "gs://cloud-samples-data/generative-ai/image/320px-Felis_catus-cat_on_snow.jpg"
	ctx := context.Background()

	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("unable to create client: %v", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)
	model.SetTemperature(0.4)
	// configure the safety settings thresholds
	model.SafetySettings = []*genai.SafetySetting{
		{
			Category:  genai.HarmCategoryHarassment,
			Threshold: genai.HarmBlockLowAndAbove,
		},
		{
			Category:  genai.HarmCategoryDangerousContent,
			Threshold: genai.HarmBlockLowAndAbove,
		},
	}

	// Given an image file URL, prepare image file as genai.Part
	img := genai.FileData{
		MIMEType: mime.TypeByExtension(filepath.Ext(image)),
		FileURI:  image,
	}

	res, err := model.GenerateContent(ctx, img, genai.Text(prompt))
	if err != nil {
		return fmt.Errorf("unable to generate contents: %w", err)
	}

	fmt.Fprintf(w, "generated response: %s\n", res.Candidates[0].Content.Parts[0])
	return nil
}

C#

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용C# 설정 안내를 따르세요. 자세한 내용은 Vertex AI C# API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Api.Gax.Grpc;
using Google.Cloud.AIPlatform.V1;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using static Google.Cloud.AIPlatform.V1.SafetySetting.Types;

public class WithSafetySettings
{
    public async Task<string> GenerateContent(
        string projectId = "your-project-id",
        string location = "us-central1",
        string publisher = "google",
        string model = "gemini-1.0-pro-vision"
    )
    {
        // Create client
        var predictionServiceClient = new PredictionServiceClientBuilder
        {
            Endpoint = $"{location}-aiplatform.googleapis.com"
        }.Build();

        // Prompt
        string prompt = "Hello!";

        // Initialize request argument(s)
        var content = new Content
        {
            Role = "USER"
        };
        content.Parts.AddRange(new List<Part>()
        {
            new()
            {
                Text = prompt
            }
        });

        var safetySettings = new List<SafetySetting>()
        {
            new()
            {
                Category = HarmCategory.HateSpeech,
                Threshold = HarmBlockThreshold.BlockLowAndAbove
            },
            new()
            {
                Category = HarmCategory.DangerousContent,
                Threshold = HarmBlockThreshold.BlockMediumAndAbove
            }
        };

        var generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            GenerationConfig = new GenerationConfig
            {
                Temperature = 0.4f,
                TopP = 1,
                TopK = 32,
                MaxOutputTokens = 2048
            },
        };
        generateContentRequest.Contents.Add(content);
        generateContentRequest.SafetySettings.AddRange(safetySettings);

        // Make the request, returning a streaming response
        using PredictionServiceClient.StreamGenerateContentStream response = predictionServiceClient.StreamGenerateContent(generateContentRequest);

        StringBuilder fullText = new();

        // Read streaming responses from server until complete
        AsyncResponseStream<GenerateContentResponse> responseStream = response.GetResponseStream();
        await foreach (GenerateContentResponse responseItem in responseStream)
        {
            // Check if the content has been blocked for safety reasons.
            bool blockForSafetyReason = responseItem.Candidates[0].FinishReason == Candidate.Types.FinishReason.Safety;
            if (blockForSafetyReason)
            {
                fullText.Append("Blocked for safety reasons");
            }
            else
            {
                fullText.Append(responseItem.Candidates[0].Content.Parts[0].Text);
            }
        }

        return fullText.ToString();
    }
}

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION: 요청을 처리하는 리전입니다. 사용 가능한 옵션은 다음과 같습니다.

    클릭하여 사용 가능한 리전 펼치기

    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID: 프로젝트 ID
  • MODEL_ID: 사용할 멀티모달 모델의 모델 ID입니다. 옵션은 다음과 같습니다.
    • gemini-1.0-pro
    • gemini-1.0-pro-vision
  • ROLE: 콘텐츠와 연결된 대화의 역할입니다. 싱글턴 사용 사례에서도 역할을 지정해야 합니다. 허용되는 값은 다음과 같습니다.
    • USER: 전송한 콘텐츠를 지정합니다.
    • MODEL: 모델의 응답을 지정합니다.
  • TEXT: 프롬프트에 포함할 텍스트 안내입니다.
  • SAFETY_CATEGORY: 기준점을 구성할 안전 카테고리입니다. 허용되는 값은 다음과 같습니다.

    클릭하여 안전 카테고리 펼치기

    • HARM_CATEGORY_SEXUALLY_EXPLICIT
    • HARM_CATEGORY_HATE_SPEECH
    • HARM_CATEGORY_HARASSMENT
    • HARM_CATEGORY_DANGEROUS_CONTENT
  • THRESHOLD: 확률에 따라 지정된 안전 카테고리에 속할 수 있는 응답 차단의 기준점입니다. 허용되는 값은 다음과 같습니다.

    클릭하여 차단 기준점 펼치기

    • BLOCK_NONE
    • BLOCK_ONLY_HIGH
    • BLOCK_MEDIUM_AND_ABOVE(기본)
    • BLOCK_LOW_AND_ABOVE
    BLOCK_LOW_AND_ABOVE는 가장 많이 차단하며 BLOCK_ONLY_HIGH는 가장 적게 차단합니다.

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent

JSON 요청 본문:

{
  "contents": {
    "role": "ROLE",
    "parts": { "text": "TEXT" }
  },
  "safety_settings": {
    "category": "SAFETY_CATEGORY",
    "threshold": "THRESHOLD"
  },
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 수신됩니다.

curl 명령어 예시

LOCATION="us-central1"
MODEL_ID="gemini-1.0-pro"
PROJECT_ID="test-project"

curl \
-X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:streamGenerateContent -d \
$'{
  "contents": {
    "role": "user",
    "parts": { "text": "Hello!" }
  },
  "safety_settings": [
    {
      "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
      "threshold": "BLOCK_NONE"
    },
    {
      "category": "HARM_CATEGORY_HATE_SPEECH",
      "threshold": "BLOCK_LOW_AND_ABOVE"
    },
    {
      "category": "HARM_CATEGORY_HARASSMENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_ONLY_HIGH"
    }
  ]
}'

Console

  1. Google Cloud 콘솔의 Vertex AI 섹션에서 Vertex AI Studio 페이지로 이동합니다.

    Vertex AI Studio로 이동

  2. 새 프롬프트 만들기에서 버튼 중 하나를 클릭하여 프롬프트 디자인 페이지를 엽니다.

  3. 안전 설정을 클릭합니다.

    안전 설정 대화상자 창이 열립니다.

  4. 각 안전 속성에 대해 원하는 기준값을 구성합니다.

  5. 저장을 클릭합니다.

다음 단계