텍스트

텍스트용 PaLM2(text-bison, text-unicorn) 기반 모델은 감정 분석, 항목 추출, 콘텐츠 생성과 같은 다양한 자연어 태스크에 최적화되어 있습니다. 텍스트용 PaLM2 모델에서 만들 수 있는 콘텐츠 유형에는 문서 요약, 질문에 대한 답변, 콘텐츠 분류 라벨이 포함됩니다.

텍스트용 PaLM2 모델은 이어지는 대화 요구 없이 API 응답 하나로 완료될 수 있는 태스크에 이상적입니다. 주고 받는 상호작용이 필요한 텍스트 태스크의 경우 채팅용 Vertex AI API 기반의 생성형 AI를 사용합니다.

콘솔에서 모델을 살펴보려면 Model Garden에서 텍스트용 PaLM2 모델 카드를 선택합니다.
Model Garden으로 이동

사용 사례

  • 요약: 원본 텍스트의 관련 정보가 포함된 더 짧은 문서를 생성합니다. 예를 들어 교과서에서 한 챕터의 내용을 요약해야 할 수 있습니다. 또는 자세한 제품 설명이 포함된 긴 단락으로부터 간결한 제품 설명을 만들 수 있습니다.

  • 질문 답변: 질문에 대한 답변을 텍스트로 제공합니다. 예를 들어 기술 자료 콘텐츠로부터 자주 묻는 질문(FAQ) 문서 생성을 자동화할 수 있습니다.

  • 분류: 제공된 텍스트에 라벨을 할당합니다. 예를 들어 텍스트가 문법적으로 올바른지를 기술하는 라벨을 적용할 수 있습니다.

  • 감정 분석: 텍스트 감정을 식별하는 분류 형식입니다. 감정은 텍스트에 적용되는 라벨로 전환됩니다. 예를 들어 텍스트 감정은 긍정이나 부정, 분노나 행복과 같은 양극성을 가질 수 있습니다.

  • 항목 추출: 텍스트에서 정보를 추출합니다. 예를 들어 기사 내용에서 영화 이름을 추출할 수 있습니다.

텍스트 프롬프트 설계에 대한 자세한 내용은 텍스트 프롬프트 설계를 참조하세요.

HTTP 요청

POST https://us-central1-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/us-central1/publishers/google/models/text-bison:predict

자세한 내용은 predict 메서드를 참조하세요.

모델 버전

최신 모델 버전을 사용하려면 버전 번호 없이 모델 이름을 지정합니다(예: text-bison).

정식 모델 버전을 사용하려면 모델 버전 번호를 지정합니다(예: text-bison@002). 각 안정화 버전은 후속 정식 버전의 출시 날짜로부터 6개월 동안 사용 가능합니다.

다음 표에는 사용 가능한 정식 모델 버전이 포함되어 있습니다.

text-bison 모델 출시일 중단 날짜
text-bison@002 2023년 12월 6일 해당 없음
text-bison@001 2023년 6월 7일 2024년 7월 6일
text-unicorn 모델 출시일 중단 날짜
text-unicorn@001 2023년 11월 30일 해당 없음

자세한 내용은 모델 버전 및 수명 주기를 참조하세요.

요청 본문

{
  "instances": [
    {
      "prompt": string
    }
  ],
  "parameters": {
    "temperature": number,
    "maxOutputTokens": integer,
    "topK": integer,
    "topP": number,
    "groundingConfig": string,
    "stopSequences": [ string ],
    "candidateCount": integer,
    "logprobs": integer,
    "presencePenalty": float,
    "frequencyPenalty": float,
    "echo": boolean,
    "seed": integer
  }
}

텍스트 모델 text-bison에 대해 다음 매개변수를 사용합니다. 자세한 내용은 텍스트 프롬프트 설계를 참조하세요.

매개변수 설명 사용 가능한 값

prompt

모델 응답을 생성하는 텍스트 입력입니다. 프롬프트에 프리앰블, 질문, 제안, 안내 또는 예시가 포함될 수 있습니다. 텍스트

temperature

강도는 응답 생성 중 샘플링에 사용되며 topPtopK가 적용될 때 발생합니다. 강도는 토큰 선택의 무작위성 수준을 제어합니다. 강도가 낮을수록 자유롭거나 창의적인 답변과 거리가 먼 응답이 필요한 프롬프트에 적합하고, 강도가 높을수록 보다 다양하거나 창의적인 결과로 이어질 수 있습니다. 강도가 0이면 확률이 가장 높은 토큰이 항상 선택됩니다. 이 경우 특정 프롬프트에 대한 응답은 대부분 확정적이지만 여전히 약간의 변형이 가능합니다.

모델이 너무 일반적이거나, 너무 짧은 응답을 반환하거나 모델이 대체 응답을 제공할 경우에는 강도를 높여보세요.

0.0–1.0

Default: 0.0

maxOutputTokens

응답에서 생성될 수 있는 토큰의 최대 개수입니다. 토큰은 약 4자(영문 기준)입니다. 토큰 100개는 단어 약 60~80개에 해당합니다.

응답이 짧을수록 낮은 값을 지정하고 잠재적으로 응답이 길면 높은 값을 지정합니다.

text-bison(최신)의 경우 1–2048

text-blice@002의 경우 1–1024

Default: 1024

topK

Top-K는 모델이 출력용 토큰을 선택하는 방식을 변경합니다. Top-K가 1이면 선택된 토큰이 모델의 어휘에 포함된 모든 토큰 중에서 가장 확률이 높다는 의미입니다(그리디 디코딩이라고도 함). 반면에 Top-K가 3이면 강도를 사용하여 가장 확률이 높은 3개 토큰 중에서 다음 토큰이 선택된다는 의미입니다.

각 토큰 선택 단계에서 확률이 가장 높은 Top-K 토큰이 샘플링됩니다. 그런 다음 Top-P를 기준으로 토큰을 추가로 필터링하고 강도 샘플링을 사용하여 최종 토큰을 선택합니다.

임의성이 낮은 응답에 낮은 값을 지정하고 임의성이 높은 응답에 높은 값을 지정합니다.

1–40

Default: 40

topP

Top-P는 모델이 출력용 토큰을 선택하는 방식을 변경합니다. 토큰은 확률의 합이 Top-P 값과 같아질 때까지 확률이 가장 높은 것부터(Top-K 참조) 가장 낮은 것까지 선택됩니다. 예를 들어 토큰 A, B, C의 확률이 0.3, 0.2, 0.1이고 Top-P 값이 0.5이면 모델이 강도를 사용해서 다음 토큰으로 A 또는 B를 선택하고 C는 후보에서 제외합니다.

임의성이 낮은 응답에 낮은 값을 지정하고 임의성이 높은 응답에 높은 값을 지정합니다.

0.0–1.0

Default: 0.95

stopSequence

문자열 중 하나가 응답에서 발견되면 모델에 텍스트 생성을 중지하도록 지시하는 문자열 목록을 지정합니다. 문자열이 응답에 여러 번 표시되면 처음 발견된 위치에서 응답이 잘립니다. 문자열은 대소문자를 구분합니다.

예를 들어 stopSequences가 지정되지 않았을 때 다음이 반환되면:

public static string reverse(string myString)

이 때 stopSequences["Str", "reverse"]로 설정된 응답이 다음과 같이 반환됩니다.

public static string

default: []

groundingConfig

그라운딩하면 언어 모델을 사용할 때 특정 데이터를 참조할 수 있습니다. 모델을 그라운딩하면 모델은 저장소의 내부, 기밀 또는 기타 특정 데이터를 참조하고 응답에 데이터를 포함시킬 수 있습니다. Vertex AI Search의 데이터 저장소만 지원됩니다.

경로는 projects/{project_id}/locations/global/collections/{collection_name}/dataStores/{DATA_STORE_ID} 형식이어야 합니다.

candidateCount

반환할 응답 변형의 개수입니다.

1–4

Default: 1

logprobs

각 생성 단계에서 확률이 가장 높은 상위 logprobs 후보 토큰과 해당하는 로그 확률을 반환합니다. 각 단계에서 선택한 토큰과 로그 확률은 항상 반환됩니다. 선택한 토큰은 확률이 가장 높은 상위 logprobs 후보에 있을 수도 있고 없을 수도 있습니다.

0-5

frequencyPenalty

양수 값은 생성된 텍스트에 반복적으로 표시되는 토큰에 페널티를 적용하여 콘텐츠가 반복될 가능성을 줄입니다. 허용되는 값은 -2.0~2.0입니다.

Minimum value: -2.0

Maximum value: 2.0

presencePenalty

양수 값은 생성된 텍스트에 이미 표시된 토큰에 페널티를 적용하여 다양한 콘텐츠가 생성될 가능성을 높입니다. 허용되는 값은 -2.0~2.0입니다.

Minimum value: -2.0

Maximum value: 2.0

echo

true인 경우 생성된 텍스트에 프롬프트가 echo 처리됩니다.

Optional

seed

디코더는 의사 난수 생성기로 무작위 노이즈를 생성하고 샘플링 전에 강도 * 노이즈가 로지트에 추가됩니다. 의사 난수 생성기(PRNG)는 시드를 입력으로 취하고, 동일한 시드로 동일한 출력을 생성합니다.

시드가 설정되지 않은 경우 디코더에 사용되는 시드가 확정적이지 않으므로 생성된 무작위 노이즈도 확정적이지 않습니다. 시드가 설정된 경우 생성된 무작위 노이즈는 확정적입니다.

Optional

샘플 요청

REST

Vertex AI API를 사용하여 텍스트 프롬프트를 테스트하려면 POST 요청을 게시자 모델 엔드포인트로 전송합니다.

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

다른 필드에 대해서는 요청 본문 테이블을 참조하세요.

HTTP 메서드 및 URL:

POST https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/text-bison:predict

JSON 요청 본문:

{
  "instances": [
    { "prompt": "Give me ten interview questions for the role of program manager."}
  ],
  "parameters": {
    "temperature": 0.2,
    "maxOutputTokens": 256,
    "topK": 40,
    "topP": 0.95,
    "logprobs": 2
  }
}

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

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://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/text-bison:predict"

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://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/text-bison:predict" | Select-Object -Expand Content

샘플 응답과 비슷한 JSON 응답이 표시됩니다.

Python용 Vertex AI SDK

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

import vertexai
from vertexai.language_models import TextGenerationModel

def interview(
    temperature: float,
    project_id: str,
    location: str,
) -> str:
    """Ideation example with a Large Language Model"""

    vertexai.init(project=project_id, location=location)
    # TODO developer - override these parameters as needed:
    parameters = {
        "temperature": temperature,  # Temperature controls the degree of randomness in token selection.
        "max_output_tokens": 256,  # Token limit determines the maximum amount of text output.
        "top_p": 0.8,  # Tokens are selected from most probable to least until the sum of their probabilities equals the top_p value.
        "top_k": 40,  # A top_k of 1 means the selected token is the most probable among all tokens.
    }

    model = TextGenerationModel.from_pretrained("text-bison@002")
    response = model.predict(
        "Give me ten interview questions for the role of program manager.",
        **parameters,
    )
    print(f"Response from Model: {response.text}")

    return response.text

if __name__ == "__main__":
    interview()

Node.js

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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
const aiplatform = require('@google-cloud/aiplatform');

// Imports the Google Cloud Prediction service client
const {PredictionServiceClient} = aiplatform.v1;

// Import the helper module for converting arbitrary protobuf.Value objects.
const {helpers} = aiplatform;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

const publisher = 'google';
const model = 'text-bison@001';

// Instantiates a client
const predictionServiceClient = new PredictionServiceClient(clientOptions);

async function callPredict() {
  // Configure the parent resource
  const endpoint = `projects/${project}/locations/${location}/publishers/${publisher}/models/${model}`;

  const prompt = {
    prompt:
      'Give me ten interview questions for the role of program manager.',
  };
  const instanceValue = helpers.toValue(prompt);
  const instances = [instanceValue];

  const parameter = {
    temperature: 0.2,
    maxOutputTokens: 256,
    topP: 0.95,
    topK: 40,
  };
  const parameters = helpers.toValue(parameter);

  const request = {
    endpoint,
    instances,
    parameters,
  };

  // Predict request
  const response = await predictionServiceClient.predict(request);
  console.log('Get text prompt response');
  console.log(response);
}

callPredict();

Java

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

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


import com.google.cloud.aiplatform.v1beta1.EndpointName;
import com.google.cloud.aiplatform.v1beta1.PredictResponse;
import com.google.cloud.aiplatform.v1beta1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1beta1.PredictionServiceSettings;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PredictTextPromptSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Details of designing text prompts for supported large language models:
    // https://cloud.google.com/vertex-ai/docs/generative-ai/text/text-overview
    String instance =
        "{ \"prompt\": " + "\"Give me ten interview questions for the role of program manager.\"}";
    String parameters =
        "{\n"
            + "  \"temperature\": 0.2,\n"
            + "  \"maxOutputTokens\": 256,\n"
            + "  \"topP\": 0.95,\n"
            + "  \"topK\": 40\n"
            + "}";
    String project = "YOUR_PROJECT_ID";
    String location = "us-central1";
    String publisher = "google";
    String model = "text-bison@001";

    predictTextPrompt(instance, parameters, project, location, publisher, model);
  }

  // Get a text prompt from a supported text model
  public static void predictTextPrompt(
      String instance,
      String parameters,
      String project,
      String location,
      String publisher,
      String model)
      throws IOException {
    String endpoint = String.format("%s-aiplatform.googleapis.com:443", location);
    PredictionServiceSettings predictionServiceSettings =
        PredictionServiceSettings.newBuilder().setEndpoint(endpoint).build();

    // 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 (PredictionServiceClient predictionServiceClient =
        PredictionServiceClient.create(predictionServiceSettings)) {
      final EndpointName endpointName =
          EndpointName.ofProjectLocationPublisherModelName(project, location, publisher, model);

      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      Value.Builder instanceValue = Value.newBuilder();
      JsonFormat.parser().merge(instance, instanceValue);
      List<Value> instances = new ArrayList<>();
      instances.add(instanceValue.build());

      // Use Value.Builder to convert instance to a dynamically typed value that can be
      // processed by the service.
      Value.Builder parameterValueBuilder = Value.newBuilder();
      JsonFormat.parser().merge(parameters, parameterValueBuilder);
      Value parameterValue = parameterValueBuilder.build();

      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instances, parameterValue);
      System.out.println("Predict Response");
      System.out.println(predictResponse);
    }
  }
}

응답 본문

{
  "predictions":[
    {
      "content": string,
      "citationMetadata": {
        "citations": [
          {
            "startIndex": integer,
            "endIndex": integer,
            "url": string,
            "title": string,
            "license": string,
            "publicationDate": string
          }
        ]
      },
      "logprobs": {
        "tokenLogProbs": [ float ],
        "tokens": [ string ],
        "topLogProbs": [ { map<string, float> } ]
      },
      "safetyAttributes": {
        "categories": [ string ],
        "blocked": boolean,
        "scores": [ float ],
        "errors": [ int ]
      }
    }
  ],
  "metadata": {
    "tokenMetadata": {
      "input_token_count": {
        "total_tokens": integer,
        "total_billable_characters": integer
      },
      "output_token_count": {
        "total_tokens": integer,
        "total_billable_characters": integer
      }
    }
  }
}
응답 요소 설명
content 입력 텍스트에서 생성된 결과입니다.
categories 생성된 콘텐츠와 연결된 안전 속성 범주의 표시 이름입니다. 순서는 점수와 일치합니다.
scores 각 카테고리의 신뢰도 점수입니다. 값이 높을수록 신뢰도가 높습니다.
blocked 모델의 입력 또는 출력이 차단되었는지를 나타내는 플래그입니다.
errors 입력 또는 출력이 차단된 이유를 식별하는 오류 코드입니다. 오류 코드 목록은 안전 필터 및 속성을 참조하세요.
startIndex 인용이 시작되는 예측 출력의 인덱스입니다(포함). 0보다 크거나 같고 end_index보다 작아야 합니다.
endIndex 인용이 끝나는 예측 출력의 인덱스입니다(제외). start_index보다 크고 len(output)보다 작아야 합니다.
url 이 인용과 연결된 URL입니다. 제공된 경우 이 URL이 해당 인용의 소스 웹페이지로 연결됩니다. 가능한 URL에는 뉴스 웹사이트, GitHub 저장소 등이 포함됩니다.
title 이 인용과 연결된 제목입니다. 제공된 경우 이 인용의 소스 제목을 나타냅니다. 가능한 제목에는 뉴스 제목, 책 제목 등이 포함됩니다.
license 인용과 연결된 라이선스입니다. 제공된 경우 이 인용의 소스에 대한 라이선스를 나타냅니다. 가능한 라이선스에는 코드 라이선스가 포함됩니다(예: mit 라이선스).
publicationDate 이 인용과 연결된 게시 날짜입니다. 제공된 경우 이 인용의 소스가 게시된 날짜를 나타냅니다. 가능한 형식은 YYYY, YYYY-MM, YYYY-MM-DD입니다.
input_token_count 입력 토큰의 수입니다. 모든 프롬프트, 프리픽스, 서픽스 간의 총 토큰 수입니다.
output_token_count 출력 토큰의 수입니다. 모든 예측에서 content의 총 토큰 수입니다.
tokens 샘플링된 토큰입니다.
tokenLogProbs 샘플링된 토큰의 로그 확률입니다.
topLogProb 각 단계에서 확률이 가장 높은 후보 토큰과 해당하는 로그 확률입니다.
logprobs `logprobs` 매개변수 결과입니다. `candidates`에 1:1 매핑됩니다.

샘플 응답

{
  "predictions": [
    {
      "citationMetadata":{
        "citations": [ ]
      },
      "safetyAttributes":{
        "scores": [
          0.1
        ],
        "categories": [
          "Finance"
        ],
        "blocked": false
      },
      "content":"1. What is your experience with project management?\n2. What are your strengths and weaknesses as a project manager?\n3. How do you handle conflict and difficult situations?\n4. How do you communicate with stakeholders?\n5. How do you stay organized and on track?\n6. How do you manage your time effectively?\n7. What are your goals for your career?\n8. Why are you interested in this position?\n9. What are your salary expectations?\n10. What are your availability and start date?",
      "logprobs": {
        "tokenLogProbs": [
          -0.1,
          -0.2
        ],
        "tokens": [
          "vertex",
          " rocks!"
        ],
        "topLogProbs": [
          {
            "vertex": -0.1,
            "hello": -0.2
          },
          {
            " rocks!": -0.2,
            " world!": -0.3
          }
        ]
      }
    },
    "metadata": {
      "tokenMetadata": {
        "outputTokenCount": {
          "totalTokens": 153,
          "totalBillableCharacters": 537
        },
        "inputTokenCount": {
          "totalBillableCharacters": 54,
          "totalTokens": 12
        }
      }
    }
  ]
}

생성형 AI 모델에서 응답 스트리밍

매개변수는 API에 대한 스트리밍 요청 또는 비스트리밍 요청에 대해 모두 동일합니다.

REST API를 사용하여 샘플 코드 요청 및 응답을 보려면 REST API 사용 예시를 참조하세요.

Python용 Vertex AI SDK를 사용하여 샘플 코드 요청 및 응답을 보려면 Python용 Vertex AI SDK 사용 예시를 참조하세요.