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 of, among others, the popular Dall-E and ChatGPT models. Unless you’ve been disconnected for the last few months, you’ve probably 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 natural language processing library 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 are going to see Betalgo.OpenAI, which for now is the most popular for C#, and certainly the one I liked the most.
Configure OpenAI to work with C#
Before starting to use ChatGPT in C#, it is necessary to configure the OpenAI API key in the development environment.
To do this, go to 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
Regarding 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$. That is, 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
Little trick, if you want to save money, make repetitive and long prompts in English, and ask it to respond 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, consult the official documentation available at https://openai.com/pricing
How to use Betalgo.OpenAI
Once the API key is configured, it is possible to use OpenAI services from C#. For this I will use the Betalgo.OpenAI library, which as I said, for now seems the most complete to me.
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 extracted from the library’s documentation.
Use ChatGPT with C#
Having a dialogue with ChatGPT is very simple. We just instantiate the Service with our ApiKey, and use the “CreateCompletion” 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 will only want a single System + User, or even just User.
Use 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"
});
Use Moderation
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);
Use Whisper with C#
Whisper is OpenAI’s speech-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 don’t recommend doing it, because there are offline ways to run Whisper (for free). We’ll see them in a future 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 functionalities.
It is compatible with .NET Standard 2.0 and .NET 6 or higher. So it is cross-platform, and we can use it on Windows, Linux, Android, and MacOs. You wouldn’t believe how well it works on a Raspberry PI 😉.
Betalgo.OpenAI is Open Source and all the code and documentation is available in the project repository at https://github.com/betalgo/openai

