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 6.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:
var api = new OpenAIClient();
There are 3 ways to provide your API keys, in order of precedence:
- Pass keys directly with constructor
- Load key from configuration file
- Use System Environment Variables
You use the OpenAIAuthentication
when you initialize the API as shown:
var api = new OpenAIClient("sk-mykeyhere");
Or create a OpenAIAuthentication
object manually
var api = new OpenAIClient(new OpenAIAuthentication("sk-secretkey"));
Attempts to load api keys from a configuration file, by default .openai
in the current directory, optionally traversing up the directory tree or in the user's home directory.
To create a configuration file, create a new text file named .openai
and containing the line:
OPENAI_KEY=sk-aaaabbbbbccccddddd
You can also load the file directly with known path by calling a static method in Authentication:
var api = new OpenAIClient(OpenAIAuthentication.LoadFromDirectory("C:\\Path\\To\\.openai"));;
Use
OPENAI_KEY
orOPENAI_SECRET_KEY
specify a key defined in the system's local environment:
var api = new OpenAIClient(OpenAIAuthentication.LoadFromEnv());
List and describe the various models available in the API. You can refer to the Models documentation to understand what models are available and the differences between them.
The Models API is accessed via OpenAIClient.ModelsEndpoint
.
Lists the currently available models, and provides basic information about each one such as the owner and availability.
var api = new OpenAIClient();
var models = await api.ModelsEndpoint.GetModelsAsync();
Retrieves a model instance, providing basic information about the model such as the owner and permissioning.
var api = new OpenAIClient();
var model = await api.ModelsEndpoint.GetModelDetailsAsync("text-davinci-003");
The Completion API is accessed via OpenAIClient.CompletionEndpoint
:
var api = new OpenAIClient();
var result = await api.CompletionEndpoint.CreateCompletionAsync("One Two Three One Two", temperature: 0.1, model: Model.Davinci);
Debug.Log(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 OpenAIClient();
await api.CompletionEndpoint.StreamCompletionAsync(result =>
{
foreach (var choice in result.Completions)
{
Debug.Log(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, model: Model.Davinci);
The result.Completions
Or if using IAsyncEnumerable{T}
(C# 8.0+)
var api = new OpenAIClient();
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, model: Model.Davinci))
{
Debug.Log(token);
}
Given a prompt and an instruction, the model will return an edited version of the prompt.
The Edits API is accessed via OpenAIClient.EditsEndpoint
.
Creates a new edit for the provided input, instruction, and parameters using the provided input and instruction.
The Create Edit API is accessed via OpenAIClient.ImagesEndpoint.CreateEditAsync()
.
var api = new OpenAIClient();
var request = new EditRequest("What day of the wek is it?", "Fix the spelling mistakes");
var result = await api.EditsEndpoint.CreateEditAsync(request);
Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.
Related guide: Embeddings
The Edits API is accessed via OpenAIClient.EmbeddingsEndpoint
.
Creates an embedding vector representing the input text.
The Create Embedding API is accessed via OpenAIClient.EmbeddingsEndpoint.CreateEmbeddingAsync()
.
var api = new OpenAIClient();
var result = await api.EmbeddingsEndpoint.CreateEmbeddingAsync("The food was delicious and the waiter...");
Given a prompt and/or an input image, the model will generate a new image.
The Images API is accessed via OpenAIClient.ImagesEndpoint
.
Creates an image given a prompt.
The Create Image API is accessed via OpenAIClient.ImagesEndpoint.GenerateImageAsync()
.
var api = new OpenAIClient();
var results = await api.ImageGenerationEndPoint.GenerateImageAsync("A house riding a velociraptor", 1, ImageSize.Small);
// results == array of image urls to download
Creates an edited or extended image given an original image and a prompt.
The Edit Image API is accessed via OpenAIClient.ImagesEndPoint.CreateImageEditAsync()
:
var api = new OpenAIClient();
var results = await api.ImagesEndPoint.CreateImageEditAsync(Path.GetFullPath(imageAssetPath), Path.GetFullPath(maskAssetPath), "A sunlit indoor lounge area with a pool containing a flamingo", 1, ImageSize.Small);
// results == array of image urls to download
Creates a variation of a given image.
The Edit Image API is accessed via OpenAIClient.ImagesEndPoint.CreateImageVariationAsync()
:
var api = new OpenAIClient();
var results = await api.ImagesEndPoint.CreateImageVariationAsync(Path.GetFullPath(imageAssetPath), 1, ImageSize.Small);
// results == array of image urls to download
Given a input text, outputs if the model classifies it as violating OpenAI's content policy.
Related guide: Moderations
Classifies if text violates OpenAI's Content Policy.
The Moderations endpoint can be accessed via OpenAIClient.ModerationsEndpoint.GetModerationAsync()
:
var api = new OpenAIClient();
var response = await api.ModerationsEndpoint.GetModerationAsync("I want to kill them.");
// response == true
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.