This is an unofficial C# library for the OpenAI API. As there are no official libraries available, we have created our own to help C# developers interact with the API easily.
To install the ManagedCode.OpenAI library from NuGet, you can use the following methods:
Open the Package Manager Console in Visual Studio and run the following command:
Install-Package ManagedCode.OpenAI
You can also use the .NET CLI to install the package. Open a terminal/command prompt and run the following command:
dotnet add package ManagedCode.OpenAI
Initializing the client You can initialize the client in two ways:
var client1 = GptClient.Builder("#API_KEY#")
.WithOrganization("#ORGANIZATION#")
.Build();
var client2 = GptClient.Builder("#API_KEY#")
.WithOrganization("#ORGANIZATION#")
.Configure(x => x.SetDefaultModel(GptModel.Ada))
.Build();
or using DI
builder.Services.AddOpenAI("#API_KEY#");
public class MyClass
{
public MyClass(IGptClient client)
{
var chat = client.OpenChat();
}
}
var client = GptClient.Builder("#API_KEY#")
.WithOrganization("#ORGANIZATION#")
.Build();
var chat = client.OpenChat();
var answer = await chat.AskAsync("2+2?");
Console.WriteLine($"Answer: {answer.Data.Content}");
var client = new GptClient("#API_KEY#");
var img = await client.ImageClient
.GenerateImage("Big man")
.AsUrl().ExecuteAsync();
var url = img.Content;
Console.WriteLine(url);
var client = new GptClient("#API_KEY#");
var imgBytes = new byte[] { };
var maskBase64 = "#CONTENT#";
var img = await client.ImageClient
.EditImage("Change color to red", x => x.FromBytes(imgBytes))
.SetImageMask(x => x.FromBase64(maskBase64))
.AsUrl().ExecuteAsync();
// Edited img URL
Console.WriteLine(img.Content);
var client = new GptClient("#API_KEY#");
var imgBytes = new byte[] { };
var imgCollection = await client.ImageClient
.VariationImage(x => x.FromBytes(imgBytes))
.AsBase64String()
.ExecuteMultipleAsync(5);
foreach (var imageBase64 in imgCollection.Content)
Console.WriteLine(imageBase64);
Create multiple variations of an image in base64 string format with 5 results:
var client = new GptClient("#API_KEY#");
var imgBytes = new byte[] { };
var imgCollection = await client.ImageClient
.VariationImage(x => x.FromBytes(imgBytes))
.AsBase64String()
.ExecuteMultipleAsync(5);
foreach (var imageBase64 in imgCollection.Content)
Console.WriteLine(imageBase64);
We welcome contributions to this project. Please submit a pull request or create an issue if you'd like to help improve this library.