A simple C# .NET wrapper library to use with OpenAI's GPT-3 API. More context on Roger Pincombe's blog and forked from OpenAI-API-dotnet.
This library is based on .NET Standard 2.0, so it should work across .NET Framework >=4.7.2 and .NET Core >= 3.0. It should work across console apps, winforms, wpf, asp.net, etc. It should also work across Windows, Linux, and Mac.
Install package OpenAI
from Nuget. Here's how via command line:
Install-Package OpenAI-DotNet
Looking to use OpenAI in the Unity Game Engine? Check out our unity package on OpenUPM:
Uses the default authentication from the current directory, the default user directory or system environment variables
OpenAI api = new OpenAI(Engine.Davinci);
There are 3 ways to provide your API keys, in order of precedence:
- Pass keys directly to
Authentication(string key)
constructor - Set environment variables
- Include a config file in the local directory or in your user directory named
.openai
and containing the line:
OPENAI_KEY=sk-aaaabbbbbccccddddd
You use the Authentication
when you initialize the API as shown:
OpenAI api = new OpenAI("sk-mykeyhere");
OpenAI api = new OpenAI(new Authentication("sk-secretkey"));
Use
OPENAI_KEY
orOPENAI_SECRET_KEY
specify a key defined in the system's local environment:
OpenAI api = new OpenAI(Authentication LoadFromEnv());
Attempts to load api keys from a configuration file, by default
.openai
in the current directory, optionally traversing up the directory tree.
OpenAI api = new OpenAI(Authentication.LoadFromDirectory("C:\\MyProject"));;
The Completion API is accessed via OpenAI.CompletionEndpoint
:
var result = await api.CompletionEndpoint.CreateCompletionAsync("One Two Three One Two", temperature: 0.1, engine: Engine.Davinci);
Console.WriteLine(result);
Get the CompletionResult
(which is mostly metadata), use its implicit string operator to get the text if all you want is the completion choice.
Streaming allows you to get results are they are generated, which can help your application feel more responsive, especially on slow models like Davinci.
var api = new OpenAI();
await api.CompletionEndpoint.StreamCompletionAsync(result =>
{
foreach (var choice in result.Completions)
{
Console.WriteLine(choice);
}
}, "My name is Roger and I am a principal software engineer at Salesforce. This is my resume:", max_tokens: 200, temperature: 0.5, presencePenalty: 0.1, frequencyPenalty: 0.1, engine: Engine.Davinci);
The result.Completions
Or if using IAsyncEnumerable{T}
(C# 8.0+)
var api = new OpenAI();
await foreach (var token in api.CompletionEndpoint.StreamCompletionEnumerableAsync("My name is Roger and I am a principal software engineer at Salesforce. This is my resume:", max_tokens: 200, temperature: 0.5, presencePenalty: 0.1, frequencyPenalty: 0.1, engine: Engine.Davinci))
{
Console.Write(token);
}
The Search API is accessed via OpenAI.SearchEndpoint
:
var api = new OpenAI();
string query = "Washington DC";
string[] documents = { "Canada", "China", "USA", "Spain" };
Dictionary<string, double> results = await api.SearchEndpoint.GetSearchResultsAsync(query, documents, Engine.Curie);
// result["USA"] == 294.22
// result["Spain"] == 73.81
The returned dictionary maps documents to scores.
var api = new OpenAI();
string query = "Washington DC";
string[] documents = { "Canada", "China", "USA", "Spain" };
string result = await api.SearchEndpoint.GetBestMatchAsync(query, documents, Engine.Curie);
// result == "USA"
The returned document result string.
var api = new OpenAI();
string query = "Washington DC";
string[] documents = { "Canada", "China", "USA", "Spain" };
Tuple<string, double> result = await await api.SearchEndpoint.GetBestMatchWithScoreAsync(query, documents, Engine.Curie);
// (result, score) == "USA", 294.22
returned Tuple result with score
The Classification API is accessed via OpenAI.ClassificationEndpoint
:
Given a query and a set of labeled examples, the model will predict the most likely label for the query.
var api = new OpenAI();
string query = "It is a raining day :(";
string[] labels = { "Positive", "Negative", "Neutral" };
Dictionary<string, string> examples = new Dictionary<string, string>
{
{ "A happy moment", "Positive" },
{ "I am sad.", "Negative" },
{ "I am feeling awesome", "Positive"}
};
var result = await api.ClassificationEndpoint.CreateClassificationAsync(new ClassificationRequest(query, examples, labels));
// result.Label == "Negative"
This library is licensed CC-0, in the public domain. You can use it for whatever you want, publicly or privately, without worrying about permission or licensing or whatever. It's just a wrapper around the OpenAI API, so you still need to get access to OpenAI from them directly. I am not affiliated with OpenAI and this library is not endorsed by them, I just have beta access and wanted to make a C# library to access it more easily. Hopefully others find this useful as well. Feel free to open a PR if there's anything you want to contribute.