Betalgo.OpenAI is a C# library that allows us to use OpenAI services, such as ChatGPT or Dall-E, from a .NET application.
OpenAI is an artificial intelligence research organization, creators, among others, of the popular Dall-E and ChatGPT models. Unless you have been disconnected in recent months, you probably have at least heard of these two OpenAI utilities.
DALL-E is a deep learning model that generates images from textual descriptions. On the other hand, ChatGPT is a library for natural language processing based on the GPT (Generative Pre-trained Transformer) architecture that allows creating high-quality chatbots and dialogue systems.
These services have an API that we can use to use these services from our programs. There is no official API for C#, but various libraries have emerged that allow us to connect to the OpenAI API from .NET.
Today we will see Betalgo.OpenAI, which for the moment is the most popular for C#, and certainly the one I liked the most.
Configuring OpenAI to work with C#
Before starting to use ChatGPT in C#, it is necessary to set up the OpenAI API key in the development environment.
To do this, go to this address https://platform.openai.com/account/api-keys and create a new API Key for your account.
Obviously, do not share the code with anyone
You will need to associate a credit card to make payments. However, for your peace of mind, it is possible to set a usage limit.
How much does OpenAI cost
As for the price, it depends on the functionality we want to use. But for now, in my opinion, it is really cheap.
For example, generating text with ChatGPT (gpt-3.5-turbo model) costs $0.002 / 1K tokens. 1 token is a measure related to the length of the message (prompt + response). Approximately,
- In English tokens = 1.25 * number of words
- In Spanish tokens = 2.00 * number of words
That is, a long response (2000) tokens costs 0.004$. In other words, you would have to make 1000 “long” requests to spend 2$. Which seems very cheap to me.
Here is a tool to estimate the number of tokens in a text https://platform.openai.com/tokenizer
Tip, if you want to save money, make repetitive and long prompts in English, and ask for the response in Spanish
On the other hand, generating an image with Dall-E costs 0.020$ for a resolution of 1024x1024. That is, you would have to generate 100 images to spend 2$.
To see the price of the rest of the services, check the official documentation available at https://openai.com/pricing
How to use Betalgo.OpenAI
Once the API key is set up, it is possible to use OpenAI services from C#. To do this, I will use the Betalgo.OpenAI library, which as I said for the moment seems the most complete.
We can easily add the library to a .NET project through the corresponding Nuget package.
Install-Package Betalgo.OpenAI
Here are some examples of how to use Betalgo.OpenAI taken from the library’s documentation.
Using ChatGPT with C#
Having a dialogue with ChatGPT is very simple. We only need to instantiate the Service with our ApiKey, and use the “CreateCompletition” function.
using OpenAI.GPT3.ObjectModels.RequestModels;
using OpenAI.GPT3.ObjectModels;
using OpenAI.GPT3.Managers;
using OpenAI.GPT3;
var openAiService = new OpenAIService(new OpenAiOptions()
{
ApiKey = "your_api_key",
});
var completionResult = await openAiService.ChatCompletion.CreateCompletion(new ChatCompletionCreateRequest
{
Messages = new List<ChatMessage>
{
ChatMessage.FromSystem("You are a helpful assistant."),
ChatMessage.FromUser("Who won the world series in 2020?"),
ChatMessage.FromAssistant("The Los Angeles Dodgers won the World Series in 2020."),
ChatMessage.FromUser("Where was it played?")
},
Model = Models.ChatGpt3_5Turbo,
MaxTokens = 1000,
Temperature = 0.7f,
TopP = 1,
PresencePenalty = 0,
FrequencyPenalty = 0,
});
if (completionResult.Successful)
{
Console.WriteLine(completionResult.Choices.First().Message.Content);
}
As we can see, we can simulate complete conversations, including System, User, and Assistant messages. In general, in many cases, we may only want a single System + User, or even just User.
Using Dall-E with C#
Creating an image with Dall-E is even simpler. We just have to do.
var imageResult = await openAiService.Image.CreateImage(new ImageCreateRequest
{
Prompt = "Laser cat eyes",
N = 2,
Size = StaticValues.ImageStatics.Size.Size256,
ResponseFormat = StaticValues.ImageStatics.ResponseFormat.Url,
User = "TestUser"
});
Using Moderation with C#
Moderation is an OpenAI service that allows determining the intent of a text. It returns an array with scores in categories such as ‘hate’, ‘violence’, ‘self-harm’, among others.
var moderationResponse = await openAiService.Moderation.CreateModeration(new CreateModerationRequest()
{
Input = "I want to kill them."
});
if (moderationResponse.Results.FirstOrDefault()?.Flagged != true)
{
ConsoleExtensions.WriteLine("Create Moderation test failed", ConsoleColor.DarkRed);
}
ConsoleExtensions.WriteLine("Create Moderation test passed.", ConsoleColor.DarkGreen);
Using Whisper with C#
Whisper is OpenAI’s voice-to-text transcription service. This is how we could use it.
const string fileName = "micro-machines.mp3";
var sampleFile = await FileExtensions.ReadAllBytesAsync($"SampleData/{fileName}");
var audioResult = await sdk.Audio.CreateTranscription(new AudioCreateTranscriptionRequest
{
FileName = fileName,
File = sampleFile,
Model = Models.WhisperV1,
ResponseFormat = StaticValues.AudioStatics.ResponseFormat.VerboseJson
});
if (audioResult.Successful)
{
Console.WriteLine(string.Join("\n", audioResult.Text));
}
else
{
if (audioResult.Error == null)
{
throw new Exception("Unknown Error");
}
Console.WriteLine($"{audioResult.Error.Code}: {audioResult.Error.Message}");
}
Although I personally do not advise you to do it, because there are offline ways to run Whisper (for free). We will see them in an upcoming article.
Conclusion
Betalgo.OpenAI is a really great library that allows us to access all OpenAI services. The documentation is very extensive and includes examples for all the functionalities.
It is compatible with .NET Standard 2.0 and .NET 6 or higher. Therefore, it is cross-platform, and we can use it on Windows, Linux, Android, and MacOs. You have no idea how well it works on a Raspberry PI 😉.
Betalgo.OpenAI is Open Source and all the code and documentation are available in the project repository at https://github.com/betalgo/openai