코드 완성

Codey for Code Completion(code-gecko)은 코드 완성을 지원하는 모델의 이름입니다. 이 모델은 작성 중인 코드를 기반으로 코드를 생성하는 기반 모델입니다. Codey for Code Completion은 사용자가 최근에 입력한 코드를 완성합니다. Codey for Code Completion은 코드 생성 API에서 지원됩니다. Codey API는 PaLM API 제품군에 포함됩니다.

코드 완성을 위한 프롬프트 만들기 방법은 코드 완성을 위한 프롬프트 만들기를 참조하세요.

콘솔에서 이 모델을 살펴보려면 Model Garden에서 Codey for Code Completion 모델 카드를 참조하세요.
Model Garden으로 이동

사용 사례

코드 완성을 위한 몇 가지 일반적인 사용 사례는 다음과 같습니다.

  • 더 빠른 코드 작성: code-gecko 모델을 사용해서 제안된 코드를 활용하여 코드를 빠르게 작성할 수 있습니다.

  • 코드 버그 최소화: 오류 방지를 위해 구문적으로 올바른 것으로 알고 있는 코드 제안을 사용합니다. 코드 완성을 통해 코드를 빠르게 작성할 때 발생할 수 있는 버그를 실수로 일으킬 위험을 최소화할 수 있습니다.

HTTP 요청

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

모델 버전

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

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

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

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

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

요청 본문

{
  "instances":[
    {
      "prefix": string,
      "suffix": string
    }
  ],
  "parameters": {
    "temperature": number,
    "maxOutputTokens": integer,
    "candidateCount": integer,
    "stopSequences": [ string ],
    "logprobs": integer,
    "presencePenalty": float,
    "frequencyPenalty": float,
    "echo": boolean,
    "seed": integer
  }
}

다음은 code-gecko라는 코드 완성 모델의 매개변수입니다. code-gecko 모델은 Codey 모델 중 하나입니다. 이러한 매개변수를 사용하여 코드 완성 프롬프트를 최적화할 수 있습니다. 자세한 내용은 코드 모델 개요코드 완성 프롬프트 만들기를 참조하세요.

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

prefix

(필수)

코드 모델에서 prefix는 생성할 코드를 설명하는 의미 있는 프로그래밍 코드 조각 또는 자연어 프롬프트의 시작 부분을 나타냅니다. 모델이 prefixsuffix 사이의 코드를 채우려고 시도합니다. 유효한 텍스트 문자열

suffix

(선택사항)

코드 완성에서 suffix는 의미 있는 프로그래밍 코드 조각의 끝 부분을 나타냅니다. 모델이 prefixsuffix 사이의 코드를 채우려고 시도합니다. 유효한 텍스트 문자열

temperature

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

0.0–1.0

Default: 0.2

maxOutputTokens

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

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

1-64

Default: 64

candidateCount

(선택사항)

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

1-4

Default: 1

(선택사항)

stopSequences

(선택사항)

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

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

public static string reverse(string myString)

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

public static string
문자열 목록입니다.

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

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

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

Optional

샘플 요청

REST

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

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

  • PROJECT_ID: 프로젝트 ID
  • 다른 필드에 대해서는 요청 본문 테이블을 참조하세요.

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

응답 본문

{
  "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 ]
      },
      "score": float
    }
  ]
}
응답 요소 설명
blocked 모델의 입력이나 출력이 차단되었는지 여부를 나타내는 안전 속성과 연결된 boolean 플래그입니다. blockedtrue이면 응답의 errors 필드에 오류 코드가 하나 이상 포함됩니다. blockedfalse이면 응답에 errors 필드가 포함되지 않습니다.
categories 생성된 콘텐츠와 연결된 안전 속성 카테고리 이름의 목록입니다. scores 매개변수의 점수 순서는 카테고리 순서와 일치합니다. 예를 들어 scores 매개변수의 첫 번째 점수는 응답이 categories 목록의 첫 번째 카테고리를 위반할 가능성을 나타냅니다.
citationMetadata 인용 배열을 포함하는 요소입니다.
citations 인용의 배열입니다. 각 인용에 해당 메타데이터가 포함됩니다.
content 입력 텍스트를 사용해서 모델에서 생성된 결과입니다.
endIndex content에서 인용이 끝나는 위치를 지정하는 정수입니다.
errors 오류 코드 배열입니다. errors 응답 필드는 응답의 blocked 필드가 true인 경우에만 응답에 포함됩니다. 오류 코드를 이해하는 방법에 대한 자세한 내용은 안전 오류를 참조하세요.
license 인용과 연결된 라이선스입니다.
publicationDate 인용이 게시된 날짜입니다. 유효한 형식은 YYYY, YYYY-MM, YYYY-MM-DD입니다.
score 0보다 작은 float 값입니다. score 값이 클수록 모델 응답의 신뢰도가 커집니다.
startIndex 콘텐츠에서 인용이 시작되는 위치를 지정하는 정수입니다.
title 인용 출처의 제목입니다. 소스 제목의 예시에는 뉴스 기사 또는 도서가 있습니다.
url 인용 출처의 URL입니다. URL 소스의 예시에는 뉴스 웹사이트 또는 GitHub 저장소가 있습니다.
tokens 샘플링된 토큰입니다.
tokenLogProbs 샘플링된 토큰의 로그 확률입니다.
topLogProbs 각 단계에서 확률이 가장 높은 후보 토큰과 해당하는 로그 확률입니다.
logprobs `logprobs` 매개변수 결과입니다. `candidates`에 1:1 매핑됩니다.

샘플 응답

{
  "predictions": [
    {
      "safetyAttributes": {
        "blocked": false,
        "categories": [],
        "scores": []
      },
      "content": " reverses a string",
      "citationMetadata": {
        "citations": []
      }
    },
    "score": -1.1161688566207886
  ]
}

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

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

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

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