Saturday, June 10, 2023

Using ChatGPT Chat Completion API with ASP.NET Blazor Web Assembly

In this tutorial you will create a very simple Blazor Web Assembly application that interacts with ChatGPT.


You will need the following:

  • .NET 7.0 or higher
  • Visual Studio Code
  • A ChatGPT account with

Get an ChatGPT API key from

Visit 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.

Give your key a name, then click on “Generate secret key”.

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

We will create a very simple Chat Completion client-side blazor app that discusses topics relating to the National Basketball Association (NBA).

In a working folder, execute the following terminal window commands to create an ASP.NET Blazor Web Assembly application named ChatGPTBlazorWasm:

dotnet new blazorwasm -n ChatGPTBlazorWasm
cd ChatGPTBlazorWasm

Open the blazor application in VS Code with:

code .

Replace contents of Pages/Index.razor with the following code:

@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 text
        text = text!.Replace("*", "");

        var lines = text.Split('\n');

        // delete empty items in lines array
        for (var i = 0; i < lines.Length; i++)
            if (lines[i] == "")
                lines = lines.Take(i).Concat(lines.Skip(i + 1)).ToArray();

        var result = new List<Message>();

        for (var i = 0; i < lines.Length; i += 2)
            if (lines[i] == "")
            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("", 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
    • 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
    • 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 *
After replacing the value of apiKey in the onInitialized() method, run the application by executing the following command i a terminal window:

dotnet watch

You should see the following page:

Note the text grounded in the NBA context about where the 2020 finals were played. Click on the green "Call Completion" button. The response indicates the the finals were held during the COVID pandemic in Orlando.

Let’s ask about what happened a year earlier in 2019 by appending this additional text:

role: user
content: How about in 2019? Which team won and where was it played?

Click on the “Call Completion” button.  Our page now looks like this:

We are told that the 2019 NBA champions were the Toronto Raptors.

You can see from this very simple tutorial that it is quite easy to incorporate ChaGPT into your Blazor Web Assembly applications.

No comments:

Post a Comment