Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
O

OpenAI-API-dotnet

> AI 编程
Open source

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

1.9K stars0 likes2 views
WebsiteGitHub

About

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

Microsoft reached out to me about transitioning this library into a new official C# OpenAI library and now it's ready to go! Starting with v2.0.0-beta.3, the official library now has full coverage and will stay up-to-date. More details in the blog post here: https://devblogs.microsoft.com/dotnet/openai-dotnet-library

This github repo will remain here to document my original version of the library through version 1.11, which is still available on Nuget as well.

C#/.NET SDK for accessing the OpenAI APIs, including GPT-3.5/4, GPT-3.5/4-Turbo, and DALL-E 2/3

A simple C# .NET wrapper library to use with OpenAI's API. More context on my blog. This is my original unofficial wrapper library around the OpenAI API.

Quick Example

csharp
var api = new OpenAI_API.OpenAIAPI("YOUR_API_KEY");
var result = await api.Chat.CreateChatCompletionAsync("Hello!");
Console.WriteLine(result);
// should print something like "Hi! How can I help you?"

Readme

  • Status
  • Requirements
  • Installation
  • Authentication
  • Chat API
    • Conversations
    • Streaming Results
    • GPT Vision
    • Chat Endpoint
    • Conversation History Context Length Management
    • JSON Mode
  • Completions API
    • Streaming completion results
  • Audio
    • Text to Speech
    • Transcribe Audio to Text
    • Translate Audio to English Text
  • Embeddings API
  • Moderation API
  • Files API
  • Image APIs (DALL-E)
    • DALLE-E 3
  • Azure
  • Additional Documentation
  • License

Status

Starting with v2.0.0-beta, this library has been adopted by Microsoft. The new official version of the library will have full coverage and will stay fully up-to-date. More details in the blog post here: https://devblogs.microsoft.com/dotnet/openai-dotnet-library/ This github repo will remain here to document my original version of the library through version 1.11, which is still available on Nuget as well.

Requirements

This library is based on .NET Standard 2.0, so it should work across all versions of .Net, from the traditional .NET Framework >=4.7.2 to .NET (Core) >= 3.0. It should work across console apps, winforms, wpf, asp.net, unity, Xamarin, etc. It should work across Windows, Linux, and Mac, and possibly even mobile. There are minimal dependencies, and it's licensed in the public domain.

Getting started

Install from NuGet

Install package OpenAI v1.11 from Nuget. Here's how via commandline:

powershell
Install-Package OpenAI -Version 1.11.0

Authentication

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

  1. Pass keys directly to APIAuthentication(string key) constructor
  2. Set environment var for OPENAI_API_KEY (or OPENAI_KEY for backwards compatibility)
  3. Include a config file in the local directory or in your user directory named .openai and containing the line:
bash
OPENAI_API_KEY=sk-aaaabbbbbccccddddd

You use the APIAuthentication when you initialize the API as shown:

csharp
// for example
OpenAIAPI api = new OpenAIAPI("YOUR_API_KEY"); // shorthand
// or
OpenAIAPI api = new OpenAIAPI(new APIAuthentication("YOUR_API_KEY")); // create object manually
// or
OpenAIAPI api = new OpenAIAPI(APIAuthentication LoadFromEnv()); // use env vars
// or
OpenAIAPI api = new OpenAIAPI(APIAuthentication LoadFromPath()); // use config file (can optionally specify where to look)
// or
OpenAIAPI api = new OpenAIAPI(); // uses default, env, or config file

You may optionally include an openAIOrganization (OPENAI_ORGANIZATION in env or config file) specifying which organization is used for an API request. Usage from these API requests will count against the specified organization's subscription quota. Organization IDs can be found on your Organization settings page.

csharp
// for example
OpenAIAPI api = new OpenAIAPI(new APIAuthentication("YOUR_API_KEY","org-yourOrgHere"));

Chat API

The Chat API is accessed via OpenAIAPI.Chat. There are two ways to use the Chat Endpoint, either via simplified conversations or with the full Request/Response methods.

Chat Conversations

The Conversation Class allows you to easily interact with ChatGPT by adding messages to a chat and asking ChatGPT to reply.

…

Chat Streaming

Streaming allows you to get results are they are generated, which can help your application feel more responsive.

Using the new C# 8.0 async iterators:

csharp
var chat = api.Chat.CreateConversation();
chat.AppendUserInput("How to make a hamburger?");

await foreach (var res in chat.StreamResponseEnumerableFromChatbotAsync())
{
	Console.Write(res);
}

Or if using classic .NET Framework or C# <8.0:

csharp
var chat = api.Chat.CreateConversation();
chat.AppendUserInput("How to make a hamburger?");

await chat.StreamResponseFromChatbotAsync(res =>
{
	Console.Write(res);
});

GPT Vision

You can send images to the chat to use the new GPT-4 Vision model. This only works with the Model.GPT4_Vision model. Please see https://platform.openai.com/docs/guides/vision for more information and limitations.

…

Conversation History Context Length Management

If the chat conversation history gets too long, it may not fit into the context length of the model. By default, the earliest non-system message(s) will be removed from the chat history and the API call will be retried. You may disable this by setting chat.AutoTruncateOnContextLengthExceeded = false, or you can override the truncation algorithm like this:

csharp
chat.OnTruncationNeeded += (sender, args) =>
{
	// args is a List<ChatMessage> with the current chat history.  Remove or edit as nessisary.
	// replace this with more sophisticated logic for your use-case, such as summarizing the chat history
	for (int i = 0; i < args.Count; i++)
	{
		if (args[i].Role != ChatMessageRole.System)
		{
			args.RemoveAt(i);
			return;
		}
	}
};

You may also wish to use a new model with a larger context length. You can do this by setting chat.Model = Model.GPT4_Turbo or chat.Model = Model.ChatGPTTurbo_16k, etc.

You can see token usage via chat.MostRecentApiResult.Usage.PromptTokens and related properties.

Chat Endpoint Requests

You can access full control of the Chat API by using the OpenAIAPI.Chat.CreateChatCompletionAsync() and related methods.

csharp
async Task<ChatResult> CreateChatCompletionAsync(ChatRequest request);

// for example
var result = await api.Chat.CreateChatCompletionAsync(new ChatRequest()
	{
		Model = Model.ChatGPTTurbo,
		Temperature = 0.1,
		MaxTokens = 50,
		Messages = new ChatMessage[] {
			new ChatMessage(ChatMessageRole.User, "Hello!")
		}
	})
// or
var result = api.Chat.CreateChatCompletionAsync("Hello!");

var reply = results.Choices[0].Message;
Console.WriteLine($"{reply.Role}: {reply.Content.Trim()}");
// or
Console.WriteLine(results);

It returns a ChatResult which is mostly metadata, so use its .ToString() method to get the text if all you want is assistant's reply text.

There's also an async streaming API which works similarly to the Completions endpoint streaming results.

JSON Mode

With the new Model.GPT4_Turbo or gpt-3.5-turbo-1106 models, you can set the ChatRequest.ResponseFormat to ChatRequest.ResponseFormats.JsonObject to enable JSON mode. When JSON mode is enabled, the model is constrained to only generate strings that parse into valid JSON object. See https://platform.openai.com/docs/guides/text-generation/json-mode for more details.

…

Completions API

Completions are considered legacy by OpenAI. The Completion API is accessed via OpenAIAPI.Completions:

csharp
async Task<CompletionResult> CreateCompletionAsync(CompletionRequest request);

// for example
var result = await api.Completions.CreateCompletionAsync(new CompletionRequest("One Two Three One Two", model: Model.CurieText, temperature: 0.1));
// or
var result = await api.Completions.CreateCompletionAsync("One Two Three One Two", temperature: 0.1);
// or other convenience overloads

You can create your CompletionRequest ahead of time or use one of the helper overloads for convenience. It returns a CompletionResult which is mostly metadata, so use its .ToString() method to get the text if all you want is the completion.

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.

Using the new C# 8.0 async iterators:

csharp
IAsyncEnumerable<CompletionResult> StreamCompletionEnumerableAsync(CompletionRequest request);

// for example
await foreach (var token in api.Completions.StreamCompletionEnumerableAsync(new CompletionRequest("My name is Roger and I am a principal software engineer at Salesforce.  This is my resume:", Model.DavinciText, 200, 0.5, presencePenalty: 0.1, frequencyPenalty: 0.1)))
{
	Console.Write(token);
}

Or if using classic .NET framework or C# <8.0:

csharp
async Task StreamCompletionAsync(CompletionRequest request, Action<CompletionResult> resultHandler);

// for example
await api.Completions.StreamCompletionAsync(
	new CompletionRequest("My name is Roger and I am a principal software engineer at Salesforce.  This is my resume:", Model.DavinciText, 200, 0.5, presencePenalty: 0.1, frequencyPenalty: 0.1),
	res => ResumeTextbox.Text += res.ToString());

Audio

The Audio API's are Text to Speech, Transcription (speech to text), and Translation (non-English speech to English text).

Text to Speech (TTS)

The TTS API is accessed via OpenAIAPI.TextToSpeech:

csharp
await api.TextToSpeech.SaveSpeechToFileAsync("Hello, brave new world!  This is a test.", outputPath);
// You can open it in the defaul audio player like this:
Process.Start(outputPath);

You can also specify all of the request parameters with a TextToSpeechRequest object:

csharp
var request = new TextToSpeechRequest()
{
	Input = "Hello, brave new world!  This is a test.",
	ResponseFormat = ResponseFormats.AAC,
	Model = Model.TTS_HD,
	Voice = Voices.Nova,
	Speed = 0.9
};
await api.TextToSpeech.SaveSpeechToFileAsync(request, "test.aac");

Instead of saving to a file, you can get audio byte stream with api.TextToSpeech.GetSpeechAsStreamAsync(request):

csharp
using (Stream result = await api.TextToSpeech.GetSpeechAsStreamAsync("Hello, brave new world!", Voices.Fable))
using (StreamReader reader = new StreamReader(result))
{
	// do something with the audio stream here
}

Transcription (Speech to Text)

The Audio Transcription API allows you to generate text from audio, in any of the supported languages. It is accessed via OpenAIAPI.Transcriptions:

csharp
string resultText = await api.Transcriptions.GetTextAsync("path/to/file.mp3");

You can ask for verbose results, which will give you segment and token-level information, as well as the standard OpenAI metadata such as processing time:

csharp
AudioResultVerbose result = await api.Transcriptions.GetWithDetailsAsync("path/to/file.m4a");
Console.WriteLine(result.ProcessingTime.TotalMillis

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#c-sharpchatgptcsharpdall-e

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
CategoryAI 编程
PricingOpen source

> Related tools

G
GitHub Copilot
GitHub 官方 AI 编程助手,覆盖补全、Chat 与 Agent 模式。
C
Cursor
AI 原生代码编辑器,对话改代码、多文件 Agent 与规则体系是其核心。
S
skills
Skills for Real Engineers. Straight from my .agents directory.