채팅 프롬프트 테스트

Vertex AI를 통해 Vertex AI Studio를 사용하여 Google Cloud 콘솔, Vertex AI API, Python용 Vertex AI SDK에서 프롬프트를 테스트할 수 있습니다. 이 페이지에서는 이러한 인터페이스를 사용하여 채팅 프롬프트를 테스트하는 방법을 보여줍니다.

채팅 프롬프트를 설계하는 방법에 대한 자세한 내용은 채팅 프롬프트를 참조하세요.

채팅 프롬프트 테스트

채팅 프롬프트를 테스트하려면 다음 방법 중 하나를 선택합니다.

REST

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

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

  • PROJECT_ID: 프로젝트 ID
  • CONTEXT: 선택사항. 컨텍스트는 모델이 응답하는 방법에 대해 모델에 제공하는 지침이거나 모델이 응답을 생성하는 데 사용하거나 참조하는 정보일 수 있습니다. 모델에 정보를 제공해야 할 때 프롬프트에 컨텍스트 정보를 추가하거나 컨텍스트 내에 있는 정보만으로 응답 경계를 제한합니다.
  • 선택사항 예시: 이 예시는 대화에 응답하는 방법을 학습하기 위해 모델에 보내는 구조화된 메시지 목록입니다.
    • EXAMPLE_INPUT: 메시지 예시입니다.
    • EXAMPLE_OUTPUT: 이상적인 응답의 예시입니다.
  • 메시지: 저자가 구분된 구조화된 양식으로 모델에 제공된 대화 기록입니다. 메시지는 오래된 것부터 최근 것까지 시간순으로 표시됩니다. 메시지 기록으로 인해 입력이 최대 길이를 초과할 경우 전체 프롬프트가 허용 범위 내에 들어올 때까지 가장 오래된 메시지가 삭제됩니다. 모델이 응답을 생성하려면 메시지 수(AUTHOR-CONTENT 쌍)가 홀수여야 합니다.
    • AUTHOR: 메시지의 저자입니다.
    • CONTENT: 메시지 콘텐츠입니다.
  • TEMPERATURE: 강도는 응답 생성 중 샘플링에 사용되며 topPtopK가 적용될 때 발생합니다. 강도는 토큰 선택의 무작위성 수준을 제어합니다. 강도가 낮을수록 자유롭거나 창의적인 답변과 거리가 먼 응답이 필요한 프롬프트에 적합하고, 강도가 높을수록 보다 다양하거나 창의적인 결과로 이어질 수 있습니다. 강도가 0이면 확률이 가장 높은 토큰이 항상 선택됩니다. 이 경우 특정 프롬프트에 대한 응답은 대부분 확정적이지만 여전히 약간의 변형이 가능합니다.

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

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

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

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

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

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

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

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

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 응답이 수신됩니다.

curl 명령어 예시

MODEL_ID="chat-bison"
PROJECT_ID=PROJECT_ID

curl \
-X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/us-central1/publishers/google/models/${MODEL_ID}:predict -d \
'{
  "instances": [{
      "context":  "My name is Ned. You are my personal assistant. My favorite movies are Lord of the Rings and Hobbit.",
      "examples": [ {
          "input": {"content": "Who do you work for?"},
          "output": {"content": "I work for Ned."}
       },
       {
          "input": {"content": "What do I like?"},
          "output": {"content": "Ned likes watching movies."}
       }],
      "messages": [
       {
          "author": "user",
          "content": "Are my favorite movies based on a book series?",
       },
       {
          "author": "bot",
          "content": "Yes, your favorite movies, The Lord of the Rings and The Hobbit, are based on book series by J.R.R. Tolkien.",
       },
       {
          "author": "user",
          "content": "When were these books published?",
       }],
   }],
  "parameters": {
    "temperature": 0.3,
    "maxOutputTokens": 200,
    "topP": 0.8,
    "topK": 40
  }
}'

Python

Python을 설치하거나 업데이트하는 방법은 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");
    }
  }
}

C#

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

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


using Google.Cloud.AIPlatform.V1;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using Value = Google.Protobuf.WellKnownTypes.Value;

public class PredictChatPromptSample
{
    public string PredictChatPrompt(
        string projectId = "your-project-id",
        string locationId = "us-central1",
        string publisher = "google",
        string model = "chat-bison@001"
    )
    {
        // Initialize client that will be used to send requests.
        // This client only needs to be created once,
        // and can be reused for multiple requests.
        var client = new PredictionServiceClientBuilder
        {
            Endpoint = $"{locationId}-aiplatform.googleapis.com"
        }.Build();

        // Configure the parent resource.
        var endpoint = EndpointName.FromProjectLocationPublisherModel(projectId, locationId, publisher, model);

        // Initialize request argument(s).
        var prompt = "How many planets are there in the solar system?";

        // You can construct Protobuf from JSON.
        var instanceJson = JsonConvert.SerializeObject(new
        {
            context = "My name is Miles. You are an astronomer, knowledgeable about the solar system.",
            examples = new[]
            {
                new
                {
                    input = new { content = "How many moons does Mars have?" },
                    output = new { content = "The planet Mars has two moons, Phobos and Deimos." }
                }
            },
            messages = new[]
            {
                new
                {
                    author = "user",
                    content = prompt
                }
            }
        });
        var instance = Value.Parser.ParseJson(instanceJson);

        var instances = new List<Value>
        {
            instance
        };

        // You can construct Protobuf from JSON.
        var parametersJson = JsonConvert.SerializeObject(new
        {
            temperature = 0.3,
            maxDecodeSteps = 200,
            topP = 0.8,
            topK = 40
        });
        var parameters = Value.Parser.ParseJson(parametersJson);

        // Make the request.
        var response = client.Predict(endpoint, instances, parameters);

        // Parse the response and return the content.
        var content = response.Predictions.First().StructValue.Fields["candidates"].ListValue.Values[0].StructValue.Fields["content"].StringValue;
        Console.WriteLine($"Content: {content}");
        return content;
    }
}

Console

Vertex AI Studio를 사용하여 Google Cloud 콘솔에서 채팅 프롬프트를 테스트하려면 다음을 수행합니다.

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

    Vertex AI Studio로 이동

  2. 시작하기 탭을 클릭합니다.
  3. 문자 채팅을 클릭합니다.
  4. 다음과 같이 프롬프트를 구성합니다.

    • 컨텍스트: 모델로 수행하려는 태스크에 대한 안내를 입력하고 모델이 참조할 상황별 정보를 포함합니다.
    • 예시: 퓨샷 프롬프트의 경우 모델이 모방할 행동 패턴을 나타내는 입력-출력 예시를 추가합니다.
  5. 모델 및 매개변수를 구성합니다.

    • 모델: 사용하려는 모델을 선택합니다.
    • 강도: 슬라이더 또는 텍스트 상자를 사용해서 강도 값을 입력합니다.

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

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

    • 토큰 제한: 슬라이더 또는 텍스트 상자를 사용하여 최대 출력 한도의 값을 입력합니다.

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

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

    • Top-K: 슬라이더 또는 텍스트 상자를 사용하여 최상위 K의 값을 입력합니다.

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

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

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

    • Top-P: 슬라이더 또는 텍스트 상자를 사용하여 최상위 P의 값을 입력합니다. 토큰의 확률 합계가 최상위 P 값과 같아질 때까지 확률이 가장 높은 순에서 낮은 순으로 토큰이 선택됩니다. 최소 변수 결과의 경우 top-P를 0으로 설정합니다.
  6. 챗봇과 대화를 시작하려면 메시지 상자에 메시지를 입력합니다. 챗봇은 이전 메시지를 새 응답의 컨텍스트로 사용합니다.
  7. 선택사항: 프롬프트를 내 프롬프트에 저장하려면 저장을 클릭합니다.
  8. 선택사항: 프롬프트에 대해 Python 코드 또는 curl 명령어를 가져오려면 코드 보기를 클릭합니다.
  9. 선택사항: 이전 메시지를 모두 지우려면 대화 지우기를 클릭합니다.

채팅 모델의 응답 스트리밍

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

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

다음 단계