This repository contains a minimal .NET 9 console app that integrates the official OpenAI .NET SDK to run a chat session with:
- Streaming output (tokens print as they arrive — no waiting for full responses)
- Persistent conversation history (system, user, and assistant turns)
The sample targets C# 13 and .NET 9.
- Uses the
OpenAINuGet package (v2.6.x) and theChatClientAPI - Streams assistant responses via
CompleteChatStreamingAsync(...) - Preserves full conversation context by appending
UserChatMessageandAssistantChatMessageobjects - Exits the loop on a blank user input
- .NET 9 SDK installed
- An OpenAI API key with access to the selected chat model
- Network access to the OpenAI API
-
Clone/download this repo and open the solution.
-
Restore and build (Visual Studio or CLI):
dotnet restore
dotnet build -c Release
- Set the
OPENAI_API_KEYenvironment variable:
- Windows (PowerShell):
$env:OPENAI_API_KEY = "<your-api-key>"
- macOS/Linux (bash/zsh):
export OPENAI_API_KEY="<your-api-key>"
- Run:
dotnet run --project OpenAI.Chat.SDK.csproj
You should see a prompt:
Type your message and press Enter. Submit a blank line to exit.
You:
Type a message and watch the assistant reply stream in real time. Submit a blank line to exit.
The core logic lives in Program.cs:
- Create a client using an API key:
var client = new OpenAIClient(new ApiKeyCredential(apiKey));
- Choose a chat model and get a chat client:
var chat = client.GetChatClient("gpt-4o-mini");
- Maintain a
List<ChatMessage>for history:- Start with a
SystemChatMessageto set the assistant behavior. - Append each
UserChatMessageandAssistantChatMessageafter every turn.
- Start with a
- Stream responses:
await foreach (var update in chat.CompleteChatStreamingAsync(messages.ToArray())) { ... }- Print
Textparts as they arrive and accumulate them into a buffer for history.
Update the line in Program.cs to a model you have access to:
var chat = client.GetChatClient("gpt-4o-mini");
See the OpenAI model catalog for available models and pricing.
If you prefer to wait for the complete response (not used in this sample), the SDK supports a non‑streaming call:
var result = await chat.CompleteChatAsync(messages.ToArray());
var completion = result.Value; // ChatCompletion
var text = string.Join("\n",
Enumerable.Range(0, completion.Content.Count)
.Select(i => completion.Content[i].Text)
.Where(t => !string.IsNullOrEmpty(t)));
- OPENAI_API_KEY not set: The app exits with an error message; set the environment variable and try again.
- 401/403 errors: Verify the API key and model access.
- Networking issues: Ensure outbound HTTPS access to the OpenAI API.
- Quotas/limits: Check your account usage and limits.
- Do not commit secrets (API keys) to source control.
- Prefer user or machine‑level environment variables, or managed secret stores.
- .NET 9
- C# 13
OpenAINuGet package (2.6.x)
- Restore:
dotnet restore - Build:
dotnet build - Run:
dotnet run --project OpenAI.Chat.SDK.csproj