Building AI-Chatbot App with ChatGPT API and Blazor: A Step-by-Step Guide

Introduction

Today, we will explore how to create a chatbot app that uses the ChatGPT API to enable natural language processing capabilities. We will go through the steps required to set up the project, design the ChatGPT service to integrate with ChatGPT API, and build a simple Blazor app that can respond to user input.

By the end of this article, you will have a working Blazor application that uses the power of ChatGPT.

I suppose I don't have to explain to you what ChatGPT is. If you don't know by now, then you really are "living in the woods".

So for people living in the woods, ChatGPT is an AI language model based on the Generative Pre-trained Transformer architecture hence the name goes like chat GPT. GPT is a deep learning algorithm that can process large amounts of text data points and generate human-like responses. (sometimes).

Final app preview

Building AI-Chatbot App with ChatGPT API and Blazor

We need just 6 steps to develop this application.

  • Step 1: Create a "Blazor-WebAssembly" or "Blazor-Server" application
  • Step 2: Add new Razor component > "ChatGPTComponent" 
  • Step 3: Create "ChatGPT-Service"
  • Step 4: Add "API-Key" to the application 
  • Step 5: Register "ChatGPT-Service" to "Blazor-App"
  • Step 6: Use the newly created "ChatGPT-Service" in "ChatGPTComponent"

Let's start.

Step 1. Create a Blazor WebAssembly or Blazor Server application

To create a new Blazor application, open Visual Studio and select "Create a new project". In the "Create a new project" dialog, select "Blazor WebAssembly App" or "Blazor Server App" and click "Next".

Building AI-Chatbot App with ChatGPT API and Blazor

In the next window, name your project and click "Create".

Building AI-Chatbot App with ChatGPT API and Blazor

Step 2. Add new Razor component > "ChatGPTComponent" 

To add a new component, right-click on the project, select "Add" then select "New item", which will bring the dialog below, then select "Razor component", give it a name, and click on the "Add" button.

Building AI-Chatbot App with ChatGPT API and Blazor

In the "ChatGPTComponent" component, add the following HTML to create a form with 2 text fields, one for request and another for a response, and also add a submit button which will call ChatGPT-Service.

@page "/"
@using System.Text;

<PageTitle>Chat GPT</PageTitle>
<body>
<EditForm Model="@AIRequest">
    <div class="searchArea">
        <button @onclick="GetAPIResponse"> Submit </button>
        <div class="inputDiv">
        <InputText class="form-control" @bind-Value="@AIRequest.Request" placeholder="Ask me anything.." />
        </div>
    </div>

    <div class="searchResult">
        <InputTextArea class="form-control" style="height:450px" @bind-Value="@AIRequest.Response" placeholder="AI will respond here..." readonly />
    </div>   
</EditForm>
</body>

Listing 1: ChatGPTComponent.razor

Next, we need a class to store API's request and response. Here create a class "Message" with 2 properties, Request, and Response.

class Message{
    public string Request { get; set; }
    public string Response { get; set; }
}

Listing 2: class Message

Inside the code section of ChatGPTComponent, create the class Message's instance, and add an event-handler "GetAPIResponse" for Send-button's click event. This will call ChatGP-Service(Listing 5) with the user's request as a parameter.

@code{
    Message AIRequest = new();

    public async Task GetAPIResponse()
    {
        try
        {
            AIRequest.Response = await chatService.GetResponse(AIRequest.Request);
        }
        catch (Exception)
        {
        }
    }
}

Listing 3: ChatGPTComponent.razor.cs

As they say, no web-app is complete without CSS. It's like saying no pizza is complete without cheese. So here is our cheese, I mean CSS below.

body {
    background-color: black;
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-height: 100vh;
}

/*--------------------------------------------------------------
# searchArea
--------------------------------------------------------------*/

.searchArea button, .searchArea .inputDiv, .searchArea input {
    height: 38px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0px 5px;
    border-radius: 10px;
}

.searchArea button {
    float: right;
    margin-left: 5px;
    border: solid 1px gray;
    width: 100px;
}

.searchArea .inputDiv {
    overflow: hidden;
    border: solid 1px gray;
}

.searchArea input {
    border: 0;
    width: 100%;
    padding: 0 3px;
    height: 22px;
}

.searchResult {
    margin: 5px;
    border-radius: 20px;
    height: 450px;
    overflow: hidden;
    border: solid 1px gray;
}

.textAreaStyle {
    height: 450px;
}

/*--------------------------------------------------------------
# Credits
--------------------------------------------------------------*/
.credits {
    position: fixed;
    right: 0;
    left: 0;
    bottom: 0;
    padding: 15px;
    text-align: right;
    font-size: 13px;
    color: #fff;
    z-index: 999999;
}

@media (max-width: 992px) {
    .credits {
        text-align: center;
        padding: 10px;
        background: rgba(0, 0, 0, 0.8);
    }
}

.credits a {
    color: #18d26e;
    transition: 0.3s;
}

    .credits a:hover {
        color: #fff;
    }

Listing 4: ChatGPTComponent.razor.css

Step 3. Create "ChatGPT-Service"

Start by adding the ChatGPTService class. Next, you'll need this class to act as a service to interact with the ChatGPT-API. So create a read-only field of HttpClient, which will make HTTP requests to the ChatGPT API. 

This class takes ChatGPT's API-key and baseUrl as parameters in its constructor and uses them to configure the HttpClient. It also defines a method called GetResponse that takes a user's query as parameters and returns a string representing the generated response. (If you remember from Listing 3, we are calling this method "GetResponse".) Once you have the response, deserialize Json and send the string to the UI.

using Newtonsoft.Json;
using System.Text;

namespace BlazingChatGPT.Data
{
    public class ChatGPTService
    {
        private readonly HttpClient _httpClient;

        public ChatGPTService(string baseUrl, string apiKey)
        {
            _httpClient = new();
            _httpClient.BaseAddress = new Uri(baseUrl);
            _httpClient.DefaultRequestHeaders.Add("authorization", $"Bearer {apiKey}");
        }

        public async Task<string> GetResponse(string query)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, _httpClient.BaseAddress)
            {
                Content = new StringContent("{\"model\": \"text-davinci-001\", \"prompt\": \"" + 
                                            query +
                                            "\",\"temperature\": 1,\"max_tokens\": 100}",
                                            Encoding.UTF8,
                                            "application/json")
            };

            var response = await _httpClient.SendAsync(request);
            response.EnsureSuccessStatusCode();

            var responseContent = await response.Content.ReadAsStringAsync();
            var responseString = JsonConvert.DeserializeObject<dynamic>(responseContent);

            return responseString!.choices[0].text;
        }
    }
}

Listing 5: class ChatGPTService

Step 4. Add "API-Key" to the application

To instantiate HttpClient with OpenAI's server, you need the server's name and API key.

To fetch the secret API key from OpenAI, follow these steps:

  1. Go to the OpenAI Developer Portal at https://platform.openai.com/
  2. Create an account by filling out the registration form and agreeing to the terms of service.
  3. Once you have signed up, log in to the Developer Dashboard and click on the "API Keys" tab.
  4. Click on the "Create API Key" button to create a new API key.

Once you have created your API key, it will be displayed on the screen. Copy the key and keep it in a secure location. Finally, use the API key to authenticate requests to the ChatGPT-API and integrate it into your application or website as needed.

Also, make sure you never share your API key anywhere publicly

You must read API Documentation for a better understanding of API's: platform.openai.com/docs/api-reference

Integrating API key into the app

For simplicity, I am adding a dummy-key in appSettings, you can encrypt your key if the source code is going to be public.

Open appSettings.json and add the following API-URL and API-Key

  "ChatGPTSettings": {
    "ApiURL": "https://api.openai.com/v1/completions",
    "ApiKey": "your API key goes here"
  }

Listing 6: appsettings.json

Step 5. Register "ChatGPT-Service" to "Blazor-App"

To use the ChatGPT-Service in your Blazor app, you'll need to register it with the dependency injection container. You can do this in the Program.cs file of your Blazor app (This is your startup file of an app).

builder.Services.AddSingleton<ChatGPTService>(cp =>
{
    var config = cp.GetRequiredService<IConfiguration>();
    var apiUrl = config.GetValue<string>("ChatGPTSettings:ApiURL");
    var apiKey = config.GetValue<string>("ChatGPTSettings:ApiKey");
    return new ChatGPTService(apiUrl, apiKey);
});

Listing 7: program.cs

We use the Config object to read the ChatGPT-API key from the app's configuration file appsettings.json, and register the ChatGPTService as a singleton with the dependency injection container.

Step 6. Use the newly created "ChatGPT-Service" in "ChatGPTComponent"

Simply inject an instance of the ChatGPT-Service into your ChatGPTComponent, like this:

@inject ChatGPTService chatService

You can then call chatService's methods to interact with the ChatGPT-Service. After merging all the code, let me show you the final version of "ChatGPTComponent.razor" after merging all the code.

@page "/"
@using System.Text
@using BlazingChatGPT.Data;

@inject ChatGPTService chatService

<PageTitle>Chat GPT</PageTitle>
<body>
<EditForm Model="@AIRequest">
    <div class="searchArea">
        <button @onclick="GetAPIResponse"> Submit </button>
        <div class="inputDiv">
        <InputText class="form-control" @bind-Value="@AIRequest.Request" placeholder="Ask me anything.." />
        </div>
    </div>

    <div class="searchResult">
        <InputTextArea class="form-control" style="height:450px" @bind-Value="@AIRequest.Response" placeholder="AI will respond here..." readonly />
    </div>
    
</EditForm>
</body>
@code{
    Message AIRequest = new();

    public async Task GetAPIResponse()
    {
        try
        {
            AIRequest.Response = await chatService.GetResponse(AIRequest.Request);
        }
        catch (Exception)
        {
        }
    }

    class Message{
       public string Request { get; set; }
       public string Response { get; set; }
    }
}

Listing 8: ChatGPTComponent.razor

Hold on to your hats folks, there's only a single task remaining!

Get rid of Index.razor, as our newly added component ChatGPTComponent.razor is now a new index page. If you see its routing at line 1, we are specifying it as @page "/", indicating that this is now the index page of the app.

Conclusion

Building a chatbot app with ChatGPT API and Blazor can be a great way to create a conversational interface that can automate various tasks and provide personalized experiences for users. Following the step-by-step guide in this article, you can easily set up a Blazor project, integrate the ChatGPT API, and deploy your chatbot app to the cloud. Overall, this guide provides a solid foundation for building your chatbot app with ChatGPT API and Blazor.