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

OpenAI-DotNet

> AI 编程
Open source

A Non-Official OpenAI RESTful API Client for DotNet

760 stars0 likes0 views
WebsiteGitHub

About

A Non-Official OpenAI RESTful API Client for DotNet

OpenAI-DotNet

A simple C# .NET client library for OpenAI to use though their RESTful API. Independently developed, this is not an official library and I am not affiliated with OpenAI. An OpenAI API account is required.

Originally Forked from OpenAI-API-dotnet. More context on Roger Pincombe's blog.

Requirements

  • This library targets .NET 8.0 and above.
  • 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

Install package OpenAI-DotNet from Nuget. Here's how via command line:

powershell:

terminal
Install-Package OpenAI-DotNet

dotnet:

terminal
dotnet add package OpenAI-DotNet

Looking to use OpenAI-DotNet in the Unity Game Engine? Check out our unity package on OpenUPM:

Documentation

Check out our new api docs!

Table of Contents

  • Authentication
  • Azure OpenAI
    • Azure Active Directory Authentication
  • OpenAI API Proxy
  • Models
    • List Models
    • Retrieve Models
    • Delete Fine Tuned Model
  • Responses
    • Create Response
      • Simple Text Response
      • Streaming Response with Function Calling
    • Get Response
    • List Input Items
    • Cancel Response
    • Delete Response
  • Conversations
    • Create Conversation
    • Retrieve Conversation
    • Update Conversation
    • Delete Conversation
    • List Conversation Items
    • Create Conversation Item
    • Retrieve Conversation Item
    • Delete Conversation Item
  • Realtime
    • Create Realtime Session
    • Client Events
      • Sending Client Events
    • Server Events
      • Receiving Server Events
  • Assistants
    • List Assistants
    • Create Assistant
    • Retrieve Assistant
    • Modify Assistant
    • Delete Assistant
    • Assistant Streaming
    • Threads
      • Create Thread
      • Create Thread and Run
        • Streaming
      • Retrieve Thread
      • Modify Thread
      • Delete Thread
      • Thread Messages
        • List Messages
        • Create Message
        • Retrieve Message
        • Modify Message
      • Thread Runs
        • List Runs
        • Create Run
          • Streaming
        • Retrieve Run
        • Modify Run
        • Submit Tool Outputs to Run
        • Structured Outputs
        • List Run Steps
        • Retrieve Run Step
        • Cancel Run
    • Vector Stores
      • List Vector Stores
      • Create Vector Store
      • Retrieve Vector Store
      • Modify Vector Store
      • Delete Vector Store
      • Vector Store Files
        • List Vector Store Files
        • Create Vector Store File
        • Retrieve Vector Store File
        • Delete Vector Store File
      • Vector Store File Batches
        • Create Vector Store File Batch
        • Retrieve Vector Store File Batch
        • List Files In Vector Store Batch
        • Cancel Vector Store File Batch
  • Chat
    • Chat Completions
    • Streaming
    • Tools
    • Vision
    • Audio
    • Structured Outputs
    • Json Mode
  • Audio
    • Create Speech
    • Create Transcription
    • Create Translation
  • Images
    • Create Image
    • Edit Image
    • Create Image Variation
  • Files
    • List Files
    • Upload File
    • Delete File
    • Retrieve File
    • Download File Content
  • Fine Tuning
    • Create Fine Tune Job
    • List Fine Tune Jobs
    • Retrieve Fine Tune Job Info
    • Cancel Fine Tune Job
    • List Fine Tune Job Events
  • Batches
    • List Batches
    • Create Batch
    • Retrieve Batch
    • Cancel Batch
  • Embeddings
    • Create Embedding
  • Moderations
    • Create Moderation

Authentication

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

[!WARNING] We recommended using the environment variables to load the API key instead of having it hard coded in your source. It is not recommended use this method in production, but only for accepting user credentials, local testing and quick start scenarios.

  1. Pass keys directly with constructor :warning:
  2. Load key from configuration file
  3. Use System Environment Variables

Pass keys directly with constructor

[!WARNING] We recommended using the environment variables to load the API key instead of having it hard coded in your source. It is not recommended use this method in production, but only for accepting user credentials, local testing and quick start scenarios.

csharp
using var api = new OpenAIClient("sk-apiKey");

Or create a OpenAIAuthentication object manually

csharp
using var api = new OpenAIClient(new OpenAIAuthentication("sk-apiKey", "org-yourOrganizationId", "proj_yourProjectId"));

Load key from configuration file

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:

[!NOTE] Organization and project id entries are optional.

Json format
json
{
  "apiKey": "sk-aaaabbbbbccccddddd",
  "organizationId": "org-yourOrganizationId",
  "projectId": "proj_yourProjectId"
}
Deprecated format
bash
OPENAI_API_KEY=sk-aaaabbbbbccccddddd
OPENAI_ORGANIZATION_ID=org-yourOrganizationId
OPENAI_PROJECT_ID=proj_yourProjectId

You can also load the configuration file directly with known path by calling static methods in OpenAIAuthentication:

  • Loads the default .openai config in the specified directory:
csharp
using var api = new OpenAIClient(OpenAIAuthentication.LoadFromDirectory("path/to/your/directory"));
  • Loads the configuration file from a specific path. File does not need to be named .openai as long as it conforms to the json format:
csharp
using var api = new OpenAIClient(OpenAIAuthentication.LoadFromPath("path/to/your/file.json"));

Use System Environment Variables

Use your system's environment variables specify an api key and organization to use.

  • Use OPENAI_API_KEY for your api key.
  • Use OPENAI_ORGANIZATION_ID to specify an organization.
  • Use OPENAI_PROJECT_ID to specify a project.
csharp
using var api = new OpenAIClient(OpenAIAuthentication.LoadFromEnvironment());

Handling OpenAIClient and HttpClient Lifecycle

OpenAIClient implements IDisposable to manage the lifecycle of the resources it uses, including HttpClient. When you initialize OpenAIClient, it will create an internal HttpClient instance if one is not provided. This internal HttpClient is disposed of when OpenAIClient is disposed of. If you provide an external HttpClient instance to OpenAIClient, you are responsible for managing its disposal.

  • If OpenAIClient creates its own HttpClient, it will also take care of disposing it when you dispose OpenAIClient.
  • If an external HttpClient is passed to OpenAIClient, it will not be disposed of by OpenAIClient. You must manage the disposal of the HttpClient yourself.

Please ensure to appropriately dispose of OpenAIClient to release resources timely and to prevent any potential memory or resource leaks in your application.

Typical usage with an internal HttpClient:

csharp
using var api = new OpenAIClient();

Custom HttpClient (which you must dispose of yourself):

csharp
using var customHttpClient = new HttpClient();
// set custom http client properties here
var api = new OpenAIClient(client: customHttpClient);

Azure OpenAI

You can also choose to use Microsoft's Azure OpenAI deployments as well.

You can find the required information in the Azure Playground by clicking the View Code button and view a URL like this:

markdown
https://{your-resource-name}.openai.azure.com/openai/deployments/{deployment-id}/chat/completions?api-version={api-version}
  • your-resource-name The name of your Azure OpenAI Resource.
  • deployment-id The deployment name you chose when you deployed the model.
  • api-version The API version to use for this operation. This follows the YYYY-MM-DD format.

To setup the client to use your deployment, you'll need to pass in OpenAISettings into the client constructor.

csharp
var auth = new OpenAIAuthentication("sk-apiKey");
var settings = new OpenAISettings(resourceName: "your-resource-name", deploymentId: "deployment-id", apiVersion: "api-version");
using var api = new OpenAIClient(auth, settings);

Azure Active Directory Authentication

Authenticate with MSAL as usual and get access token, then use the access token when creating your OpenAIAuthentication. Then be sure to set useAzureActiveDirectory to true when creating your OpenAISettings.

Tutorial: Desktop app that calls web APIs: Acquire a token

csharp
// get

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#aiapi-proxychat-gptchatgpt

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.