Using the OpenAI API in C#: Chat Completions and Responses API



Last updated: October 28th, 2026

Updated October 2026: the original version of this post used the legacy Completions API and the text-davinci-003 model, both of which OpenAI has retired. It now uses the official OpenAI .NET library (2.x) with the Chat Completions and Responses APIs. Every sample compiles against OpenAI 2.14 on .NET 8 and .NET 10.

Quick Answer

  1. Create an API key at platform.openai.com/api-keys and store it in the OPENAI_API_KEY environment variable.
  2. Install the official package: dotnet add package OpenAI
  3. Create a ChatClient with a model name and call CompleteChatAsync:
using OpenAI.Chat;

// dotnet add package OpenAI
string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
    ?? throw new InvalidOperationException("Set the OPENAI_API_KEY environment variable.");

ChatClient client = new(model: "gpt-5-mini", apiKey: apiKey);

ChatCompletion completion = await client.CompleteChatAsync(
    new SystemChatMessage("You are a concise assistant for .NET developers."),
    new UserChatMessage("Explain what IHttpClientFactory solves in two sentences."));

Console.WriteLine(completion.Content[0].Text);
Console.WriteLine($"Tokens: {completion.Usage.InputTokenCount} in / {completion.Usage.OutputTokenCount} out");

Chat Completions vs. the Responses API

  • Chat Completions (/v1/chat/completions, ChatClient): you send the whole list of messages (system, user, assistant) on every call. It is simple, stable and widely supported, including by many OpenAI-compatible providers.
  • Responses API (/v1/responses, ResponsesClient): OpenAI's newer, recommended API. It can keep conversation state on the server (previous_response_id), has built-in tools such as web search and file search, and is where new features appear first.
  • Legacy Completions (/v1/completions, models like text-davinci-003): retired. If your code still calls it, migrate to one of the two above.

Pick a current model from OpenAI's models page. The examples use gpt-5-mini, a low-cost model suited to high-volume tasks; keep the model name in configuration so you can change it without redeploying.

Chat Completions in C#

Conversation history and output limits

The API is stateless: to continue a conversation, add the assistant's reply and the next user message to the list and send it all again. MaxOutputTokenCount caps the reply length (and cost).

using OpenAI.Chat;

string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ChatClient client = new(model: "gpt-5-mini", apiKey: apiKey);

// Keep the whole conversation in a list and send it every time.
List<ChatMessage> messages =
[
    new SystemChatMessage("You write short, factual answers."),
    new UserChatMessage("What is the default port for SQL Server?")
];

ChatCompletionOptions options = new()
{
    MaxOutputTokenCount = 300 // caps the reply length (and your cost)
};

ChatCompletion first = await client.CompleteChatAsync(messages, options);
Console.WriteLine(first.Content[0].Text);

// Add the assistant's reply, then ask a follow-up question.
messages.Add(new AssistantChatMessage(first));
messages.Add(new UserChatMessage("And for SQL Server Browser?"));

ChatCompletion second = await client.CompleteChatAsync(messages, options);
Console.WriteLine(second.Content[0].Text);

Streaming the reply

Streaming prints text as it is generated, which feels much faster in chat UIs:

using OpenAI.Chat;

string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ChatClient client = new(model: "gpt-5-mini", apiKey: apiKey);

await foreach (StreamingChatCompletionUpdate update in
    client.CompleteChatStreamingAsync("Write a haiku about garbage collection."))
{
    if (update.ContentUpdate.Count > 0)
    {
        Console.Write(update.ContentUpdate[0].Text);
    }
}
Console.WriteLine();

The Responses API in C#

In the .NET library the Responses client is still marked [Experimental], so you must suppress the OPENAI001 diagnostic to use it. GetOutputText() collects the text from the response, and previousResponseId continues a conversation without resending the history:

#pragma warning disable OPENAI001 // The Responses client is marked [Experimental] in the .NET SDK
using OpenAI.Responses;

string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(apiKey);

CreateResponseOptions options = new()
{
    Model = "gpt-5-mini",
    Instructions = "You are a concise assistant for .NET developers.",
    MaxOutputTokenCount = 500
};
options.InputItems.Add(ResponseItem.CreateUserMessageItem(
    "Give me three tips for faster EF Core queries."));

ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());

// Continue the conversation without resending history:
ResponseResult followUp = await client.CreateResponseAsync(
    "gpt-5-mini",
    "Show a code example for the second tip.",
    previousResponseId: response.Id);
Console.WriteLine(followUp.GetOutputText());

Calling the API With Plain HttpClient

You don't need any package. This is handy for scripts, unusual platforms, or seeing exactly what the API returns:

using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

// No SDK: call the Responses API directly with HttpClient.
string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

using var http = new HttpClient { BaseAddress = new Uri("https://api.openai.com/v1/") };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

var request = new
{
    model = "gpt-5-mini",
    instructions = "Answer in one sentence.",
    input = "What does the C# 'required' keyword do?"
};

using HttpResponseMessage httpResponse = await http.PostAsJsonAsync("responses", request);
string body = await httpResponse.Content.ReadAsStringAsync();

if (!httpResponse.IsSuccessStatusCode)
{
    throw new HttpRequestException($"OpenAI returned {(int)httpResponse.StatusCode}: {body}");
}

// The text lives in output[] -> items of type "message" -> content[] -> type "output_text".
using JsonDocument doc = JsonDocument.Parse(body);
foreach (JsonElement item in doc.RootElement.GetProperty("output").EnumerateArray())
{
    if (item.GetProperty("type").GetString() != "message") continue;

    foreach (JsonElement part in item.GetProperty("content").EnumerateArray())
    {
        if (part.GetProperty("type").GetString() == "output_text")
        {
            Console.WriteLine(part.GetProperty("text").GetString());
        }
    }
}

Using OpenAI in ASP.NET Core

The SDK clients are thread-safe, so register one as a singleton and inject it. Store the key with dotnet user-secrets in development and an environment variable (for example OpenAI__ApiKey) in production:

// Program.cs (ASP.NET Core): register one ChatClient for the whole app.
// The SDK clients are thread-safe, so a singleton is the right lifetime.
using OpenAI.Chat;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton(_ => new ChatClient(
    model: builder.Configuration["OpenAI:Model"] ?? "gpt-5-mini",
    apiKey: builder.Configuration["OpenAI:ApiKey"]
        ?? throw new InvalidOperationException("OpenAI:ApiKey is not configured.")));

var app = builder.Build();

app.MapPost("/ask", async (AskRequest request, ChatClient chat) =>
{
    ChatCompletion completion = await chat.CompleteChatAsync(request.Question);
    return Results.Ok(new { answer = completion.Content[0].Text });
});

app.Run();

record AskRequest(string Question);

The library retries 408, 429 and 5xx errors automatically (three times, with exponential backoff). If you still hit rate limits, slow down or queue the work.

Building Applications on the API

The power of working directly with the API comes when you automate tasks. You can choose a model per task, check every response in code, and retry when a result is too long, too short or contains something you don't want. Cheaper models at higher volume are often better than an expensive model used once.

There are limits to how much you can send and receive in one request, so break big jobs into small, well-defined steps. For example, to rewrite every meta description on a website, process the pages one at a time in a background job and save each result to your database, rather than pasting them into a chat window by hand.

Prompt Engineering

Prompt engineering means giving the model clear instructions, and ideally an example of the output you want, so it produces consistent results. An example I've used is generating URL keys: given a phrase like "how to fix your bike if its tires are flat", return "fix-bike-flat-tires". With one or two examples in the instructions, the model reliably produces SEO-friendly keys for any phrase.

Example: A Loop That Writes Meta Descriptions

This loop reads the instructions from a text file (so you can tune the prompt without recompiling), asks for a meta description for each article title, and retries when the result is too long:

using OpenAI.Chat;

string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ChatClient client = new(model: "gpt-5-mini", apiKey: apiKey);

// Instructions live in a text file so you can tune them without recompiling.
string instructions = await File.ReadAllTextAsync("meta-description-prompt.txt");
string[] titles = await File.ReadAllLinesAsync("titles.txt");

const int MaxLength = 155;
const int MaxAttempts = 3;

foreach (string title in titles.Where(t => !string.IsNullOrWhiteSpace(t)))
{
    string? metaDescription = null;

    for (int attempt = 1; attempt <= MaxAttempts && metaDescription is null; attempt++)
    {
        ChatCompletion completion = await client.CompleteChatAsync(
            new SystemChatMessage(instructions),
            new UserChatMessage($"Article title: {title}"));

        string candidate = completion.Content[0].Text.Trim().Trim('"');

        if (candidate.Length is > 0 and <= MaxLength)
        {
            metaDescription = candidate;
        }
    }

    Console.WriteLine(metaDescription is null
        ? $"SKIPPED (too long after {MaxAttempts} tries): {title}"
        : $"{title}\n  -> {metaDescription}");

    // Save metaDescription to your database here.
}

An instructions file might say: "Write one meta description for the article title you are given. 140 to 155 characters, plain text, no quotes, active voice, include the main keyword once, and end with a reason to click."

Frequently Asked Questions

Which NuGet package should I use for OpenAI in C#?

The official OpenAI package, maintained by OpenAI with Microsoft. It covers chat, responses, embeddings, images, audio and more. Microsoft.Extensions.AI builds on it if you want a provider-neutral abstraction.

Is the OpenAI Completions API deprecated?

Yes. The legacy /v1/completions endpoint and its models (such as text-davinci-003) were retired. Use Chat Completions or the Responses API instead.

How do I call the OpenAI Responses API from C#?

Create a ResponsesClient (namespace OpenAI.Responses) with your API key, add #pragma warning disable OPENAI001, and call CreateResponseAsync. Read the text with response.GetOutputText().

How do I keep my OpenAI API key safe in .NET?

Never commit it. Use dotnet user-secrets locally and environment variables or a secrets manager in production, and call the API only from your server, never from browser JavaScript.

Summary

For new C# code, install the official OpenAI package, use ChatClient for straightforward chat and ResponsesClient for the newer features, keep the model name and key in configuration, and treat each response as data your code checks before using.


Comments

No Comments

CAPTCHA

Tagged: AI, C Sharp, ChatGPT


Join my email list!



ryan
About Me

With over 15 years in tech, I've excelled as a senior software engineer, specializing in ASP.NET, C#, SQL, Azure, and front-end technologies. I've led diverse projects across various sectors, from startups to global corporations, particularly during my decade in the San Francisco Bay Area.


Sign Up Hostinger Email