반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

Guide - Code completion

2023. 1. 9. 08:01 | Posted by 솔웅


반응형

Code completion 

Limited beta

Learn how to generate or manipulate code

Introduction

The Codex model series is a descendant of our GPT-3 series that's been trained on both natural language and billions of lines of code. It's most capable in Python and proficient in over a dozen languages including JavaScript, Go, Perl, PHP, Ruby, Swift, TypeScript, SQL, and even Shell. During this initial limited beta period, Codex usage is free. Learn more.

 

Codex 모델 시리즈는 자연어와 수십억 줄의 코드에 대해 훈련된 GPT-3 시리즈의 후손입니다. Python에서 가장 유능하며 JavaScript, Go, Perl, PHP, Ruby, Swift, TypeScript, SQL 및 Shell을 포함한 12개 이상의 언어에 능숙합니다. 이 초기 제한 베타 기간 동안 Codex 사용은 무료입니다. 더 알아보기.

 

You can use Codex for a variety of tasks including:

  • Turn comments into code
  • Complete your next line or function in context
  • Bring knowledge to you, such as finding a useful library or API call for an application
  • Add comments
  • Rewrite code for efficiency

다음과 같은 다양한 작업에 Codex를 사용할 수 있습니다.
* 주석을 코드로 변환
* 컨텍스트에서 다음 라인 또는 기능을 완료하십시오.
* 유용한 라이브러리 찾기 또는 응용 프로그램에 대한 API 호출과 같은 지식 제공
* 주석 추가
* 효율성을 위해 코드 재작성

 

To see Codex in action, check out our Codex JavaScript Sandbox or our other demo videos.

 

Codex가 작동하는 모습을 보려면 Codex JavaScript Sandbox 또는 다른 데모 비디오를 확인하십시오.

 

 

Quickstart

To start using Codex yourself, try opening these examples in the Playground.  

 

Codex를 직접 사용하려면 플레이그라운드에서 이 예제를 열어보십시오.

 

Saying "Hello" (Python)

"""
Ask the user for their name and say "Hello"
"""
Open in Playground

Create random names (Python)

"""
1. Create a list of first names
2. Create a list of last names
3. Combine them randomly into a list of 100 full names
"""
Open in Playground

Create a MySQL query (Python)

"""
Table customers, columns = [CustomerId, FirstName, LastName, Company, Address, City, State, Country, PostalCode, Phone, Fax, Email, SupportRepId]
Create a MySQL query for all customers in Texas named Jane
"""
query =
Open in Playground

Explaining code (JavaScript)

// Function 1
var fullNames = [];
for (var i = 0; i < 50; i++) {
  fullNames.push(names[Math.floor(Math.random() * names.length)]
    + " " + lastNames[Math.floor(Math.random() * lastNames.length)]);
}

// What does Function 1 do?
Open in Playground

More examples

Visit our examples library to explore more prompts designed for Codex.

 

Codex용으로 설계된 더 많은 프롬프트를 탐색하려면 예제 라이브러리를 방문하십시오.

 

Best practices

Start with a comment, data or code. You can experiment using one of the Codex models in our playground (styling instructions as comments when needed.)

To get Codex to create a useful completion it's helpful to think about what information a programmer would need to perform a task. This could simply be a clear comment or the data needed to write a useful function, like the names of variables or what class a function handles.

 

주석, 데이터 또는 코드로 시작하십시오. 플레이그라운드에서 Codex 모델 중 하나를 사용하여 실험할 수 있습니다(필요한 경우 주석으로 스타일 지정 지침).
Codex가 유용한 코드 완성을 만들려면 프로그래머가 작업을 수행하는 데 어떤 정보가 필요한지 생각하는 것이 좋습니다. 이것은 단순히 명확한 주석이거나 변수 이름이나 함수가 처리하는 클래스와 같이 유용한 함수를 작성하는 데 필요한 데이터일 수 있습니다.

 

# Create a function called 'nameImporter' to add a first and last name to the database
Open in Playground

 

In this example we tell Codex what to call the function and what task it's going to perform.

This approach scales even to the point where you can provide Codex with a comment and an example of a database schema to get it to write useful query requests for various databases.

 

이 예에서 우리는 Codex에게 함수를 호출할 대상과 수행할 작업을 알려줍니다.
이 접근 방식은 다양한 데이터베이스에 대한 유용한 쿼리 요청을 작성할 수 있도록 Codex에 주석과 데이터베이스 스키마의 예를 제공할 수 있는 지점까지 확장됩니다.

 

# Table albums, columns = [AlbumId, Title, ArtistId]
# Table artists, columns = [ArtistId, Name]
# Table media_types, columns = [MediaTypeId, Name]
# Table playlists, columns = [PlaylistId, Name]
# Table playlist_track, columns = [PlaylistId, TrackId]
# Table tracks, columns = [TrackId, Name, AlbumId, MediaTypeId, GenreId, Composer, Milliseconds, Bytes, UnitPrice]

# Create a query for all albums by Adele
Open in Playground

 

When you show Codex the database schema it's able to make an informed guess about how to format a query.

Specify the language. Codex understands dozens of different programming languages. Many share similar conventions for comments, functions and other programming syntax. By specifying the language and what version in a comment, Codex is better able to provide a completion for what you want. That said, Codex is fairly flexible with style and syntax.

 

Codex에 데이터베이스 스키마를 표시하면 쿼리 형식을 지정하는 방법에 대해 정보에 입각한 추측을 할 수 있습니다.
언어를 지정합니다. Codex는 수십 가지의 다양한 프로그래밍 언어를 이해합니다. 많은 사람들이 주석, 함수 및 기타 프로그래밍 구문에 대해 유사한 규칙을 공유합니다. 주석에 언어와 버전을 지정함으로써 Codex는 원하는 것을 더 잘 완성할 수 있습니다. 즉, Codex는 스타일과 구문이 상당히 유연합니다.

 

# R language
# Calculate the mean distance between an array of points
Open in Playground
# Python 3
# Calculate the mean distance between an array of points
Open in Playground

 

Prompt Codex with what you want it to do. If you want Codex to create a webpage, placing the first line of code in an HTML document (<!DOCTYPE html>) after your comment tells Codex what it should do next. The same method works for creating a function from a comment (following the comment with a new line starting with func or def).

 

원하는 작업을 Codex에 표시하십시오. Codex가 웹페이지를 생성하도록 하려면 HTML 문서(<!DOCTYPE html>)에 코드의 첫 번째 줄을 입력한 후 Codex에 다음에 수행할 작업을 알려줍니다. 동일한 방법이 주석에서 함수를 생성하는 데 작동합니다(주석 뒤에 func 또는 def로 시작하는 새 줄이 있음).

 

<!-- Create a web page with the title 'Kat Katman attorney at paw' -->
<!DOCTYPE html>
Open in Playground

 

Placing <!DOCTYPE html> after our comment makes it very clear to Codex what we want it to do.

 

주석 뒤에 <!DOCTYPE html>을 넣으면 Codex가 원하는 작업을 매우 명확하게 알 수 있습니다.

 

# Create a function to count to 100

def counter
Open in Playground

 

If we start writing the function Codex will understand what it needs to do next.

Specifying libraries will help Codex understand what you want. Codex is aware of a large number of libraries, APIs and modules. By telling Codex which ones to use, either from a comment or importing them into your code, Codex will make suggestions based upon them instead of alternatives.

 

함수 작성을 시작하면 Codex는 다음에 해야 할 일을 이해할 것입니다.
라이브러리를 지정하면 Codex가 원하는 것을 이해하는 데 도움이 됩니다. Codex는 수많은 라이브러리, API 및 모듈을 알고 있습니다. 주석에서 또는 코드로 가져오기를 통해 Codex에 어떤 것을 사용해야 하는지 알려줌으로써 Codex는 대안 대신 이를 기반으로 제안을 합니다.

 

<!-- Use A-Frame version 1.2.0 to create a 3D website -->
Open in Playground

 

By specifying the version you can make sure Codex uses the most current library.

Note: Codex can suggest helpful libraries and APIs, but always be sure to do your own research to make sure that they're safe for your application.

Comment style can affect code quality. With some languages the style of comments can improve the quality of the output. For example, when working with Python, in some cases using doc strings (comments wrapped in triple quotes) can give higher quality results than using the pound (#) symbol.

 

버전을 지정하면 Codex가 최신 라이브러리를 사용하도록 할 수 있습니다.
참고: Codex는 유용한 라이브러리와 API를 제안할 수 있지만 항상 자신의 응용 프로그램에 대해 안전한지 확인하기 위해 자체 조사를 수행해야 합니다.
주석 스타일은 코드 품질에 영향을 미칠 수 있습니다. 일부 언어에서는 주석 스타일이 출력 품질을 향상시킬 수 있습니다. 예를 들어 Python으로 작업할 때 경우에 따라 doc 문자열(3중 따옴표로 묶인 주석)을 사용하면 파운드(#) 기호를 사용하는 것보다 더 나은 품질의 결과를 얻을 수 있습니다.

 

"""
Create an array of users and email addresses
"""
Open in Playground

 

Put comments inside of functions can be helpful. Recommended coding standards usually suggest placing the description of a function inside the function. Using this format helps Codex more clearly understand what you want the function to do.

 

함수 내부에 주석을 넣는 것이 도움이 될 수 있습니다. 권장되는 코딩 표준은 일반적으로 함수 내부에 함수 설명을 배치할 것을 제안합니다. 이 형식을 사용하면 Codex가 함수에서 원하는 작업을 보다 명확하게 이해할 수 있습니다.

 

def getUserBalance(id):
    """
    Look up the user in the database ‘UserData' and return their current account balance.
    """
Open in Playground

 

Provide examples for more precise results. If you have a particular style or format you need Codex to use, providing examples or demonstrating it in the first part of the request will help Codex more accurately match what you need.

 

보다 정확한 결과를 위해 예를 제공하십시오. Codex가 사용해야 하는 특정 스타일이나 형식이 있는 경우 요청의 첫 번째 부분에서 예제를 제공하거나 시연하면 Codex가 필요한 것을 보다 정확하게 일치시키는 데 도움이 됩니다.

 

"""
Create a list of random animals and species
"""
animals  = [ {"name": "Chomper", "species": "Hamster"}, {"name":
Open in Playground

 

Lower temperatures give more precise results. Setting the API temperature to 0, or close to zero (such as 0.1 or 0.2) tends to give better results in most cases. Unlike GPT-3, where a higher temperature can provide useful creative and random results, higher temperatures with Codex may give you really random or erratic responses.

In cases where you need Codex to provide different potential results, start at zero and then increment upwards by .1 until you find suitable variation.

 

온도가 낮을수록 더 정확한 결과를 얻을 수 있습니다. API 온도를 0으로 설정하거나 0에 가깝게(예: 0.1 또는 0.2) 설정하면 대부분의 경우 더 나은 결과를 얻을 수 있습니다. 더 높은 온도가 유용한 창의적이고 임의적인 결과를 제공할 수 있는 GPT-3와 달리 Codex의 높은 온도는 정말 임의적이거나 불규칙한 응답을 제공할 수 있습니다.
다른 잠재적 결과를 제공하기 위해 Codex가 필요한 경우 0에서 시작하여 적절한 변형을 찾을 때까지 0.1씩 위쪽으로 증가합니다.

 

Organize tasks into functions. We can get Codex to write functions by specifying what the function should do in as precise terms as possible in comment. By writing the following comment, Codex creates a Javascript timer function that's triggered when a user presses a button:

A simple JavaScript timer

 

작업을 기능으로 구성합니다. 주석에서 가능한 한 정확한 용어로 함수가 수행해야 하는 작업을 지정하여 Codex가 함수를 작성하도록 할 수 있습니다. Codex는 다음 주석을 작성하여 사용자가 버튼을 누를 때 트리거되는 Javascript 타이머 기능을 생성합니다.
간단한 JavaScript 타이머

 

// Create a timer that creates an alert in 10 seconds
Open in Playground

 

We can use Codex to perform common tasks with well known libraries like creating a customer with the Stripe API:

Create a Stripe customer in Python

 

Codex를 사용하여 Stripe API로 고객을 생성하는 것과 같이 잘 알려진 라이브러리로 일반적인 작업을 수행할 수 있습니다.
Python에서 Stripe 고객 만들기

 

# Create a Stripe customer from an email address
Open in Playground

 

Creating example data. Testing applications often requires using example data. Because Codgen is a language model that understands how to comprehend and write natural language, you can ask Codex to create data like arrays of made up names, products and other variables.

 

예제 데이터를 생성합니다. 응용 프로그램을 테스트하려면 종종 예제 데이터를 사용해야 합니다. Codgen은 자연어를 이해하고 쓰는 방법을 이해하는 언어 모델이기 때문에 Codex에 구성된 이름, 제품 및 기타 변수의 배열과 같은 데이터를 생성하도록 요청할 수 있습니다.

 

/* Create an array of weather temperatures for San Francisco */
Open in Playground

 

Asking Codex to perform this task will produce a table like this:

 

Codex에게 이 작업을 수행하도록 요청하면 다음과 같은 테이블이 생성됩니다.

 

var weather = [
  { month: 'January', high: 58, low: 48 },
  { month: 'February', high: 61, low: 50 },
  { month: 'March', high: 64, low: 53 },
  { month: 'April', high: 67, low: 55 },
  { month: 'May', high: 70, low: 58 },
  { month: 'June', high: 73, low: 61 },
  { month: 'July', high: 76, low: 63 },
  { month: 'August', high: 77, low: 64 },
  { month: 'September', high: 76, low: 63 },
  { month: 'October', high: 73, low: 61 },
  { month: 'November', high: 68, low: 57 },
  { month: 'December', high: 64, low: 54 }
];
Open in Playground

 

Compound functions and small applications. We can provide Codex with a comment consisting of a complex request like creating a random name generator or performing tasks with user input and Codex can generate the rest provided there are enough tokens.

 

복합 함수 및 소규모 응용 프로그램. 임의 이름 생성기 생성 또는 사용자 입력으로 작업 수행과 같은 복잡한 요청으로 구성된 설명을 Codex에 제공할 수 있으며 Codex는 충분한 토큰이 있는 경우 나머지를 생성할 수 있습니다.

 

/*
Create a list of animals
Create a list of cities
Use the lists to generate stories about what I saw at the zoo in each city
*/
Open in Playground

 

Limit completion size for more precise results or lower latency. Requesting longer completions in Codex can lead to imprecise answers and repetition. Limit the size of the query by reducing max_tokens and setting stop tokens. For instance, add \n as a stop sequence to limit completions to one line of code. Smaller completions also incur less latency.

Use streaming to reduce latency. Large Codex queries can take tens of seconds to complete. To build applications that require lower latency, such as coding assistants that perform autocompletion, consider using streaming. Responses will be returned before the model finishes generating the entire completion. Applications that need only part of a completion can reduce latency by cutting off a completion either programmatically or by using creative values for stop.

Users can combine streaming with duplication to reduce latency by requesting more than one solution from the API, and using the first response returned. Do this by setting n > 1. This approach consumes more token quota, so use carefully (e.g., by using reasonable settings for max_tokens and stop).

Use Codex to explain code. Codex's ability to create and understand code allows us to use it to perform tasks like explaining what the code in a file does. One way to accomplish this is by putting a comment after a function that starts with "This function" or "This application is." Codex will usually interpret this as the start of an explanation and complete the rest of the text.

 

보다 정확한 결과 또는 대기 시간 단축을 위해 완료 크기를 제한합니다. Codex에서 더 긴 완료를 요청하면 부정확한 답변과 반복이 발생할 수 있습니다. max_tokens를 줄이고 중지 토큰을 설정하여 쿼리 크기를 제한합니다. 예를 들어 한 줄의 코드로 완료를 제한하려면 중지 시퀀스로 \n을 추가합니다. 완료 횟수가 적을수록 대기 시간도 줄어듭니다.


대기 시간을 줄이려면 스트리밍을 사용하십시오. 큰 Codex 쿼리는 완료하는 데 수십 초가 걸릴 수 있습니다. 자동 완성을 수행하는 코딩 도우미와 같이 짧은 대기 시간이 필요한 애플리케이션을 구축하려면 스트리밍을 사용하는 것이 좋습니다. 모델이 전체 완료 생성을 완료하기 전에 응답이 반환됩니다. 완료의 일부만 필요한 애플리케이션은 프로그래밍 방식으로 완료를 차단하거나 중지에 대한 창의적인 값을 사용하여 대기 시간을 줄일 수 있습니다.


사용자는 스트리밍과 복제를 결합하여 API에서 둘 이상의 솔루션을 요청하고 반환된 첫 번째 응답을 사용하여 대기 시간을 줄일 수 있습니다. n > 1로 설정하여 이를 수행하십시오. 이 접근 방식은 더 많은 토큰 할당량을 소비하므로 신중하게 사용하십시오(예: max_tokens 및 stop에 대한 합리적인 설정 사용).
Codex를 사용하여 코드를 설명하십시오. 코드를 생성하고 이해하는 Codex의 기능을 사용하여 파일의 코드가 수행하는 작업을 설명하는 것과 같은 작업을 수행할 수 있습니다. 이를 수행하는 한 가지 방법은 "이 함수" 또는 "이 애플리케이션은"으로 시작하는 함수 뒤에 주석을 추가하는 것입니다. Codex는 일반적으로 이것을 설명의 시작으로 해석하고 나머지 텍스트를 완성합니다.

 

/* Explain what the previous function is doing: It
Open in Playground

 

Explaining an SQL query. In this example we use Codex to explain in a human readable format what an SQL query is doing.

 

SQL 쿼리 설명. 이 예에서는 Codex를 사용하여 SQL 쿼리가 수행하는 작업을 사람이 읽을 수 있는 형식으로 설명합니다.

 

SELECT DISTINCT department.name
FROM department
JOIN employee ON department.id = employee.department_id
JOIN salary_payments ON employee.id = salary_payments.employee_id
WHERE salary_payments.date BETWEEN '2020-06-01' AND '2020-06-30'
GROUP BY department.name
HAVING COUNT(employee.id) > 10;
-- Explanation of the above query in human readable format
--
Open in Playground

Writing unit tests. Creating a unit test can be accomplished in Python simply by adding the comment "Unit test" and starting a function.

 

단위 테스트 작성. Python에서 "Unit test"라는 주석을 추가하고 함수를 시작하기만 하면 단위 테스트를 만들 수 있습니다.

 

# Python 3
def sum_numbers(a, b):
  return a + b

# Unit test
def
Open in Playground

 

Checking code for errors. By using examples, you can show Codex how to identify errors in code. In some cases no examples are required, however demonstrating the level and detail to provide a description can help Codex understand what to look for and how to explain it. (A check by Codex for errors should not replace careful review by the user. )

 

코드에 오류가 있는지 확인 중입니다. 예제를 사용하여 Codex에서 코드의 오류를 식별하는 방법을 보여줄 수 있습니다. 어떤 경우에는 예가 필요하지 않지만 설명을 제공하기 위해 수준과 세부 사항을 시연하면 Codex가 무엇을 찾고 어떻게 설명해야 하는지 이해하는 데 도움이 될 수 있습니다. (오류에 대한 Codex의 확인은 사용자의 신중한 검토를 대신할 수 없습니다. )

 

/* Explain why the previous function doesn't work. */
Open in Playground

 

Using source data to write database functions. Just as a human programmer would benefit from understanding the database structure and the column names, Codex can use this data to help you write accurate query requests. In this example we insert the schema for a database and tell Codex what to query the database for.

 

소스 데이터를 사용하여 데이터베이스 기능을 작성합니다. 인간 프로그래머가 데이터베이스 구조와 열 이름을 이해하면 도움이 되는 것처럼 Codex는 이 데이터를 사용하여 정확한 쿼리 요청을 작성하는 데 도움을 줄 수 있습니다. 이 예에서는 데이터베이스에 대한 스키마를 삽입하고 Codex에게 데이터베이스를 쿼리할 내용을 알려줍니다.

 

# Table albums, columns = [AlbumId, Title, ArtistId]
# Table artists, columns = [ArtistId, Name]
# Table media_types, columns = [MediaTypeId, Name]
# Table playlists, columns = [PlaylistId, Name]
# Table playlist_track, columns = [PlaylistId, TrackId]
# Table tracks, columns = [TrackId, Name, AlbumId, MediaTypeId, GenreId, Composer, Milliseconds, Bytes, UnitPrice]

# Create a query for all albums by Adele
Open in Playground

 

Converting between languages. You can get Codex to convert from one language to another by following a simple format where you list the language of the code you want to convert in a comment, followed by the code and then a comment with the language you want it translated into.

 

언어 간 변환. 주석에 변환하려는 코드의 언어를 나열한 다음 코드와 번역하려는 언어의 주석을 나열하는 간단한 형식에 따라 Codex를 한 언어에서 다른 언어로 변환할 수 있습니다.

 

# Convert this from Python to R
# Python version

[ Python code ]

# End

# R version
Open in Playground

 

Rewriting code for a library or framework. If you want Codex to make a function more efficient, you can provide it with the code to rewrite followed by an instruction on what format to use.

 

라이브러리 또는 프레임워크용 코드 재작성. Codex가 기능을 더 효율적으로 만들도록 하려면 다시 작성할 코드와 사용할 형식에 대한 지침을 Codex에 제공할 수 있습니다.

 

// Rewrite this as a React component
var input = document.createElement('input');
input.setAttribute('type', 'text');
document.body.appendChild(input);
var button = document.createElement('button');
button.innerHTML = 'Say Hello';
document.body.appendChild(button);
button.onclick = function() {
  var name = input.value;
  var hello = document.createElement('div');
  hello.innerHTML = 'Hello ' + name;
  document.body.appendChild(hello);
};

// React version:
Open in Playground

 

Inserting code 

Beta

The completions endpoint also supports inserting code within code by providing a suffix prompt in addition to the prefix prompt. This can be used to insert a completion in the middle of a function or file.

 

완료 끝점(completions endpoint)은 또한 접두사 프롬프트 외에 접미사 프롬프트를 제공하여 코드 내에 코드 삽입을 지원합니다. 함수나 파일 중간에 완성을 삽입하는 데 사용할 수 있습니다.

 

def get_largest_prime_factor(n):     if n < 2:         return False     def is_prime(n): > for i in range(2, n): > if n % i == 0: > return False > return True >     largest = 1     for j in range(2, n + 1):         if n % j == 0 and is_prime(j):     return largest

 

By providing the model with additional context, it can be much more steerable. However, this is a more constrained and challenging task for the model.

 

모델에 추가 컨텍스트를 제공함으로써 모델을 훨씬 더 조종할 수 있습니다. 그러나 이것은 모델에 대해 더 제한적이고 도전적인 작업입니다.

 

Best practices

Inserting code is a new feature in beta and you may have to modify the way you use the API for better results. Here are a few best practices:

Use max_tokens > 256. The model is better at inserting longer completions. With too small max_tokens, the model may be cut off before it's able to connect to the suffix. Note that you will only be charged for the number of tokens produced even when using larger max_tokens.

Prefer finish_reason == "stop". When the model reaches a natural stopping point or a user provided stop sequence, it will set finish_reason as "stop". This indicates that the model has managed to connect to the suffix well and is a good signal for the quality of a completion. This is especially relevant for choosing between a few completions when using n > 1 or resampling (see the next point).

Resample 3-5 times. While almost all completions connect to the prefix, the model may struggle to connect the suffix in harder cases. We find that resampling 3 or 5 times (or using best_of with k=3,5) and picking the samples with "stop" as their finish_reason can be an effective way in such cases. While resampling, you would typically want a higher temperatures to increase diversity.

Note: if all the returned samples have finish_reason == "length", it's likely that max_tokens is too small and model runs out of tokens before it manages to connect the prompt and the suffix naturally. Consider increasing max_tokens before resampling.

 

코드 삽입은 베타의 새로운 기능이며 더 나은 결과를 위해 API를 사용하는 방식을 수정해야 할 수도 있습니다. 다음은 몇 가지 모범 사례입니다.
max_tokens > 256을 사용하십시오. 모델은 더 긴 완료를 삽입하는 데 더 좋습니다. max_token이 너무 작으면 접미사에 연결하기 전에 모델이 잘릴 수 있습니다. 더 큰 max_tokens를 사용하는 경우에도 생성된 토큰 수에 대해서만 비용이 청구됩니다.


finish_reason == "중지"를 선호합니다. 모델이 자연스러운 중지 지점 또는 사용자가 제공한 중지 시퀀스에 도달하면 finish_reason을 "중지"로 설정합니다. 이것은 모델이 접미사에 잘 연결되었음을 나타내며 완성 품질에 대한 좋은 신호입니다. 이것은 특히 n > 1 또는 리샘플링을 사용할 때 몇 가지 완성 중에서 선택하는 것과 관련이 있습니다(다음 지점 참조).


3-5회 리샘플링. 거의 모든 완료가 접두사에 연결되지만 어려운 경우에는 모델이 접미사를 연결하는 데 어려움을 겪을 수 있습니다. 우리는 3번 또는 5번 리샘플링(또는 k=3,5와 함께 best_of를 사용)하고 finish_reason으로 "stop"을 사용하여 샘플을 선택하는 것이 이러한 경우에 효과적인 방법이 될 수 있음을 발견했습니다. 리샘플링하는 동안 일반적으로 다양성을 높이기 위해 더 높은 온도를 원할 것입니다.


참고: 반환된 모든 샘플에 finish_reason == "길이"가 있는 경우 max_tokens가 너무 작고 모델이 프롬프트와 접미사를 자연스럽게 연결하기 전에 토큰이 부족할 수 있습니다. 리샘플링하기 전에 max_tokens를 늘리는 것이 좋습니다.

 

Editing code 

Beta

The edits endpoint can be used to edit code, rather than just completing it. You provide some code and an instruction for how to modify it, and the code-davinci-edit-001 model will attempt to edit it accordingly. This is a natural interface for refactoring and tweaking code. During this initial beta period, usage of the edits endpoint is free.

 

edits 끝점은 코드를 완료하는 대신 코드를 편집하는 데 사용할 수 있습니다. 일부 코드와 수정 방법에 대한 지침을 제공하면 code-davinci-edit-001 모델이 그에 따라 수정을 시도합니다. 이것은 코드 리팩토링 및 조정을 위한 자연스러운 인터페이스입니다. 이 초기 베타 기간 동안 edits 엔드포인트 사용은 무료입니다.

 

Examples

Iteratively build a program

Writing code is often an iterative process that requires refining the text along the way. Editing makes it natural to continuously refine the output of the model until the final result is polished. In this example, we use fibonacci as an example of how to iteratively build upon code.

 

코드 작성은 종종 그 과정에서 텍스트를 수정해야 하는 반복적인 프로세스입니다. 편집은 최종 결과가 다듬어질 때까지 모델의 출력을 지속적으로 다듬는 것을 자연스럽게 만듭니다. 이 예제에서는 피보나치를 코드를 반복적으로 빌드하는 방법의 예로 사용합니다.

 

 

 

 

Best practices

The edits endpoint is still in alpha, we suggest following these best practices.

  1. Consider using an empty prompt! In this case, editing can be used similarly to completion.
  2. Be as specific with the instruction as possible.
  3. Sometimes, the model cannot find a solution and will result in an error. We suggest rewording your instruction or input.

모범 사례
edits 엔드포인트는 아직 알파 상태이므로 다음 모범 사례를 따르는 것이 좋습니다.

1. 빈 프롬프트 사용을 고려하십시오! 이 경우 편집은 완성과 유사하게 사용할 수 있습니다.
2. 가능한 한 구체적으로 지시하십시오.
3. 경우에 따라 모델이 솔루션을 찾지 못하고 오류가 발생합니다. 귀하의 지침이나 입력을 다른 말로 바꾸는 것이 좋습니다.

반응형

'Open AI > GUIDES' 카테고리의 다른 글

Guide - Rate limits  (0) 2023.03.05
Guide - Speech to text  (0) 2023.03.05
Guide - Chat completion (ChatGPT API)  (0) 2023.03.05
Guides - Production Best Practices  (0) 2023.01.10
Guides - Safety best practices  (0) 2023.01.10
Guides - Moderation  (0) 2023.01.10
Guides - Embeddings  (0) 2023.01.10
Guides - Fine tuning  (0) 2023.01.10
Guide - Image generation  (0) 2023.01.09
Guide - Text completion  (0) 2023.01.09