코드 완료 및 개발 프로세스 지원
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 function
"""
// calculate the average of the numbers in an array, but only if they're even
public
모델은 함수 정의의 주석과 시작을 가져와서 어떤 컨텍스트에서든 완료합니다.
# calculate the average of the even numbers in an array
def calculate_even_average(numbers):
total = 0
count = 0
for number in numbers:
if number % 2 == 0:
total += number
count += 1
if count == 0:
return 0 # avoid division by zero
else:
return total / count
// calculate the average of the even numbers in an array
public double CalculateEvenAverage(int[] numbers) {
int total = 0;
int count = 0;
foreach (int number in numbers) {
if (number % 2 == 0) {
total += number;
count++;
}
}
if (count == 0) {
return 0; // avoid division by zero
} else {
return (double) total / count;
}
}
이 경우 함수가 시작되기 전에 비교적 간단하고 완전한 주석으로 인해 원하는 것을 파악할 수 있었습니다. 더 복잡한 함수 또는 작업을 사용할 때 유용한 응답을 얻으려면 더 많은 컨텍스트가 필요합니다.
Python과 같은 일부 언어의 경우 모델이 원하는 언어를 가정할 수 있을 만큼 구문이 명확하다는 것을 알아두는 것이 중요합니다. C# 또는 Java와 같은 구문적으로 유사한 언어의 경우 모델이 잘못된 언어를 사용할 가능성이 더 높습니다. 이 경우 프롬프트에서 언어를 지정하거나 컨텍스트에 대한 더 많은 코드를 제공해 보세요.
주석 없이 모델에 부분 코드를 제공하여 유사한 기능을 볼 수 있습니다. 예를 들어 다음 프롬프트를 수행합니다.
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);
}
}
응답에는 해당 함수가 수행하는 일에 대한 자연어 설명도 포함되어 있습니다. 이 경우 계승값 함수의 재귀 구현으로 응답했습니다. 그러나 프롬프트는 모델에서 원하는 것을 더 잘 나타내기 위해 프롬프트에 더 많은 컨텍스트가 필요한 경우를 보여 주는 Fibonacci 함수의 시작이었을 수도 있습니다.
GitHub Copilot과 같은 도구는 OpenAI 모델을 활용하여 위의 예제와 비슷한 방식으로 코드 및 함수 완성을 제안합니다. GitHub Copilot은 기본 제공 프롬프트와 페어링된 프로그래머 역할을 하기 위해 작성하는 코드의 컨텍스트를 사용하는 이 기능의 실례를 보여 주는 좋은 예입니다.
단위 테스트 작성
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;
}
}
한 단계 더 나아가 방금 주석을 추가한 함수에 대한 설명서를 요청합니다.
def permutations(lst):
"""
Generates all possible permutations of a given list of integers using recursion.
Args:
lst (list): The list of integers to generate permutations for.
Returns:
list: A list of all possible permutations of the input list.
"""
# 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
/// <summary>
/// Generates all possible permutations of a given list of integers using recursion.
/// </summary>
/// <param name="lst">The list of integers to generate permutations for.</param>
/// <returns>A list of all possible permutations of the input list.</returns> ```
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;
}
}