Skip to content

Netizine/OpenAI

OpenAI

Codacy Badge Codacy Badge GitHub Workflow Status (with branch) GitHub last commit GitHub Nuget

The unofficial OpenAI .NET library, supporting .NET Standard 2.0+, .NET Core 2.0+, and .NET Framework 4.6.2+.

Installation

Using the .NET Core command-line interface (CLI) tools:

dotnet add package Netizine.OpenAI

Using the NuGet Command Line Interface (CLI):

nuget install Netizine.OpenAI

Using the Package Manager Console:

Install-Package Netizine.OpenAI

From within Visual Studio:

  1. Open the Solution Explorer.
  2. Right-click on a project within your solution.
  3. Click on Manage NuGet Packages...
  4. Click on the Browse tab and search for "OpenAI".
  5. Click on the OpenAI package, select the appropriate version in the right-tab and click Install.

Documentation

For a comprehensive list of examples, check out the API documentation. See video demonstrations covering how to use the library.

Usage

Authentication

OpenAI authenticates API requests using your account’s secret key, which you can find in the OpenAI Dashboard. By default, secret keys can be used to perform any API request without restriction.

Use OpenAI.OpenAIConfiguration.ApiKey property to set the secret key.

OpenAI.OpenAIConfiguration.ApiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");

Retrieve a resource

The Retrieve method of the service class can be used to retrieve a resource:

ModelService modelService = new ModelService();
Model model = modelService.Get("davinci");
Console.WriteLine(model.OwnedBy);

Creating a resource

The Create method of the service class can be used to create a new resource:

ChatCompletionMessage chatMessage = new ChatCompletionMessage {
    Role = ChatRoles.User,
    Content = "Can you explain the meaning of life"
};
List<ChatCompletionMessage> chatMessageList = new List<ChatCompletionMessage>
{
    chatMessage
};
ChatGPT3CompletionService chatCompletionService = new ChatGPT3CompletionService();
ChatGPT3CompletionCreateOptions chatCompletionOptions = new ChatGPT3CompletionCreateOptions {
    Model = "gpt-3.5-turbo",
    Messages = chatMessageList,
    Temperature = 0,
};
ChatCompletion chatCompletion = chatCompletionService.Create(chatCompletionOptions);
Console.WriteLine(chatCompletion.Choices[0].Message);
CompletionService completionService = new CompletionService();
Completion completion = completionService.Create(new CompletionCreateOptions
{
    Prompt = "Say this is a test",
    Model = "text-davinci-003",
    MaxTokens = 7,
    Temperature = 0,
});
Console.WriteLine(completion.Id);

Deleting a resource

The Delete method of the service class can be used to delete a resource:

FileService fileService = new FileService();
File deleteFile = fileService.Delete(createdFile.Id, new FileDeleteOptions());
Console.WriteLine(deleteFile.Id);

Listing a resource

The List method on the service class can be used to list resources page-by-page.

ModelService modelService = new ModelService();
OpenAIList<Model> models = modelService.List();

// Enumerate the list
foreach (Model model in models)
{
    Console.WriteLine(model.Id);
}

FormEncoder provides methods to serialize various objects with application/x-www-form-urlencoded encoding.

var imageService = new ImageService();
Image editedImage = imageService.Edit(new EditImageCreateOptions
{
    Image = "otters.png",
    ImageSource = System.IO.File.ReadAllBytes("otters.png"),
    Mask = "otters-mask.png",
    MaskSource = System.IO.File.ReadAllBytes("otters-mask.png"),
    Prompt = "A cute baby sea otter wearing a beret",
    N = 2,
    Size = "1024x1024",
});
Console.WriteLine(editedImage.Data[0].Url);

Per-request configuration

All of the service methods accept an optional RequestOptions object. This is used if you want to pass the secret API key on each method etc.

var requestOptions = new RequestOptions
{
    ApiKey = "SECRET API KEY",
    OrganizationId = "ORGANIZATION ID"
};

Using a custom HttpClient

You can configure the library with your own custom HttpClient:

OpenAIConfiguration.OpenAIClient = new OpenAIClient(
    apiKey,
    httpClient: new SystemNetHttpClient(httpClient));

Please refer to the Advanced client usage page to see more examples of using custom clients, e.g. for using a proxy server, a custom message handler, etc.

Automatic retries

The library automatically retries requests on intermittent failures like on a connection error, timeout, or on certain API responses like a status 409 Conflict.

By default, it will perform up to two retries. That number can be configured with OpenAIConfiguration.MaxNetworkRetries:

OpenAIConfiguration.MaxNetworkRetries = 0; // Zero retries

How to use parameters and properties

OpenAI is a typed library and it supports all public properties or parameters. In cases where OpenAI adds some new features which introduce new properties or parameters that are not immediately available in the SDK, the library may not support these properties or parameters yet but there is still an approach that allows you to use them.

Parameters To pass undocumented parameters to OpenAI using the OpenAI SDK, you need to use the AddExtraParam() method, as shown below:

CompletionService completionService = new CompletionService();
var completionOptions = new CompletionCreateOptions
{
    Prompt = "Say this is a test",
    Model = "text-davinci-003",
    MaxTokens = 7,
    Temperature = 0,
};
completionOptions.AddExtraParam("new_feature_enabled", "true");
Completion completion = completionService.Create(completionOptions);
Console.WriteLine(completion.Id);

Properties

To retrieve undocumented properties from OpenAI using C# you can use an option in the library to return the raw JSON object and return the property. An example of this is shown below:

ModelService modelService = new ModelService();
Model model = modelService.Get("davinci");
var featureEnabled = model.RawJObject["feature_enabled"];

This information is passed along when the library makes calls to the OpenAI API.

dotnet add package OpenAI --version

Support

New features and bug fixes are released on the latest major version of the OpenAI .NET client library. If you are on an older major version, we recommend that you upgrade to the latest in order to use the new features and bug fixes including those for security vulnerabilities. Older major versions of the package will continue to be available for use, but will not be receiving any updates.

Development

The test suite depends on openai-mock, so make sure to fetch and run it from a background terminal (openai-mock's README also contains instructions for installing via Nuget):

dotnet tool install --global OpenAI.Mock
openai-mock

Alternatively, if you have already installed it, run

dotnet tool update --global OpenAI.Mock
openai-mock

Run all tests from the tests/OpenAI.Tests directory:

dotnet test

Run some tests, filtering by name:

dotnet test --filter FullyQualifiedName~ModelServiceTest

Run tests for a single target framework:

dotnet test --framework netcoreapp2.1

CI/CD Tests

If you need to run tests in a CI/CD pipeline, you can specify the OPENAI_MOCK_PORT environment variable to a specific port. Then in your pipeline, add a step to install the openai-mock server before running unit tests.

    - name: Install OpenAI.Mock
      run: dotnet tool install --global OpenAI.Mock

The library uses dotnet-format for code formatting. Code must be formatted before PRs are submitted, otherwise CI will fail. Run the formatter with:

dotnet format Netizine.OpenAI.sln

For any requests, bug or comments, please open an issue or submit a pull request.