The ChatGPT language model from OpenAI was designed to respond to input in natural language and produce writing that resembles that of a person. Using transformer-based language modeling, ChatGPT was trained on a vast corpus of online content, including books, articles, news, and web pages.
You may build sophisticated chatbots, text analyzers, and even code generators using ChatGPT to enhance your apps with natural language processing capabilities.
It is capable of
A .NET library specifically designed to work with OpenAI APIs. By using these, you may simplify the integration process and allow apps to fully utilize Chat-GPT's capabilities.
Create an account on OpenAI Chat
We need to sign up for an OpenAI account before we can begin using ChatGPT.
Given below are the steps to register for a ChatGPT account.
Step – 1: Go to the OpenAI website ( https://chat.openai.com/auth/login )
Step – 2: You can signup and Log-in from the above website
Step – 3: You may create an account using your phone number, email address, Google or Microsoft account, or you can sign in if you already have one.
Step – 4: You will be sent to a screen where you must enter your password when the account creation is complete.
Step – 5: Use a secure password, and make sure your email address is legitimate to prevent misunderstandings.
Step – 6: Now that you have logged into ChatGPT, you may examine the ChatGPT performance and chat samples.
Create an OpenAI key
• Create an account on OpenAI platform for generating your own OpenAI key.
To use the c# ChatGPT API, you may require an API key from OpenAI.
When you get the API, you may use it to authenticate API requests.
Next, you need to create a new secret key as shown in the following figure.
Once the secret key has been generated, you can review the details of your secret key, including the name, private key, date it was produced, and the last time it was used as shown in the following figure.
Create an ASP.NET application
To create the asp.net ChatGPT demo application, first, you need to create a new C# project in Visual Studio.
Installation of OpenAI API
Installing the OpenAI C# SDK is the first step towards integrating ChatGPT. To do this with the NuGet package management, use the following command in the Package Manager Console:
Install-Package OpenAI
Initialize the SDK
You must initialize the OpenAI C# SDK after installing it by providing your OpenAI API key. You may do this by creating an instance of the OpenAIClient class and passing it your API key as a parameter.
var openAi = new OpenAIAPI("YOUR_API_KEY");
using OpenAI_API;
var openAi = new OpenAIAPI("YOUR_API_KEY");
using OpenAI_API;
var openAi = new OpenAIAPI("YOUR_API_KEY");
Start to add ChatGPT code in the application
The Chat API is accessed via OpenAIAPI.Chat. The ChatGPT API has been deployed, thus we can now contribute code to the application. All you need to do is swap out YOUR API KEY for your OpenAI API Key.
There are two ways to use the Chat Endpoint,
- Using simplified conversations
- With the full Request/Response methods.
Using simplified conversations
The Conversation Class enables you to easily interact with ChatGPT by adding messages to a conversation and asking ChatGPT to respond.
using System.Threading.Tasks;
static async Task Main(string[] args)
// Instances of the APIAuthentication class can be created using your API key.
var authentication = new APIAuthentication("YOUR_API_KEY");
// APIAuthentication object used to create an instance of the OpenAIAPI class
var api = new OpenAIAPI(authentication);
// ChatGPT lets you start a new chat.
var conversation = api.Chat.CreateConversation();
// Add user input and receive a reply from ChatGPT
conversation.AppendUserInput("YOUR_INPUT_HERE");
var response = await conversation.GetResponseFromChatbot();
Console.WriteLine(response);
// Before closing the terminal window, await user input.
using System;
using System.Threading.Tasks;
using OpenAI_API;
class Program
{
static async Task Main(string[] args)
{
// Instances of the APIAuthentication class can be created using your API key.
var authentication = new APIAuthentication("YOUR_API_KEY");
// APIAuthentication object used to create an instance of the OpenAIAPI class
var api = new OpenAIAPI(authentication);
// ChatGPT lets you start a new chat.
var conversation = api.Chat.CreateConversation();
// Add user input and receive a reply from ChatGPT
conversation.AppendUserInput("YOUR_INPUT_HERE");
var response = await conversation.GetResponseFromChatbot();
Console.WriteLine(response);
// Before closing the terminal window, await user input.
Console.ReadLine();
}
}
using System;
using System.Threading.Tasks;
using OpenAI_API;
class Program
{
static async Task Main(string[] args)
{
// Instances of the APIAuthentication class can be created using your API key.
var authentication = new APIAuthentication("YOUR_API_KEY");
// APIAuthentication object used to create an instance of the OpenAIAPI class
var api = new OpenAIAPI(authentication);
// ChatGPT lets you start a new chat.
var conversation = api.Chat.CreateConversation();
// Add user input and receive a reply from ChatGPT
conversation.AppendUserInput("YOUR_INPUT_HERE");
var response = await conversation.GetResponseFromChatbot();
Console.WriteLine(response);
// Before closing the terminal window, await user input.
Console.ReadLine();
}
}
To test this code, you have to write the input text at “YOUR_INPUT_HERE”.
Using the full Request/Response methods
Using OpenAIAPI.Chat, you may have access to all of the Chat API's controls and functions that go along with CreateChatCompletionAsync(). Use its function to retrieve a ChatResult that mostly contains metadata.
If you only need the prompt answer text, you may use toString() to obtain it. Check out this example where the ChatGPTTurbo Model is used.
async Task<chatresult> CreateChatCompletionAsync(ChatRequest request);
var result = await api.Chat.CreateChatCompletionAsync(new ChatRequest()
Model = Model.ChatGPTTurbo,
Messages = new ChatMessage[] {
new ChatMessage(ChatMessageRole.User, "Hello!")
var result = api.Chat.CreateChatCompletionAsync("Hello!");
var reply = results.Choices[0].Message;
Console.WriteLine($"{reply.Role}: {reply.Content.Trim()}");
Console.WriteLine(results);
async Task<chatresult> CreateChatCompletionAsync(ChatRequest request);
// for example
var result = await api.Chat.CreateChatCompletionAsync(new ChatRequest()
{
Model = Model.ChatGPTTurbo,
Temperature = 0.1,
MaxTokens = 50,
Messages = new ChatMessage[] {
new ChatMessage(ChatMessageRole.User, "Hello!")
}
})
// or
var result = api.Chat.CreateChatCompletionAsync("Hello!");
var reply = results.Choices[0].Message;
Console.WriteLine($"{reply.Role}: {reply.Content.Trim()}");
// or
Console.WriteLine(results);
</chatresult>
async Task CreateChatCompletionAsync(ChatRequest request);
// for example
var result = await api.Chat.CreateChatCompletionAsync(new ChatRequest()
{
Model = Model.ChatGPTTurbo,
Temperature = 0.1,
MaxTokens = 50,
Messages = new ChatMessage[] {
new ChatMessage(ChatMessageRole.User, "Hello!")
}
})
// or
var result = api.Chat.CreateChatCompletionAsync("Hello!");
var reply = results.Choices[0].Message;
Console.WriteLine($"{reply.Role}: {reply.Content.Trim()}");
// or
Console.WriteLine(results);
Azure OpenAI
When using the Azure OpenAI Service, you must include both your model deployment id and the name of your Azure OpenAI resource.
Configuration should look something like this for the Azure service:
OpenAIAPI api = OpenAIAPI.ForAzure("YourResourceName", "deploymentId", "api-key");
OpenAIAPI api = OpenAIAPI.ForAzure("YourResourceName", "deploymentId", "api-key");
OpenAIAPI api = OpenAIAPI.ForAzure("YourResourceName", "deploymentId", "api-key");
After that, you may utilize the API object as usual. Any of the other c# ChatGPT API examples or methods mentioned in the Authentication section above may also be specified as the APIAuthentication. This library does not yet support the AD-Flow; it only supports the API-key flow.
This brings us to the end of this blog. We hope this article has helped you understand the best practices of ChatGPT .net integration.