Open AI Challenge, Day 3: Mastering Code Generation

Sukhpinder Singh - Mar 28 - - Dev Community

Designed for developers familiar with Azure and generative AI, the guide walks you through the process of harnessing the power of the gpt turbo model for code generation.

Introduction

The Microsoft team has recently launched an Open AI challenge, in which a developer can learn how to build Azure AI solutions and apps.

Prerequisite

  • Experience working with Azure and Azure portals.

  • An understanding of generative AI.

  • Experience in one high-level programming language like C# or Python

Steps to Create Open AI Service on Azure with “Dall-E” model deployed.
Day 1 — Azure Open AI Challenge

If you would like to explore image generation, follow this link
Day 2 — Azure Open AI Challenge: Image Generation

Getting Started

Considering Azure Open AI Service is running on the Azure portal and the gpt-turbo model is deployed successfully.

Step 1: Create a console application

To test image generation, create a console application in Visual Studio or Visual Studio Code.

    dotnet new console
Enter fullscreen mode Exit fullscreen mode

Step 2: Read the configuration

Read the configuration from appsettings.json file

    // Build a config object and retrieve user settings.
    IConfiguration config = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();
    string? oaiEndpoint = config["AzureOAIEndpoint"];
    string? oaiKey = config["AzureOAIKey"];
    string? oaiDeploymentName = config["AzureOAIDeploymentName"];
Enter fullscreen mode Exit fullscreen mode

Step 3: Add sample code

Create a file under the console application project as follows sample-code> function > function.cs

    namespace Function
    {
        class Program
        {
            int AbsoluteSquare(int num1, int num2)
            {
                int result = Math.Abs(num1 - num2);
                result *= result;
                return result;
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode

Another file as sample-code > go-fish > go-fish.cs => Reference file

Step 3: Prepare Console Menu

The next step is to prepare a menu on the console application using digits.

  • If the console message is “quit” the console application is exited.

  • If the console input is 1 or 2, then the sample file function.cs is used

  • If the console input is 3, then the sample file go-fish.cs is used

  • Else it will return a console message saying invalid input

    do
    {
        Console.WriteLine("\n1: Add comments to my function\n" +
        "2: Write unit tests for my function\n" +
        "3: Fix my Go Fish game\n" +
        "\"quit\" to exit the program\n\n" +
        "Enter a number to select a task:");

        command = Console.ReadLine() ?? "";

        if (command == "quit")
        {
            Console.WriteLine("Exiting program...");
            break;
        }

        Console.WriteLine("\nEnter a prompt: ");
        string userPrompt = Console.ReadLine() ?? "";
        string codeFile = "";

        if (command == "1" || command == "2")
            codeFile = System.IO.File.ReadAllText($@"{AppDomain.CurrentDomain.BaseDirectory}sample-code\function\function.cs");
        else if (command == "3")
            codeFile = System.IO.File.ReadAllText($@"{AppDomain.CurrentDomain.BaseDirectory}sample-code\go-fish\go-fish.cs");
        else
        {
            Console.WriteLine("Invalid input. Please try again.");
            continue;
        }

        userPrompt += codeFile;
        await GetResponseFromOpenAI(userPrompt);
    } while (true);
Enter fullscreen mode Exit fullscreen mode

Step 4: Code generation from AI

Please find below the method GetResponseFromOpenAI which generates the code using gpt-turbo.

  • Read the configuration values required, if not present don’t execute.

  • Prepare the request for chat completion response.

  • Finally, write the response back to result > app.txt file

    async Task GetResponseFromOpenAI(string prompt)
    {
        Console.WriteLine("\nCalling Azure OpenAI to generate code...\n\n");

        if (string.IsNullOrEmpty(oaiEndpoint) || string.IsNullOrEmpty(oaiKey) || string.IsNullOrEmpty(oaiDeploymentName))
        {
            Console.WriteLine("Please check your appsettings.json file for missing or incorrect values.");
            return;
        }

        // Configure the Azure OpenAI client
        OpenAIClient client = new OpenAIClient(new Uri(oaiEndpoint), new AzureKeyCredential(oaiKey));

        // Define chat prompts
        string systemPrompt = "You are a helpful AI assistant that helps programmers write code.";
        string userPrompt = prompt;

        // Format and send the request to the model
        var chatCompletionsOptions = new ChatCompletionsOptions()
        {
            Messages =
            {
                new ChatRequestSystemMessage(systemPrompt),
                new ChatRequestUserMessage(userPrompt)
            },
            Temperature = 0.7f,
            MaxTokens = 1000,
            DeploymentName = oaiDeploymentName
        };

        // Get response from Azure OpenAI
        Response<ChatCompletions> response = await client.GetChatCompletionsAsync(chatCompletionsOptions);

        ChatCompletions completions = response.Value;
        string completion = completions.Choices[0].Message.Content;

        // Write full response to console, if requested
        if (printFullResponse)
        {
            Console.WriteLine($"\nFull response: {JsonSerializer.Serialize(completions, new JsonSerializerOptions { WriteIndented = true })}\n\n");
        }

        // Write the file.
        System.IO.File.WriteAllText(@"result\app.txt", completion);

        // Write response to console
        Console.WriteLine($"\nResponse written to result/app.txt\n\n");
    }
Enter fullscreen mode Exit fullscreen mode

Test Case 1: Add comments to the code

  • Choose option 1

  • Then add the following prompt to add comments to the code

Add comments to the following function. Return only the commented code.

Output Test Case 1

Refer to the sample function.cs file on GitHub.

Please find below the convert function with the single line comments added as shown below.

    // This function calculates the absolute square of the difference between two numbers

    namespace Function
    {
        class Program
        {
            // Function to calculate the absolute square of the difference between two numbers
            int AbsoluteSquare(int num1, int num2)
            {
                // Calculate the absolute difference between the two numbers
                int result = Math.Abs(num1 - num2);

                // Square the result
                result *= result;

                // Return the absolute square of the difference between the two numbers
                return result;
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode

Additionally, the user can suggest gpt model to add multi-line comments instead of single lines using the following prompt

Add comments to the following function. Return only the commented code. \n — -\n

    namespace Function
    {
        class Program
        {
            // This function calculates the absolute square of the difference between two integers.
            // Parameters:
            //   num1: the first integer
            //   num2: the second integer
            // Returns:
            //   The absolute square of the difference between num1 and num2
            int AbsoluteSquare(int num1, int num2)
            {
                int result = Math.Abs(num1 - num2);
                result *= result;
                return result;
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode

Test Case 2: Add comments to the code

  • Choose option 2

  • Then add the following prompt to add comments to the code

Write four unit tests for the following function. \n — -\n

Output Test Case 2

Refer to the sample function.cs file on GitHub. Please find below the test cases added

    Sure! Here are four unit tests for the `AbsoluteSquare` function:

    1. Test case where `num1` is greater than `num2`:

    [Test]
    public void TestAbsoluteSquare_GreaterNum1_ReturnsSquaredDifference()
    {
        int num1 = 5;
        int num2 = 2;
        int expected = 9;
        int result = Function.Program.AbsoluteSquare(num1, num2);
        Assert.AreEqual(expected, result);
    }

    2. Test case where `num2` is greater than `num1`:

    [Test]
    public void TestAbsoluteSquare_GreaterNum2_ReturnsSquaredDifference()
    {
        int num1 = 2;
        int num2 = 5;
        int expected = 9;
        int result = Function.Program.AbsoluteSquare(num1, num2);
        Assert.AreEqual(expected, result);
    }

    3. Test case where `num1` and `num2` are the same:

    [Test]
    public void TestAbsoluteSquare_SameNumbers_ReturnsZero()
    {
        int num1 = 4;
        int num2 = 4;
        int expected = 0;
        int result = Function.Program.AbsoluteSquare(num1, num2);
        Assert.AreEqual(expected, result);
    }


    4. Test case where `num1` and `num2` are negative:

    [Test]
    public void TestAbsoluteSquare_NegativeNumbers_ReturnsSquaredDifference()
    {
        int num1 = -3;
        int num2 = -6;
        int expected = 9;
        int result = Function.Program.AbsoluteSquare(num1, num2);
        Assert.AreEqual(expected, result);
    }
Enter fullscreen mode Exit fullscreen mode

Test Case 3: Fix my Go Fish game

  • Choose option 3

  • Then add the following prompt to add comments to the code

Fix the code below for an app to play Go Fish with the user. Return only the corrected code. \n — -\n

Output Test Case 3

Refer to the sample go-fish.cs file on GitHub.

Please find below the code that is fixed.


    using System;  
    using System.Collections.Generic;  
    using System.Linq;  

    namespace GoFish  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                // Define the deck of cards  
                List<string> deck = new List<string> { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };  
                deck.AddRange(deck);  
                deck.AddRange(deck);  
                deck.AddRange(deck);  

                // Shuffle the deck  
                var rand = new Random();  
                deck = deck.OrderBy(x => rand.Next()).ToList();  

                // Deal the cards  
                List<string> playerHand = deck.Take(5).ToList();  
                List<string> computerHand = deck.Skip(5).Take(5).ToList();  

                // Define the initial score  
                int playerScore = 0;  
                int computerScore = 0;  

                // Define the main game loop  
                while (deck.Count > 0)  
                {  
                    // Print the player's hand  
                    Console.WriteLine("Your hand: " + string.Join(", ", playerHand));  

                    // Ask the player for a card  
                    Console.Write("Do you have any... ");  
                    string card = Console.ReadLine();  

                    // Check if the player has the card  
                    if (playerHand.Contains(card))  
                    {  
                        // Remove the card from the player's hand  
                        playerHand.Remove(card);  

                        // Add a point to the player's score  
                        playerScore += 1;  

                        // Print the player's score  
                        Console.WriteLine("You got a point!");  
                        Console.WriteLine("Your score: " + playerScore);  
                    }  
                    else  
                    {  
                        // Go fish!  
                        Console.WriteLine("Go fish!");  

                        // Draw a card from the deck  
                        string drawnCard = deck.First();  
                        deck.RemoveAt(0);  

                        // Add the card to the player's hand  
                        playerHand.Add(drawnCard);  

                        // Print the card that was drawn  
                        Console.WriteLine("You drew a " + drawnCard);  
                    }  

                    // Check if the player has won  
                    if (playerScore == 5)  
                    {  
                        Console.WriteLine("You win!");  
                        break;  
                    }  

                    // Computer's turn  
                    string computerCard = computerHand[rand.Next(computerHand.Count)];  
                    Console.WriteLine("Do you have any " + computerCard + "?");  
                    if (playerHand.Contains(computerCard))  
                    {  
                        // Remove the card from the player's hand  
                        playerHand.Remove(computerCard);  

                        // Add a point to the computer's score  
                        computerScore += 1;  

                        // Print the computer's score  
                        Console.WriteLine("The computer got a point!");  
                        Console.WriteLine("Computer score: " + computerScore);  
                    }  
                    else  
                    {  
                        // Go fish!  
                        Console.WriteLine("The computer goes fishing!");  

                        // Draw a card from the deck  
                        string drawnCard = deck.First();  
                        deck.RemoveAt(0);  

                        // Add the card to the computer's hand  
                        computerHand.Add(drawnCard);  

                        // Print the card that was drawn  
                        Console.WriteLine("The computer drew a " + drawnCard);  
                    }  

                    // Check if the computer has won  
                    if (computerScore == 5)  
                    {  
                        Console.WriteLine("The computer wins!");  
                        break;  
                    }  
                }  
            }  
        }  
    }
Enter fullscreen mode Exit fullscreen mode

Finally, if you type quit, the console application will be terminated.

Complete code on GitHub

Make sure to give it a star on GitHub and provide feedback on how to improve the tool further..!!

ssukhpinder/AzureOpenAI

C# Programming🚀

Thank you for being a part of the C# community! Before you leave:

If you’ve made it this far, please show your appreciation with a clap and follow the author! 👏️️

Follow us: X | LinkedIn | Dev.to | Hashnode | Newsletter | Tumblr

Visit our other platforms: GitHub | Instagram | Tiktok | Quora | Daily.dev

More content at C# Programming

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .