Using OpenAI API to Generate Text in a Blazor WASM

Using OpenAI API to Generate Text in a Blazor WASM

Step 1: Set up a new Blazor WebAssembly Project

Create the Blazor WebAssembly App: Open your terminal or command prompt and run the following command to create a new Blazor WebAssembly app:

dotnet new blazorwasm -o OpenAIBlazorApp

This will create a new Blazor WebAssembly application in a folder named OpenAIBlazorApp.

Navigate to the project directory:

Step 2: Install HttpClient and Add Services

The application will need to make HTTP requests to the OpenAI API. Ensure you have HttpClient set up in your Program.cs to call external APIs.

Open the project in Visual Studio 2022

Edit the Program file to appear as below:

Step 3: Create the API Service to Call OpenAI

  1. Create a folder called Services in your project.
  2. Add a new class OpenAIService.cs inside the Services folder:

Write the following code in the OpenAIService class

using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;

namespace OpenAIBlazorApp.Services
{
    public class OpenAIService
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiKey = "<YOUR-API-KEY>"; // Add your OpenAI API key here

        public OpenAIService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<string> GenerateTextAsync(string prompt)
        {
            // API endpoint for text completion (GPT-3 or GPT-4)
            var url = "https://api.openai.com/v1/completions";
            
            var requestData = new
            {
                model = "text-davinci-003", // You can use other models too
                prompt = prompt,
                max_tokens = 150,
                temperature = 0.7
            };

            var jsonContent = JsonSerializer.Serialize(requestData);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            // Add the Authorization header with the API key
            content.Headers.Add("Authorization", $"Bearer {_apiKey}");

            var response = await _httpClient.PostAsync(url, content);

            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                var completion = JsonSerializer.Deserialize<JsonElement>(responseContent);
                return completion.GetProperty("choices")[0].GetProperty("text").GetString();
            }
            else
            {
                return "Error: Unable to generate text.";
            }
        }
    }
}

Step 4: Register the Service in Program.cs

builder.Services.AddScoped();

Step 5: Create the Blazor UI for Interaction

  1. Open the Pages/Home.razor file and replace its contents with the following code to create a UI that allows the user to enter a prompt and display the generated response:
@page "/"
@inject OpenAIService OpenAIService

<h3>Generate Text using OpenAI</h3>

<div>
    <label for="promptInput">Enter your prompt:</label>
    <textarea id="promptInput" @bind="prompt" rows="4" cols="50"></textarea>
</div>
<br />

<button @onclick="GenerateText" class="btn btn-primary">Generate</button>

<div>
    <h4>Response:</h4>
    <p>@generatedText</p>
</div>

@code {
    private string prompt = string.Empty;
    private string generatedText = string.Empty;

    private async Task GenerateText()
    {
        if (string.IsNullOrWhiteSpace(prompt))
        {
            generatedText = "Please enter a prompt.";
            return;
        }

        generatedText = "Generating...";

        try
        {
            generatedText = await OpenAIService.GenerateTextAsync(prompt);
        }
        catch
        {
            generatedText = "An error occurred while contacting the API.";
        }
    }
}

Key Points:

  • prompt is bound to the textarea input.
  • When the “Generate” button is clicked, the GenerateText method is called to invoke the OpenAIService and display the generated text.
  • generatedText is displayed in the UI once the response is received.

Step 6: Run the Application

  1. Build and run the application:
    • In Visual Studio, click “Run” or press Ctrl + F5.

Step 7: Test the Application

  1. Enter a prompt like “Explain the concept of closures in JavaScript” in the textarea.
  2. Click Generate.
  3. After a few seconds, you should see the response from the OpenAI API, explaining the concept of closures.
Follow Me Here

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.