This past Thursday night after the Virtual Boston Azure meetup, Bill Wilder (@codingoutloud) created an
AI mini-workshop (hands on) for the attendees that were interested in getting hands on with code using the Azure OpenAI API.
This post is me using the same idea but with Semantic Kernel.
OpenAI Chat Hello World C#
Bill provided the following code for us to get a simple OpenAI chat working:
using Azure;
using Azure.AI.OpenAI;
string? key = "...";
string? endpoint = "...";
string? deployment = "...";
// output today's date just for fun
Console.WriteLine($"\n----------------- DEBUG INFO -----------------");
var today = DateTime.Now.ToString("MMMM dd");
Console.WriteLine($"Today is {today}");
Console.WriteLine("----------------------------------------------");
var client = new OpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));
// TODO: CHALLENGE 1: does the AI respond accurately to this prompt? How to fix?
var prompt = $"Tell me an interesting fact from world about an event " +
$"that took place on {today}. " +
$"Be sure to mention the date in history for context.";
CompletionsOptions completionsOptions = new()
{
Temperature = 0.7f,
DeploymentName = deployment,
Prompts = { prompt },
MaxTokens = 250, // PLEASE DON'T MAKE LARGER THAN 250 (but see what happens at 25)
};
Response<Completions> completionsResponse = client.GetCompletions(completionsOptions);
Console.WriteLine($"\nPROMPT: \n\n{prompt}");
int i = 0;
foreach (var choice in completionsResponse.Value.Choices)
{
Console.WriteLine($"\nRESPONSE {++i}/{completionsResponse.Value.Choices.Count}:" +
$"{choice.Text}");
}
Console.WriteLine($"\n----------------- DEBUG INFO -----------------");
Console.WriteLine($"Tokens used: {completionsResponse.Value.Usage.CompletionTokens}/{completionsOptions.MaxTokens}");
Console.WriteLine("----------------------------------------------");
When you run this code (you’ll of course need to add in you own values for the key
, endpoint
and deployment
), you will get a response like this: