Edit

Share via


Build an AI chat app with .NET

In this quickstart, you learn how to create a conversational .NET console chat app using an OpenAI or Azure OpenAI model. The app uses the Microsoft.Extensions.AI library so you can write code using AI abstractions rather than a specific SDK. AI abstractions enable you to change the underlying AI model with minimal code changes.

Prerequisites

Prerequisites

Note

You can also use Semantic Kernel to accomplish the tasks in this article. Semantic Kernel is a lightweight, open-source SDK that lets you build AI agents and integrate the latest AI models into your .NET apps.

Create the app

Complete the following steps to create a .NET console app to connect to an AI model.

  1. In an empty directory on your computer, use the dotnet new command to create a new console app:

    dotnet new console -o ChatAppAI
    
  2. Change directory into the app folder:

    cd ChatAppAI
    
  3. Install the required packages:

    dotnet add package Azure.Identity
    dotnet add package Azure.AI.OpenAI
    dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    
    dotnet add package OpenAI
    dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    
  4. Open the app in Visual Studio Code (or your editor of choice).

    code .
    

Create the AI service

  1. To provision an Azure OpenAI service and model, complete the steps in the Create and deploy an Azure OpenAI Service resource article.

  2. From a terminal or command prompt, navigate to the root of your project directory.

  3. Run the following commands to configure your Azure OpenAI endpoint and model name for the sample app:

    dotnet user-secrets init
    dotnet user-secrets set AZURE_OPENAI_ENDPOINT <your-Azure-OpenAI-endpoint>
    dotnet user-secrets set AZURE_OPENAI_GPT_NAME <your-Azure-OpenAI-model-name>
    

Configure the app

  1. Navigate to the root of your .NET project from a terminal or command prompt.

  2. Run the following commands to configure your OpenAI API key as a secret for the sample app:

    dotnet user-secrets init
    dotnet user-secrets set OpenAIKey <your-OpenAI-key>
    dotnet user-secrets set ModelName <your-OpenAI-model-name>
    

Add the app code

This app uses the Microsoft.Extensions.AI package to send and receive requests to the AI model. The app provides users with information about hiking trails.

  1. In the Program.cs file, add the following code to connect and authenticate to the AI model.

    IConfigurationRoot config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string endpoint = config["AZURE_OPENAI_ENDPOINT"];
    string deployment = config["AZURE_OPENAI_GPT_NAME"];
    
    IChatClient chatClient =
        new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
        .GetChatClient(deployment)
        .AsIChatClient();
    

    Note

    DefaultAzureCredential searches for authentication credentials from your local tooling. If you aren't using the azd template to provision the Azure OpenAI resource, you'll need to assign the Azure AI Developer role to the account you used to sign in to Visual Studio or the Azure CLI. For more information, see Authenticate to Azure AI services with .NET.

    var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string model = config["ModelName"];
    string key = config["OpenAIKey"];
    
    // Create the IChatClient
    IChatClient chatClient =
        new OpenAIClient(key).GetChatClient(model).AsIChatClient();
    
  2. Create a system prompt to provide the AI model with initial role context and instructions about hiking recommendations:

    // Start the conversation with context for the AI model
    List<ChatMessage> chatHistory =
        [
            new ChatMessage(ChatRole.System, """
                You are a friendly hiking enthusiast who helps people discover fun hikes in their area.
                You introduce yourself when first saying hello.
                When helping people out, you always ask them for this information
                to inform the hiking recommendation you provide:
    
                1. The ___location where they would like to hike
                2. What hiking intensity they are looking for
    
                You will then provide three suggestions for nearby hikes that vary in length
                after you get that information. You will also share an interesting fact about
                the local nature on the hikes when making a recommendation. At the end of your
                response, ask if there is anything else you can help with.
            """)
        ];
    
  3. Create a conversational loop that accepts an input prompt from the user, sends the prompt to the model, and prints the response completion:

    // Loop to get user input and stream AI response
    while (true)
    {
        // Get user prompt and add to chat history
        Console.WriteLine("Your prompt:");
        string? userPrompt = Console.ReadLine();
        chatHistory.Add(new ChatMessage(ChatRole.User, userPrompt));
    
        // Stream the AI response and add to chat history
        Console.WriteLine("AI Response:");
        string response = "";
        await foreach (ChatResponseUpdate item in
            chatClient.GetStreamingResponseAsync(chatHistory))
        {
            Console.Write(item.Text);
            response += item.Text;
        }
        chatHistory.Add(new ChatMessage(ChatRole.Assistant, response));
        Console.WriteLine();
    }
    
  4. Use the dotnet run command to run the app:

    dotnet run
    

    The app prints out the completion response from the AI model. Send additional follow up prompts and ask other questions to experiment with the AI chat functionality.

Clean up resources

If you no longer need them, delete the Azure OpenAI resource and GPT-4 model deployment.

  1. In the Azure Portal, navigate to the Azure OpenAI resource.
  2. Select the Azure OpenAI resource, and then select Delete.

Next steps