Skip to content

iamhitya/openai-chat-dotnet-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 

Repository files navigation

.NET Console OpenAI Chat (SDK)

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.

Features

  • Uses the OpenAI NuGet package (v2.6.x) and the ChatClient API
  • Streams assistant responses via CompleteChatStreamingAsync(...)
  • Preserves full conversation context by appending UserChatMessage and AssistantChatMessage objects
  • Exits the loop on a blank user input

Prerequisites

  • .NET 9 SDK installed
  • An OpenAI API key with access to the selected chat model
  • Network access to the OpenAI API

Getting started

  1. Clone/download this repo and open the solution.

  2. Restore and build (Visual Studio or CLI):

dotnet restore
dotnet build -c Release
  1. Set the OPENAI_API_KEY environment variable:
  • Windows (PowerShell):
$env:OPENAI_API_KEY = "<your-api-key>"
  • macOS/Linux (bash/zsh):
export OPENAI_API_KEY="<your-api-key>"
  1. 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.

How it works

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 SystemChatMessage to set the assistant behavior.
    • Append each UserChatMessage and AssistantChatMessage after every turn.
  • Stream responses:
    • await foreach (var update in chat.CompleteChatStreamingAsync(messages.ToArray())) { ... }
    • Print Text parts as they arrive and accumulate them into a buffer for history.

Changing the model

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.

Non‑streaming example (reference)

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)));

Troubleshooting

  • 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.

Security notes

  • Do not commit secrets (API keys) to source control.
  • Prefer user or machine‑level environment variables, or managed secret stores.

Tech stack

  • .NET 9
  • C# 13
  • OpenAI NuGet package (2.6.x)

Scripts/commands summary

  • Restore: dotnet restore
  • Build: dotnet build
  • Run: dotnet run --project OpenAI.Chat.SDK.csproj

About

Sample console app to demonstrate how to integrate the OpenAI SDK into a .NET project.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages