In this tutorial you will create a very simple Blazor Web Assembly application that interacts with ChatGPT.
Prerequisites
You will need the following:
- .NET 7.0 or higher
- Visual Studio Code
- A ChatGPT account with https://openai.com
Get an ChatGPT API key from openai.com
Visit https://openai.com and create an account. The login page looks like this:
Click on your profile and select “View API keys”. On the next page, click on the “+ Create new secret key” button.
An API key is generated. You must save this key somewhere because this is your only chance to view it as it cannot be viewed again. Click on the copy button and paste it is a safe place.
Creating ASP.NET Blazor Web Assembly App
dotnet new blazorwasm -n ChatGPTBlazorWasmcd ChatGPTBlazorWasm
@page "/"@inject HttpClient httpClient<h1>ChatGPT with Blazor WebAssembly (NBA)</h1><textarea @bind="dialog" cols="100" rows="15"></textarea><br /><button @onclick="GetOpenAIChatCompletions" class="btn btn-success">Call Completion</button>@code {private string? dialog;protected override void OnInitialized(){const string? apiKey = "fake-chatgpt-api-key";httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");Message[] messages = new Message[] {new Message { Role = "system", Content = "You are a helpful assistant." },new Message { Role = "user", Content = "Who won the NBA in 2020?" },new Message { Role = "assistant", Content = "The Los Angeles Lakers won the NBA in 2020." },new Message { Role = "user", Content = "Where was it played?" },};dialog = "";foreach (var message in messages){dialog += $"role: {message.Role}\ncontent: {message.Content}\n\n";}}private async Task GetOpenAIChatCompletions(){string? text = this.dialog;// remove any * in texttext = text!.Replace("*", "");var lines = text.Split('\n');// delete empty items in lines arrayfor (var i = 0; i < lines.Length; i++){if (lines[i] == ""){lines = lines.Take(i).Concat(lines.Skip(i + 1)).ToArray();i--;}}var result = new List<Message>();for (var i = 0; i < lines.Length; i += 2){if (lines[i] == ""){continue;}var r = lines[i].Split(": ")[1];var c = lines[i + 1].Split(": ")[1];result.Add(new Message { Role = r, Content = c });}var response = await httpClient.PostAsJsonAsync("https://api.openai.com/v1/chat/completions", new{max_tokens = 50,n = 1,stop = "\n",model = "gpt-3.5-turbo",temperature = 0.5,messages = result});var data = await response.Content.ReadFromJsonAsync<OpenAIResponse>();Message? message = data!.choices![0].message;var content = message!.Content;var role = message!.Role;var reply = $"role: {role}\ncontent: {content}";this.dialog += "*" + reply + "*" + Environment.NewLine + Environment.NewLine;}private class Message{public string? Role { get; set; }public string? Content { get; set; }}private class OpenAIResponse{public Choice[]? choices { get; set; }}private class Choice{public Message? message { get; set; }}}
Explaining the above code:
- The UI consists of a textarea and button.
- OnInitialized() method
- remember to set the value of apiKey with the key that you obtained from https://openai.com
- an HTTP header with Authorization key is created with the appropriate Bearer value
- array named messages is declared with the initial dialog text
- the messages array is used to set the contents of the textarea
- GetOpenAIChatCompletions() method
- this method is called when the button is clicked
- a POST request is made to the endpoint at https://api.openai.com/v1/chat/completions
- response from the server is appended to the textarea. In order to distinguish the response from the rest of the dialog, it is surrounded by *
role: usercontent: How about in 2019? Which team won and where was it played?