完成代码并协助执行开发过程

已完成

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