코드 완성 프롬프트 테스트

제대로 작동하는 프롬프트를 설계하려면 여러 버전의 프롬프트를 테스트하고 프롬프트 매개변수로 실험하여 최적의 응답을 가져오는 요소를 결정합니다. Codey API와 Google Cloud 콘솔에서 Vertex AI Studio를 사용하여 프로그래매틱 방식으로 프롬프트를 테스트할 수 있습니다.

코드 완성 프롬프트 테스트

코드 완성 프롬프트를 테스트하려면 다음 방법 중 하나를 선택합니다.

REST

Vertex AI API를 사용하여 코드 완성 프롬프트를 테스트하려면 게시자 모델 엔드포인트에 POST 요청을 보냅니다.

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

  • PROJECT_ID: 프로젝트 ID
  • PREFIX: 코드 모델에서 prefix는 생성할 코드를 설명하는 의미 있는 프로그래밍 코드 조각 또는 자연어 프롬프트의 시작 부분을 나타냅니다. 모델이 prefixsuffix 사이의 코드를 채우려고 시도합니다.
  • SUFFIX: 코드 완성에서 suffix는 의미 있는 프로그래밍 코드 조각의 끝 부분을 나타냅니다. 모델이 prefixsuffix 사이의 코드를 채우려고 시도합니다.
  • TEMPERATURE: 강도는 응답 생성 중 샘플링에 사용됩니다. 강도는 토큰 선택의 무작위성 수준을 제어합니다. 강도가 낮을수록 자유롭거나 창의적인 답변과 거리가 먼 응답이 필요한 프롬프트에 적합하고, 강도가 높을수록 보다 다양하거나 창의적인 결과로 이어질 수 있습니다. 강도가 0이면 확률이 가장 높은 토큰이 항상 선택됩니다. 이 경우 특정 프롬프트에 대한 응답은 대부분 확정적이지만 여전히 약간의 변형이 가능합니다.
  • MAX_OUTPUT_TOKENS: 응답에서 생성될 수 있는 토큰의 최대 개수입니다. 토큰은 약 4자(영문 기준)입니다. 토큰 100개는 단어 약 60~80개에 해당합니다.

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

  • CANDIDATE_COUNT: 반환할 응답 변형의 개수입니다. 유효한 값 범위는 1~4 사이의 int입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "instances": [
    { "prefix": "PREFIX",
      "suffix": "SUFFIX"}
  ],
  "parameters": {
    "temperature": TEMPERATURE,
    "maxOutputTokens": MAX_OUTPUT_TOKENS,
    "candidateCount": CANDIDATE_COUNT
  }
}

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

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

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

Python

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

from vertexai.language_models import CodeGenerationModel

def complete_code_function(temperature: float = 0.2) -> object:
    """Example of using Codey for Code Completion to complete a function."""

    # TODO developer - override these parameters as needed:
    parameters = {
        "temperature": temperature,  # Temperature controls the degree of randomness in token selection.
        "max_output_tokens": 64,  # Token limit determines the maximum amount of text output.
    }

    code_completion_model = CodeGenerationModel.from_pretrained("code-gecko@001")
    response = code_completion_model.predict(
        prefix="def reverse_string(s):", **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 = 'code-gecko@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 = {
    prefix:
      'def reverse_string(s): \
        return s[::-1] \
      #This function',
  };
  const instanceValue = helpers.toValue(prompt);
  const instances = [instanceValue];

  const parameter = {
    temperature: 0.2,
    maxOutputTokens: 64,
  };
  const parameters = helpers.toValue(parameter);

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

  // Predict request
  const [response] = await predictionServiceClient.predict(request);
  console.log('Get code completion 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.InvalidProtocolBufferException;
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 PredictCodeCompletionCommentSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace this variable before running the sample.
    String project = "YOUR_PROJECT_ID";

    // Learn how to create prompts to work with a code model to create code completion suggestions:
    // https://cloud.google.com/vertex-ai/docs/generative-ai/code/code-completion-prompts
    String instance =
        "{ \"prefix\": \""
            + "def reverse_string(s):\n"
            + "  return s[::-1]\n"
            + "#This function"
            + "\"}";
    String parameters = "{\n" + "  \"temperature\": 0.2,\n" + "  \"maxOutputTokens\": 64,\n" + "}";
    String location = "us-central1";
    String publisher = "google";
    String model = "code-gecko@001";

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

  // Use Codey for Code Completion to complete a code comment
  public static void predictComment(
      String instance,
      String parameters,
      String project,
      String location,
      String publisher,
      String model)
      throws IOException {
    final 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);

      Value instanceValue = stringToValue(instance);
      List<Value> instances = new ArrayList<>();
      instances.add(instanceValue);

      Value parameterValue = stringToValue(parameters);

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

  // Convert a Json string to a protobuf.Value
  static Value stringToValue(String value) throws InvalidProtocolBufferException {
    Value.Builder builder = Value.newBuilder();
    JsonFormat.parser().merge(value, builder);
    return builder.build();
  }
}

Console

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

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

    Vertex AI Studio로 이동

  2. 시작하기를 클릭합니다.
  3. 코드 프롬프트를 클릭합니다.
  4. 모델에서 code-gecko으로 시작하는 이름의 모델을 선택합니다. code-gecko 다음의 3자릿수 숫자는 모델의 버전 번호를 나타냅니다. 예를 들어 code-gecko@002은(는) 코드 완성 모델의 안정화 버전인 버전 2의 이름입니다.
  5. 프롬프트에 코드 완성 프롬프트를 입력합니다.
  6. 강도토큰 제한을 조정하여 응답에 미치는 영향을 실험합니다. 자세한 내용은 코드 완성 모델 매개변수를 참조하세요.
  7. 제출을 클릭하여 응답을 생성합니다.
  8. 프롬프트를 저장하려면 저장을 클릭합니다.
  9. 코드 보기를 클릭하여 프롬프트에 대한 Python 코드 또는 curl 명령어를 확인합니다.

curl 명령어 예시

MODEL_ID="code-gecko"
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': [
      { 'prefix': 'def reverse_string(s):',
        'suffix': ''
    }
  ],
  'parameters': {
    'temperature': 0.2,
    'maxOutputTokens': 64,
    'candidateCount': 1
  }
}"

코드 완성을 위한 프롬프트 설계에 대한 자세한 내용은 코드 완성을 위한 프롬프트 만들기를 참조하세요.

코드 모델의 응답 스트리밍

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

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

다음 단계