자연어에서 코드 생성
Azure OpenAI 모델의 기능 중 하나는 자연어 프롬프트에서 코드를 생성하는 것입니다. 작업은 간단한 한 줄 명령에서 전체 애플리케이션까지 다양할 수 있습니다. AI 모델은 제공된 코드 또는 이전 응답을 편집하고 업데이트하여 요청된 작업을 완료할 수도 있습니다.
이 단원의 예제에서는 gpt-35-turbo
를 사용합니다.
함수 작성
Azure OpenAI 모델은 원하는 내용만 설명하여 함수 및 앱을 여러 언어로 만들 수 있습니다. 예를 들어 write a function for binary search in python
프롬프트가 제공되면 함수와 코드에 대한 설명이 포함된 응답을 받을 수 있습니다.
Sure, here's an example implementation of binary search algorithm in Python:
def binary_search(array, target):
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == target:
return mid
elif array[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
This function takes in two arguments - an array of integers and a target integer that we want to search
for in the array. The function initializes two pointers - low and high - to the first and last indices
of the array, respectively.
Inside the while loop, the function calculates the middle index using integer division (//). If the
middle element is equal to the target, the function returns the index of the middle element. If the
middle element is less than the target, we update the low pointer to mid + 1. Otherwise, we update the
high pointer to mid - 1. We continue these steps until we find the target or the pointers cross each
other (i.e., low > high).
If the target is not found in the array, the function returns -1.
Note that the binary search algorithm assumes that the input array is sorted in ascending order. If
the array is not sorted, the algorithm may not return the correct result.
요청은 함수보다 더 나아가 일련의 함수 또는 전체 앱을 요청할 수 있습니다. 응답은 달성하려는 작업에 대한 좋은 출발점을 제공합니다.
코딩 언어 변경
한 언어로 된 코드가 있지만 다른 언어로 된 코드가 필요한 경우 Azure OpenAI가 원하는 언어로 변환할 수 있습니다. 예를 들어 Python에 이 print_squares
함수가 있다고 가정해 보겠습니다.
def print_squares(n):
for i in range(1, n+1):
print(i**2)
프롬프트 convert this code to C#
와 함께 그 코드를 제공하는 경우 다음 함수와 비슷하게 표시될 수 있습니다.
public void PrintSquares(int n)
{
for (int i = 1; i <= n; i++)
{
Console.WriteLine(i * i);
}
}
모델은 for
루프와 함수가 서로 다른 언어(C#의 액세스 한정자 포함)로 정의되는 방식의 차이점을 이해하고 코드를 적절하게 변경했습니다.
알 수 없는 코드 이해
Azure OpenAI 모델은 이해가 되지 않거나 익숙하지 않은 언어로 되어 있을 수 있는 코드를 이해하는 데 유용합니다. 예를 들어 가상의 코딩 언어로 다음 함수가 제공되었고 이를 이해하는 방법을 몰랐다고 가정해 보겠습니다.
fn qzplv(n: i32, m: i32) -> i32 {
if n == 0 {
return m + 1;
} else if m == 0 {
return qzplv(n - 1, 1);
} else {
return qzplv(n - 1, qzplv(n, m - 1));
}
}
could you explain what this code is doing?
프롬프트와 함께 모델에 제공될 때 다음과 유사한 응답이 표시됩니다.
Sure, I'd be happy to explain what this code is doing!
This code is implementing the Ackermann function, which is a well-known mathematical function that
grows very quickly in terms of computation time as its inputs increase. The function takes two integer
arguments (n and m) and returns another integer.
Here's how the function works:
- If n is equal to 0, the function returns m + 1.
- If m is equal to 0, the function calls itself recursively with n - 1 and 1 as arguments.
- Otherwise, the function calls itself recursively with n - 1 and the result of calling itself with n
and m - 1 as arguments.
The function is implemented in a way that is easy to understand and follow, but it has a very high
computational complexity. In fact, it grows so quickly that it can't be computed for values of n and m
greater than about 4 or 5.
설명과 번역을 익숙한 한 언어로 결합하면 이 기능이 훨씬 더 유용해집니다.
코드 완료 및 개발 프로세스 지원
Azure OpenAI는 단위 테스트 작성, 부분 코드 완료, 코드 주석 처리 및 설명서 생성과 같은 개발자의 일반적인 소프트웨어 개발 작업을 지원할 수 있습니다. 개발자는 AI 지원을 사용하여 복잡한 프로그래밍 및 문제 해결 작업에 더 많은 시간을 할애할 수 있습니다.
Azure OpenAI 모델은 주석, 함수 이름 및 부분적으로 작성된 코드를 기반으로 코드를 생성할 수 있습니다. 모델을 제공할 수 있는 컨텍스트가 많을수록 응답의 정확도가 높아집니다.
예를 들어, 다음과 같은 프롬프트를 가정할 때:
complete the following function
"""
# calculate the average of the numbers in an array, but only if they're even
def
모델은 함수 정의의 주석과 시작을 가져와서 어떤 컨텍스트에서든 완료합니다.
주석 없이 모델에 부분 코드를 제공하여 유사한 기능을 볼 수 있습니다. 예를 들어 다음 프롬프트를 수행합니다.
complete the following code
"""
def func1(n)
if n==0:
complete the following code
"""
public int Func1(int n) {
if (n == 0) {
AI 모델은 함수가 완료될 가능성이 가장 높은 함수로 완료하기 위해 최선을 다합니다.
def func1(n):
if n == 0:
return 1
else:
return n * func1(n-1)
public int Func1(int n) {
if (n == 0) {
return 1;
} else {
return n * Func1(n-1);
}
}
응답에는 해당 함수가 수행하는 일에 대한 자연어 설명도 포함되어 있습니다. 이 경우 계승값 함수의 재귀 구현으로 응답했습니다.
단위 테스트 작성
Azure OpenAI 모델은 코드를 보다 강력하게 만들기 위해 작성하는 함수에 대한 단위 테스트를 생성할 수 있습니다. 예를 들어 이진 검색 함수를 사용합니다.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
public static int BinarySearch(int[] arr, int target)
{
int left = 0;
int right = arr.Length - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] == target)
{
return mid;
}
else if (arr[mid] < target)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
write three unit tests for this function
프롬프트와 함께 해당 함수를 제공하면 다음과 유사한 응답이 표시됩니다.
def test_binary_search():
# Test case 1: Target element is in the middle of the array
arr1 = [1, 2, 3, 4, 5, 6]
target1 = 4
assert binary_search(arr1, target1) == 3
# Test case 2: Target element is at the beginning of the array
arr2 = [1, 2, 3, 4, 5, 6]
target2 = 1
assert binary_search(arr2, target2) == 0
# Test case 3: Target element is not in the array
arr3 = [1, 2, 3, 4, 5, 6]
target3 = 7
assert binary_search(arr3, target3) == -1
[Test]
public void TestBinarySearch1()
{
int[] arr = { 1, 2, 3, 4, 5 };
int target = 3;
int expected = 2;
int result = BinarySearch(arr, target);
Assert.AreEqual(expected, result);
}
[Test]
public void TestBinarySearch2()
{
int[] arr = { 10, 20, 30, 40, 50 };
int target = 35;
int expected = -1;
int result = BinarySearch(arr, target);
Assert.AreEqual(expected, result);
}
[Test]
public void TestBinarySearch3()
{
int[] arr = { 3, 6, 9, 12, 15 };
int target = 6;
int expected = 1;
int result = BinarySearch(arr, target);
Assert.AreEqual(expected, result);
}
이 기능은 프롬프트에 포함하려는 사례를 지정하는 경우 훨씬 유용합니다. 코드에 대한 단위 테스트를 작성하는 데 걸리는 시간을 줄일 수 있습니다.
설명 추가 및 설명서 생성
코드를 더욱 개선하기 위해 AI 모델은 주석과 설명서를 추가할 수 있습니다. 코드 주석 없이 처음 읽을 때 약간 이해하기 어려울 수 있는 다음 함수를 예로 들어 봅니다.
def permutations(lst):
if len(lst) == 0:
return []
elif len(lst) == 1:
return [lst]
else:
result = []
for i in range(len(lst)):
temp = lst[i]
remaining = lst[:i] + lst[i+1:]
for p in permutations(remaining):
result.append([temp] + p)
return result
public static List<List<int>> Permutations(List<int> lst)
{
if (lst.Count == 0)
{
return new List<List<int>>();
}
else if (lst.Count == 1)
{
return new List<List<int>> { lst };
}
else
{
List<List<int>> result = new List<List<int>>();
for (int i = 0; i < lst.Count; i++)
{
int temp = lst[i];
List<int> remaining = new List<int>(lst);
remaining.RemoveAt(i);
foreach (List<int> p in Permutations(remaining))
{
List<int> permutation = new List<int> { temp };
permutation.AddRange(p);
result.Add(permutation);
}
}
return result;
}
}
코드에 주석을 추가하도록 요청하는 프롬프트와 함께 모델에 해당 함수를 제공하고 다음과 유사한 응답을 받습니다.
def permutations(lst):
# Check if the input list is empty
if len(lst) == 0:
return []
# Check if the input list has only one element
elif len(lst) == 1:
return [lst]
else:
# Initialize an empty list to store permutations
result = []
# Iterate through each element of the input list
for i in range(len(lst)):
# Remove the current element from the list and store it in a variable
temp = lst[i]
remaining = lst[:i] + lst[i+1:]
# Recursively call the function on the remaining list
for p in permutations(remaining):
# Append the current element to the beginning of each permutation and add it to the result list
result.append([temp] + p)
# Return the final list of permutations
return result
public static List<List<int>> Permutations(List<int> lst)
{
// Check if the input list is empty
if (lst.Count == 0)
{
return new List<List<int>>();
}
// Check if the input list has only one element
else if (lst.Count == 1)
{
return new List<List<int>> { lst };
}
else
{
// Initialize an empty list to store permutations
List<List<int>> result = new List<List<int>>();
// Iterate through each element of the input list
for (int i = 0; i < lst.Count; i++)
{
// Remove the current element from the list and store it in a variable
int temp = lst[i];
List<int> remaining = new List<int>(lst);
remaining.RemoveAt(i);
// Recursively call the function on the remaining list
foreach (List<int> p in Permutations(remaining))
{
// Append the current element to the beginning of each permutation and add it to the result list
List<int> permutation = new List<int> { temp };
permutation.AddRange(p);
result.Add(permutation);
}
}
// Return the final list of permutations
return result;
}
}
한 단계 더 나아가 설명서를 요청하는 경우 OpenAI는 입력 및 출력을 포함한 설명을 추가합니다.
버그 수정 및 코드 개선
개발자는 간혹 주로 작동하는 코드를 작성할 수 있지만 버그, 구문, 성능 또는 모듈성을 수정하여 개선할 수 있습니다. Azure OpenAI 모델은 개선 방법을 식별하고 더 나은 코드를 작성하는 방법에 대한 제안을 제공하는 데 도움이 될 수 있습니다.
코드의 버그 수정
Azure OpenAI 모델은 코드를 분석하고 잠재적으로 문제를 해결할 수 있는 변경 내용을 제안하여 코드의 버그를 해결하는 데 도움이 될 수 있습니다. 이렇게 해서 개발자가 버그를 더 빠르고 효율적으로 식별하고 해결할 수 있습니다.
예를 들어 작동하지 않는 다음 함수가 있다고 가정해 보겠습니다.
def calculate_average(numbers):
total = 0
for i in range(len(numbers)):
number = numbers[i]
total += number
average = total
rerun averave
public double CalculateAverage(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
int number = numbers[i];
total += number;
}
double average = (double)total;
rerun averave;
}
Fix the bugs in this function
프롬프트와 함께 모델에 해당 함수를 제공하면 고정 코드와 수정된 내용에 대한 설명이 포함된 응답을 받습니다.
def calculate_average(numbers):
total = 0
for i in range(len(numbers)):
number = numbers[i]
total += number
average = total / len(numbers)
return average
public double CalculateAverage(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
int number = numbers[i];
total += number;
}
double average = (double)total / numbers.Length;
return average;
}
There were a few issues with the original code:
1. The variable "average" was assigned the value of "total" instead of the actual average.
2. There was a typo in the last line - "rerun" should be "return".
3. The average was not actually calculated - the corrected code divides the total by the length of
the "numbers" list to get the average.
성능 향상
개발자가 작성하는 코드가 작동할 수 있지만 작업을 수행하는 더 효율적인 방법이 있을 수 있습니다. 다음은 비효율적일 수 있는 첫 번째 n개 양의 정수의 합계를 계산하는 함수의 예입니다.
def sum_of_n(n):
result = 0
for i in range(1, n+1):
result += i
return result
public int SumOfN(int n)
{
int result = 0;
for (int i = 1; i <= n; i++)
{
result += i;
}
return result;
}
이 버전은 올바르게 작동하지만 시간 복잡성이 O(n)입니다. 모델에 제공된 경우 응답은 다음과 같습니다.
We can improve this function it by using a mathematical formula instead.
Here's the more efficient version:
def sum_of_n(n):
return n * (n + 1) // 2
public int SumOfN(int n)
{
return n * (n + 1) / 2;
}
이 버전은 여전히 올바른 결과를 반환하지만 시간 복잡성은 이제 O(1)이므로 훨씬 더 효율적입니다.
비효율적인 코드 리팩터링
더 나은 코드는 버그가 덜 발생할 수 있고 유지 관리가 더 쉬울 수 있으며, Azure OpenAI 모델은 개발자에게 코드를 리팩터링하는 방법을 안내하는 데 도움이 될 수 있습니다.
다음과 같은 함수가 있다고 합시다.
def calculateTotalPrice(item, quantity):
if item == 'apple':
return quantity * 0.5
elif item == 'banana':
return quantity * 0.75
elif item == 'orange':
return quantity * 0.6
else:
return 0
public double CalculateTotalPrice(string item, int quantity)
{
if (item == "apple")
{
return quantity * 0.5;
}
else if (item == "banana")
{
return quantity * 0.75;
}
else if (item == "orange")
{
return quantity * 0.6;
}
else
{
return 0;
}
}
이 코드는 이름과 수량을 기준으로 특정 항목의 총 가격을 계산합니다. 그러나 코드는 모듈식이 아니며 유지 관리가 어려울 수 있습니다. 리팩터링 요청과 함께 모델에 제공된 경우 응답은 다음과 같습니다.
item_prices = {
'apple': 0.5,
'banana': 0.75,
'orange': 0.6
}
def calculate_total_price(item, quantity):
price = item_prices.get(item, 0)
return quantity * price
static Dictionary<string, double> itemPrices = new Dictionary<string, double>()
{
{"apple", 0.5},
{"banana", 0.75},
{"orange", 0.6}
};
static double CalculateTotalPrice(string item, int quantity)
{
double price;
if (!itemPrices.TryGetValue(item, out price))
{
price = 0;
}
return quantity * price;
}
모델은 코드와 함께 리팩터링에 대한 설명을 제공합니다.
In this refactored code, we've created an object called itemPrices that maps item names to their
prices. We've also simplified the calculateTotalPrice function by using the itemPrices object to look
up the price of the item, rather than using a series of if/else statements. This makes the code more
modular and easier to maintain, and also reduces the risk of introducing bugs in the future.