Complete the following steps to create a .NET console app to connect to an AI model.
In an empty directory on your computer, use the dotnet new command to create a new console app:
dotnet new console -o ChatAppAIdotnet add package OpenAI dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease dotnet add package Microsoft.Extensions.Configuration dotnet add package Microsoft.Extensions.Configuration.UserSecrets
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.
In the Program.cs file, add the following code to connect and authenticate to the AI model.
// See https://aka.ms/new-console-template for more information
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
using OpenAI;
Console.WriteLine("Hello, World!");
var config = new ConfigurationBuilder().AddUserSecrets().Build();
string model = config["ModelName"]; //"gpt-5"; //
string key = config["OpenAIKey"];
// Create the IChatClient
IChatClient chatClient =
new OpenAIClient(key).GetChatClient(model).AsIChatClient();
//ChatClient chatClient = new OpenAIClient(key).GetChatClient(model);
// Start the conversation with context for the AI model
List 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.
""")
];
// 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();
}