Skip to content

MaochSoft/OpenAI-DotNet

 
 

Repository files navigation

C#/.NET SDK for accessing the OpenAI GPT-3 API

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.

Requirements

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.

Getting started

Install from NuGet

NuGet version (OpenAI-DotNet) Nuget Publish Discord

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:

openupm

Quick Start

Uses the default authentication from the current directory, the default user directory or system environment variables

OpenAI api = new OpenAI(Engine.Davinci);

Authentication

There are 3 ways to provide your API keys, in order of precedence:

  1. Pass keys directly to Authentication(string key) constructor
  2. Set environment variables
  3. 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:

If you want to provide a key manually

OpenAI api = new OpenAI("sk-mykeyhere");

Create a Authentication object manually

OpenAI api = new OpenAI(new Authentication("sk-secretkey"));

Use System Environment Variables

Use OPENAI_KEY or OPENAI_SECRET_KEY specify a key defined in the system's local environment:

OpenAI api = new OpenAI(Authentication LoadFromEnv());

Load key from specified directory

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"));;

Completions

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

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);
}

Document Search

The Search API is accessed via OpenAI.SearchEndpoint:

You can get all results as a dictionary using

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.

You can get only the best match using

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.

And if you only want the best match but still want to know the score, use

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

Classifications

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"

License

CC-0 Public Domain

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.

About

A fast lightweight library for OpenAI

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 100.0%