The official .NET library for the OpenAI API
翻訳待ち
Loading the full README.
Read the full README ↗The OpenAI .NET library provides convenient access to the OpenAI REST API from .NET applications.
It is generated from our OpenAPI specification in collaboration with Microsoft.
To call the OpenAI REST API, you will need an API key. To obtain one, first create a new OpenAI account or log in. Next, navigate to the API key page and select "Create new secret key", optionally naming the key. Make sure to save your API key somewhere safe and do not share it with anyone.
Add the client library to your .NET project by installing the NuGet package via your IDE or by running the following command in the .NET CLI:
dotnet add package OpenAI
Note that the code examples included below were written using .NET 10. The OpenAI .NET library is compatible with all .NET Standard 2.0 applications, but the syntax used in some of the code examples in this document may depend on newer language features.
Some client APIs are marked with [Experimental] while their .NET design is still evolving. Using one produces a compiler error that you must explicitly suppress for its diagnostic ID. See Preview APIs for .NET guidance and Feature lifecycle for how OpenAI .NET APIs are introduced and promoted to stable.
The public API listings for this library can be found in the api/ folder (organized by target framework), and there are many code examples to help. For instance, the following snippet illustrates the basic use of the chat completions API:
ChatClient client = new(model: "gpt-5.1", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
ChatCompletion completion = client.CompleteChat("Say 'this is a test.'");
Console.WriteLine($"[ASSISTANT]: {completion.Content[0].Text}");
While you can pass your API key directly as a string, it is highly recommended that you keep it in a secure location and instead access it via an environment variable or configuration file as shown above to avoid storing it in source control.
If you need to connect to an alternative API endpoint (for example, a proxy or self-hosted OpenAI-compatible LLM), you can specify a custom base URL and API key using the ApiKeyCredential and OpenAIClientOptions:
ChatClient client = new(
model: "MODEL_NAME",
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("OPENAI_API_KEY")),
options: new OpenAIClientOptions()
{
Endpoint = new Uri("https://YOUR_BASE_URL")
});
Replace MODEL_NAME with your model name and BASE_URL with your endpoint URI. This is useful when working with OpenAI-compatible APIs or custom deployments.
The library is organized into namespaces by feature areas in the OpenAI REST API. Each namespace contains a corresponding client class.
This is the beginning of the README. Read the rest at the original. Read the full README ↗