Tutorial: Integrating ChatGPT Model in a Cross-platform .NET Application

In this blog, we delve into the fascinating realm of AI and embedding ChatGPT APIs into .NET applications. We start by laying the foundation with the essential steps of ChatGPT integration in a .NET C# environment. From there, we will guide you in developing an Uno Platform application that integrates immersive text-based communication experiences that leverage the capabilities of OpenAI’s ChatGPT model. 

To better understand the process, you can follow along with the code sample provided below to accompany the step-by-step process.

Note: Among the remarkable initiatives of OpenAI is ChatGPT, an advanced conversational AI system designed to provide users with natural and captivating responses. ChatGPT leverages an extensive neural network model known as GPT-x (with “x” denoting its numerical version; currently 4.5 at the time of writing), which has been trained on vast volumes of text data. This powerful model enables ChatGPT to generate coherent and diverse texts across various topics.

Setting up ChatGPT APIs with Uno Platform and Visual Studio

Step 1: Create an OpenAI Account

To use Open-AI’s ChatGPT APIs, you will need to sign up for an account on their website and get an API key as shown below. 

Step 2: Install Uno Platform Extension

You will also need to install Visual Studio, and the Uno Platform extension for Visual Studio. You can find more details on how to set up your development environment on the Uno Platform documentation. 

Step 3: Create a New Project

Once you have everything ready, you can create a new Uno Platform project in Visual Studio. You can use the new template wizard to configure your project and target your platform. For this article’s companion sample code, I create a project with four heads: Windows, Android, iOS, and WebAssembly. 

Step 4: Install Open-AI .NET NuGet Package

The next step is to add the Open-AI .NET NuGet package to your project. This is a .NET wrapper for Open-AI’s APIs that make it easy to interact with them from C#. You can install it by right-clicking on your solution in the Solution Explorer and selecting Manage NuGet Packages for Solution. Then, search for Betalgo.OpenAI and install it on all your project heads. 

Getting Started with Application Logic

Now, you can start coding your application’s logic. First, you need to create an instance of the OpenAIService class and pass your API key as a parameter. You can store your API key in a constant string variable or in a configuration file.

For example:

				
					using OpenAI; 
using OpenAI.Managers; 
 
private OpenAIService _client; 
public OpenAIClient() 
{ 
    _client = new OpenAIService( 
    new OpenAiOptions() 
    { 
    ApiKey = "<insert api key here>" 
    }); 
 } 
				
			

Next, you need to create a method that will take the user input as a parameter and return the chatgpt responses as a list of string. There are 2 method that can be used: Create Completions and Chat Completions. You can use the  client.Completions.CreateCompletionand client.ChatCompletion.CreateCompletion  methods to call the ChatGPT API and pass some options to customize the behavior of the chatbot responses.

For example:

				
					public async Task<List<string>> CreateCompletions(string prompt) 
{ 
  var result = await _client.Completions.CreateCompletion(new CompletionCreateRequest() 
  { 
    Prompt = prompt, // Set the prompt to be the user input 
    Model = Models.TextDavinciV3, // Set the engine to be davinci, which is the most advanced one 
    Temperature = 0.7f, // Set the temperature to control the randomness of the response 
    MaxTokens = 512 // Set the maximum number of tokens to be generated 
    }); 
    if (result.Successful) 
    		{ 
    			return result.Choices.Select(choice => choice.Text).ToList(); 
    		} 
    		else 
    		{ 
    			if (result.Error == null) 
    			{ 
    				throw new Exception("Unknown Error"); 
    			} 
     
    			return new List<string>{ result.Error.Message ?? $"Unknown Error Message", result.Error.Code ?? $"Unknown Error Code." }; 
		} 
	} 
 
public async Task<List<string>> ChatCompletions(string prompt) 
{ 
  	var result = await _client.ChatCompletion.CreateCompletion(new ChatCompletionCreateRequest() 
  	{ 
  		Messages = new List<ChatMessage> 
  		{ 
  			ChatMessage.FromSystem("You are a helpful assistant."), 
  			ChatMessage.FromUser(prompt) 
  		}, 
  		Model = Models.ChatGpt3_5Turbo 
  	}); 
   
        if (result.Successful) 
        { 
            var _result = result.Choices.Select( choice => choice.Message.Content); 
  		return _result.ToList(); 
        } 
  	else 
  	{ 
  		if (result.Error == null) 
  		{ 
  			throw new Exception("Unknown Error"); 
  		} 
   
  		return	new List<string> { result.Error.Message ?? $"Unknown Error Message", result.Error.Code ?? $"Unknown Error Code." }; 
  	} 
  } 
} 
				
			

Building and Connecting your UI

In the last step, it’s essential to build a user interface (UI) for your application. You can employ XAML to design your UI and establish a binding between it and your code-behind using the MVVM (Model-View-ViewModel) or MVVM pattern. For instance, you can create a straightforward UI that incorporates a text box for user input, a button to send messages, and a stack panel to display the responses.

Below are some videos showcasing the application running seamlessly on Windows, iOS, Android, and WebAssembly platforms:

Play Video

ChatGPT, .NET and Uno Platform For-the-win

Congratulations! You have successfully developed an Uno Platform application using ChatGPT APIs and .NET. You are now ready to run your application on any platform of your choice and indulge in delightful conversations with your AI companion.

Enjoy the experience, and happy coding!

Next Steps

To upgrade to the latest release of Uno Platform, please update your packages to 4.9 via your Visual Studio NuGet package manager! If you are new to Uno Platform, following our official getting started guide is the best way to get started. (5 min to complete)

Tags: