문자 채팅

채팅용 PaLM2(chat-bison) 기반 모델은 언어 이해, 언어 생성, 대화 성능이 뛰어난 대규모 언어 모델(LLM)입니다. 이 채팅 모델은 자연스러운 멀티턴 대화를 수행하도록 미세 조정되어 있으며 주고 받는 상호 작용이 필요한 코드에 대한 텍스트 태스크에 이상적입니다.

하나의 API 응답으로 완료할 수 있는 텍스트 태스크의 경우(연속 대화가 필요하지 않음) 텍스트 모델을 사용합니다.

콘솔에서 이 모델을 살펴보려면 Model Garden에서 채팅 모델 카드의 PaLM2를 참조하세요.
Model Garden으로 이동

사용 사례

  • 고객 서비스: 모델이 회사 제품에 대해서만 이야기하는 고객 서비스 에이전트로 응답하도록 지시합니다.

  • 기술 지원: 모델이 응답 방법 및 언급 제외 표현에 대한 특정 매개변수를 사용해서 콜 센터 에이전트로 고객과 상호작용하도록 지시합니다.

  • 사람 및 캐릭터: 모델이 특정 사람의 스타일(예: "셰익스피어 스타일")로 응답하도록 지시합니다.

  • 웹사이트 컴패니언: 쇼핑, 여행, 기타 사용 사례를 위한 대화형 비서를 만듭니다.

자세한 내용은 채팅 프롬프트 설계를 참조하세요.

HTTP 요청

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

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

모델 버전

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

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

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

chat-bison 모델 출시일 중단 날짜
chat-bison@002 2023년 12월 6일 2024년 10월 9일
chat-bison@001 2023년 7월 10일 2024년 7월 6일

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

요청 본문

{
  "instances": [
    {
      "context":  string,
      "examples": [
        {
          "input": { "content": string },
          "output": { "content": string }
        }
      ],
      "messages": [
        {
          "author": string,
          "content": string,
        }
      ],
    }
  ],
  "parameters": {
    "temperature": number,
    "maxOutputTokens": integer,
    "topP": number,
    "topK": integer,
    "groundingConfig": string,
    "stopSequences": [ string ],
    "candidateCount": integer
    "logprobs": integer,
    "presencePenalty": float,
    "frequencyPenalty": float,
    "seed": integer
  }
}

채팅 API 호출의 경우 context, examples, messages를 조합해서 프롬프트를 만듭니다. 다음 표에서는 텍스트용 Vertex AI PaLM API에 대해 구성해야 하는 매개변수를 보여줍니다.

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

context

(선택사항)

컨텍스트는 대화 전반에 걸친 모델의 응답 방식을 결정합니다. 예를 들어 모델이 사용할 수 있거나 사용할 수 없는 단어, 중점을 두거나 피해야 할 주제, 응답 형식 또는 스타일을 지정하는 데 컨텍스트를 사용할 수 있습니다. 텍스트

examples

(선택사항)

모델이 대화 응답 방법을 학습하기 위한 예시입니다.

[{
  "input": {"content": "provide content"},
  "output": {"content": "provide content"}
}]

messages

(필수)

저자가 구분된 구조화된 양식으로 모델에 제공된 대화 기록입니다. 메시지는 오래된 것부터 최근 것까지 시간순으로 표시됩니다. 메시지 기록으로 인해 입력이 최대 길이를 초과할 경우 전체 프롬프트가 허용 범위 내에 들어올 때까지 가장 오래된 메시지가 삭제됩니다.

[{
  "author": "user",
  "content": "user message"
}]

temperature

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

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

0.0–1.0

Default: 0.0

maxOutputTokens

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

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

1–2048

Default: 1024

topK

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

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

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

1–40

Default: 40

topP

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

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

0.0–1.0

Default: 0.95

stopSequences

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

예를 들어 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

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/chat-bison:predict

JSON 요청 본문:

{
  "instances": [{
      "context":  "CONTEXT",
      "examples": [
       {
          "input": {"content": "EXAMPLE_INPUT"},
          "output": {"content": "EXAMPLE_OUTPUT"}
       }],
      "messages": [
       {
          "author": "AUTHOR",
          "content": "CONTENT",
       }],
   }],
  "parameters": {
    "temperature": TEMPERATURE,
    "maxOutputTokens": MAX_OUTPUT_TOKENS,
    "topP": TOP_P,
    "topK": TOP_K
  }
}

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

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/chat-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/chat-bison:predict" | Select-Object -Expand Content

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

Python

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

from vertexai.language_models import ChatModel, InputOutputTextPair

def science_tutoring(temperature: float = 0.2) -> None:
    chat_model = ChatModel.from_pretrained("chat-bison@001")

    # 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.95,  # 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.
    }

    chat = chat_model.start_chat(
        context="My name is Miles. You are an astronomer, knowledgeable about the solar system.",
        examples=[
            InputOutputTextPair(
                input_text="How many moons does Mars have?",
                output_text="The planet Mars has two moons, Phobos and Deimos.",
            ),
        ],
    )

    response = chat.send_message(
        "How many planets are there in the solar system?", **parameters
    )
    print(f"Response from Model: {response.text}")

    return response

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 = 'chat-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 = {
    context:
      'My name is Miles. You are an astronomer, knowledgeable about the solar system.',
    examples: [
      {
        input: {content: 'How many moons does Mars have?'},
        output: {
          content: 'The planet Mars has two moons, Phobos and Deimos.',
        },
      },
    ],
    messages: [
      {
        author: 'user',
        content: 'How many planets are there in the solar system?',
      },
    ],
  };
  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 chat prompt response');
  const predictions = response.predictions;
  console.log('\tPredictions :');
  for (const prediction of predictions) {
    console.log(`\t\tPrediction : ${JSON.stringify(prediction)}`);
  }
}

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;

// Send a Predict request to a large language model to test a chat prompt
public class PredictChatPromptSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String instance =
        "{\n"
            + "   \"context\":  \"My name is Ned. You are my personal assistant. My favorite movies"
            + " are Lord of the Rings and Hobbit.\",\n"
            + "   \"examples\": [ { \n"
            + "       \"input\": {\"content\": \"Who do you work for?\"},\n"
            + "       \"output\": {\"content\": \"I work for Ned.\"}\n"
            + "    },\n"
            + "    { \n"
            + "       \"input\": {\"content\": \"What do I like?\"},\n"
            + "       \"output\": {\"content\": \"Ned likes watching movies.\"}\n"
            + "    }],\n"
            + "   \"messages\": [\n"
            + "    { \n"
            + "       \"author\": \"user\",\n"
            + "       \"content\": \"Are my favorite movies based on a book series?\"\n"
            + "    }]\n"
            + "}";
    String parameters =
        "{\n"
            + "  \"temperature\": 0.3,\n"
            + "  \"maxDecodeSteps\": 200,\n"
            + "  \"topP\": 0.8,\n"
            + "  \"topK\": 40\n"
            + "}";
    String project = "YOUR_PROJECT_ID";
    String publisher = "google";
    String model = "chat-bison@001";

    predictChatPrompt(instance, parameters, project, publisher, model);
  }

  static void predictChatPrompt(
      String instance, String parameters, String project, String publisher, String model)
      throws IOException {
    PredictionServiceSettings predictionServiceSettings =
        PredictionServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .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)) {
      String location = "us-central1";
      final EndpointName endpointName =
          EndpointName.ofProjectLocationPublisherModelName(project, location, publisher, model);

      Value.Builder instanceValue = Value.newBuilder();
      JsonFormat.parser().merge(instance, instanceValue);
      List<Value> instances = new ArrayList<>();
      instances.add(instanceValue.build());

      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");
    }
  }
}

응답 본문

{
  "predictions": [
    {
      "candidates": [
        {
          "author": string,
          "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": false,
        "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 채팅 메시지의 텍스트 콘텐츠입니다.
candidates 지정된 메시지에서 생성된 채팅 결과입니다.
categories 생성된 콘텐츠와 연결된 안전 속성 범주의 표시 이름입니다. 순서는 점수와 일치합니다.
author 해당 차례의 작성자 태그입니다.
scores 각 카테고리의 신뢰도 점수입니다. 값이 높을수록 신뢰도가 높습니다.
blocked 모델의 입력 또는 출력이 차단되었는지를 나타내는 플래그입니다.
startIndex 인용이 시작되는 예측 출력의 인덱스입니다(포함). 0보다 크거나 같고 end_index보다 작아야 합니다.
endIndex 인용이 끝나는 예측 출력의 인덱스입니다(제외). start_index보다 크고 len(output)보다 작아야 합니다.
url 이 인용과 연결된 URL입니다. 제공된 경우 이 URL이 해당 인용의 소스 웹페이지로 연결됩니다. 가능한 URL에는 뉴스 웹사이트, GitHub 저장소 등이 포함됩니다.
title 이 인용과 연결된 제목입니다. 제공된 경우 이 인용의 소스 제목을 나타냅니다. 가능한 제목에는 뉴스 제목, 책 제목 등이 포함됩니다.
license 인용과 연결된 라이선스입니다. 제공된 경우 이 인용의 소스에 대한 라이선스를 나타냅니다. 가능한 라이선스에는 코드 라이선스가 포함됩니다(예: mit 라이선스).
publicationDate 이 인용과 연결된 게시 날짜입니다. 제공된 경우 이 인용의 소스가 게시된 날짜를 나타냅니다. 가능한 형식은 YYYY, YYYY-MM, YYYY-MM-DD입니다.
safetyAttributes 카테고리 및 연결된 신뢰도 점수의 컬렉션입니다. candidates에 대한 1:1 매핑입니다.
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
      },
      "candidates": [
        {
          "author": "AUTHOR",
          "content": "RESPONSE"
        }
      ]
    }
  ]
}

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

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

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

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