Prerequisites
- .NET 8 SDK
- A C# code editor such as Visual Studio Code
- An Azure subscription with access to the OpenAI Service
Getting started with Azure OpenAI service
Setting | Value |
---|---|
KEY 1: | this-is-a-fake-api-key |
Endpoint: | https://mze-openai.openai.azure.com/ |
Model deployment: | gpt35-turbo-deployment |
Next, we will create our console application.
Console Application
dotnet new console -f net8.0 -o BotWithPersonalitycd BotWithPersonality
dotnet add package Azure.AI.OpenAI -v 1.0.0-beta.11dotnet add package Microsoft.Extensions.Configuration.Json -v 8.0.0
Configuration Settings
{"settings": {"deployment-name": "gpt35-turbo-deployment","endpoint": "https://mze-openai.openai.azure.com/","key": "this-is-a-fake-api-key"}}
<ItemGroup><None Include="*.json" CopyToOutputDirectory="PreserveNewest" /></ItemGroup>
public class Utils {public static string GetConfigValue(string config) {IConfigurationBuilder builder = new ConfigurationBuilder();if (System.IO.File.Exists("appsettings.json"))builder.AddJsonFile("appsettings.json", false, true);if (System.IO.File.Exists("appsettings.Development.json"))builder.AddJsonFile("appsettings.Development.json", false, true);IConfigurationRoot root = builder.Build();return root[config]!;}}
Building our ChatBot app
Let us first read the settings we need from appsettings.json. Therefore, append this code to Program.cs:using Azure;using Azure.AI.OpenAI;using BotWithPersonality;
string ENDPOINT = Utils.GetConfigValue("settings:endpoint");string KEY = Utils.GetConfigValue("settings:key");string DEPLOYMENT_NAME = Utils.GetConfigValue("settings:deployment-name");
const string SYSTEM_MESSAGE= """You are a friendly assistant named DotNetBot.You prefer to use Canadian Newfoundland English as your language and are an expert in the .NET runtimeand C# and F# programming languages.Response using Newfoundland colloquialisms and slang.""";
var openAiClient = new OpenAIClient(new Uri(ENDPOINT),new AzureKeyCredential(KEY));
var chatCompletionsOptions = new ChatCompletionsOptions{DeploymentName = DEPLOYMENT_NAME, // Use DeploymentName for "model" with non-Azure clientsMessages ={new ChatRequestSystemMessage(SYSTEM_MESSAGE),new ChatRequestUserMessage("Introduce yourself"),}};
while (true){Console.WriteLine();Console.Write("DotNetBot: ");Response<ChatCompletions> chatCompletionsResponse = await openAiClient.GetChatCompletionsAsync(chatCompletionsOptions);var chatMessage = chatCompletionsResponse.Value.Choices[0].Message;Console.WriteLine($"[{chatMessage.Role.ToString().ToUpperInvariant()}]: {chatMessage.Content}");chatCompletionsOptions.Messages.Add(new ChatRequestUserMessage(chatMessage.Content));Console.WriteLine();Console.Write("Enter a message: ");var userMessage = Console.ReadLine();chatCompletionsOptions.Messages.Add(new ChatRequestUserMessage(userMessage));}