코드 채팅

Code Chat용 Codey(codechat-bison)는 코드 채팅을 지원하는 모델의 이름입니다. 이 모델은 코드에 특화된 멀티턴(multi-turn) 대화를 지원하는 기반 모델입니다. 이 모델을 사용하면 개발자가 챗봇과 채팅하여 코드 관련 질문에 대한 도움을 받을 수 있습니다. 코드 채팅 API는 Code Chat용 Codey 모델과 상호작용하는 데 사용됩니다.

Code Chat용 Codey는 지속적으로 대화에 참여할 수 있도록 주고 받는 상호작용으로 완성되는 코드 태스크에 적합합니다. 단일 상호작용이 필요한 코드 태스크의 경우 코드 완성용 API 또는 코드 생성용 API를 사용합니다.

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

사용 사례

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

  • 코드에 대한 도움말 보기: API에 대한 질문, 지원되는 프로그래밍 언어의 문법 또는 작성 중인 코드에 필요한 라이브러리 버전 등 코드에 대한 질문에 도움이 됩니다.

  • 디버깅: 컴파일되지 않거나 버그가 포함된 코드를 디버깅하는 데 도움이 됩니다.

  • 문서화: 코드를 정확하게 문서화할 수 있도록 코드를 이해하는 데 도움이 됩니다.

  • 코드에 대해 알아보기: 익숙하지 않은 코드에 대한 학습하는 데 도움이 됩니다.

HTTP 요청

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

모델 버전

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

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

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

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

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

요청 본문

{
  "instances": [
    {
      "context": string,
      "messages": [
        {
          "content": string,
          "author": string
        }
      ]
    }
  ],
  "parameters":{
    "temperature": number,
    "maxOutputTokens": integer,
    "candidateCount": integer,
    "logprobs": integer,
    "presencePenalty": float,
    "frequencyPenalty": float,
    "seed": integer
  }
}

다음은 codechat-bison이라는 코드 채팅 모델의 매개변수입니다. codechat-bison 모델은 Codey 모델 중 하나입니다. 이러한 매개변수를 사용하면 코드에 대한 챗봇 대화 프롬프트를 최적화할 수 있습니다. 자세한 내용은 코드 모델 개요코드에 대한 채팅 프롬프트 만들기를 참조하세요.

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

context

응답을 근거로 하기위해 모델에 먼저 제공해야 하는 텍스트입니다. 텍스트

messages

(필수)

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

List[Structured Message]
    "author": "user",
     "content": "user message"

temperature

(선택사항)

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

0.0–1.0

Default: 0.2

maxOutputTokens

(선택사항)

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

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

1–2048

Default: 1024

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 요청을 게시자 모델 엔드포인트로 전송합니다.

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

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

    HTTP 메서드 및 URL:

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

    JSON 요청 본문:

    {
      "instances": [
        {
          "messages": [
            {
              "author": "AUTHOR",
              "content": "CONTENT"
            }
          ]
        }
      ],
      "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/codechat-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/codechat-bison:predict" | Select-Object -Expand Content

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

Python

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

from vertexai.language_models import CodeChatModel

def write_a_function(temperature: float = 0.5) -> object:
    """Example of using Codey for Code Chat Model to write a function."""

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

    code_chat_model = CodeChatModel.from_pretrained("codechat-bison@001")
    chat = code_chat_model.start_chat()

    response = chat.send_message(
        "Please help write a function to calculate the min of two numbers", **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 = 'codechat-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}`;

  // Learn more about creating prompts to work with a code chat model at:
  // https://cloud.google.com/vertex-ai/docs/generative-ai/code/code-chat-prompts
  const prompt = {
    messages: [
      {
        author: 'user',
        content: 'Hi, how are you?',
      },
      {
        author: 'system',
        content: 'I am doing good. What can I help you in the coding world?',
      },
      {
        author: 'user',
        content:
          'Please help write a function to calculate the min of two numbers',
      },
    ],
  };
  const instanceValue = helpers.toValue(prompt);
  const instances = [instanceValue];

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

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

  // Predict request
  const [response] = await predictionServiceClient.predict(request);
  console.log('Get code chat 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.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.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 PredictCodeChatSample {

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

    // Learn more about creating prompts to work with a code chat model at:
    // https://cloud.google.com/vertex-ai/docs/generative-ai/code/code-chat-prompts
    String instance =
        "{ \"messages\": [\n"
            + "{\n"
            + "  \"author\": \"user\",\n"
            + "  \"content\": \"Hi, how are you?\"\n"
            + "},\n"
            + "{\n"
            + "  \"author\": \"system\",\n"
            + "  \"content\": \"I am doing good. What can I help you in the coding world?\"\n"
            + " },\n"
            + "{\n"
            + "  \"author\": \"user\",\n"
            + "  \"content\":\n"
            + "     \"Please help write a function to calculate the min of two numbers.\"\n"
            + "}\n"
            + "]}";
    String parameters = "{\n" + "  \"temperature\": 0.5,\n" + "  \"maxOutputTokens\": 1024\n" + "}";
    String location = "us-central1";
    String publisher = "google";
    String model = "codechat-bison@001";

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

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

샘플 응답

{
  "predictions": [
    {
      "citationMetadata": [
        {
          "citations": []
        }
      ],
      "candidates": [
        {
          "author": "AUTHOR",
          "content": "RESPONSE"
        }
      ],
      "safetyAttributes": {
        "categories": [],
        "blocked": false,
        "scores": []
      },
      "score": -1.1161688566207886
    }
  ]
}

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

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

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

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