In this OpenAI .NET blog post, we will demonstrate how to create a web application running on Blazor that translates text using GPT-4o.

With the official OpenAI .NET library, it is possible to leverage the entire OpenAI API, including the latest Responses API. This post will guide you in creating a simple web application that translates text from English to two languages (additional languages can be added).

Get Started

To create the web application, an OpenAI developer account with an API key is required to make API calls to the OpenAI API service.

Create Blazor Web Application

To create a Blazor web application, use Dotnet CLI (`dotnet new blazor`) or Visual Studio Code.

Install OpenAI .NET Library

The main component of the web application is the OpenAI .NET library. To utilize the latest features, install the latest version using the following dotnet command:

dotnet add package OpenAI --prerelease

Create OpenAI Service

To interact with the OpenAI API, a service needs to be created to send the text for translation to the GPT-4o LLM model. From the root folder of the Blazor application, create a folder named Services. Inside this folder, create a file named TranslateService.cs.

Service Configuration

With the folder structure established, we can proceed to configure the service. The following code snippet creates a service and a function that receives text input along with the target language for translation.

Add Service to main

Add the following code in the Program.cs file to register the service.

User Interface

Finally, create a user interface to send input to the service. Add the following code to the Home.razor page.

Run and Test

To run the web application, execute the program using `dotnet run` and open a web browser. The interface will appear as shown. To see a demonstration of how it works, visit the following demo page which uses the same code.


Discover more from CPI Consulting Pty Ltd Experts in Cloud, AI and Cybersecurity

Subscribe to get the latest posts sent to your email.