48 CZ-PRG (GMT+1)
US-NYC (GMT-5)
Blazor Web App (Server rendered)
AI AGENTS · CONVERSATIONAL UX

Chat Assistants

Build assistants that hold useful conversations—not just isolated prompts. This guide explains the .NET package choices, the chat request lifecycle, production patterns, and how to connect a .NET application to OpenAI, Azure OpenAI, Anthropic, or Google Gemini.

AT A GLANCE

What makes an assistant conversational?

  • Multi-turn context with explicit history
  • System instructions and generation options
  • Provider choice behind a .NET abstraction
  • Controlled context, privacy, and cost
CONCEPTS

A chat assistant is an application pattern

A language model does not remember previous requests by itself. A chat application creates the experience of a continuing conversation by sending the relevant prior messages with each new turn. The application also decides which instructions to include, what context to retrieve, and how much history to retain.

Typical request lifecycle

  1. Authenticate the user and load only their authorized conversation state.
  2. Compose system instructions, a bounded slice of history, and the new user message.
  3. Call a provider SDK through IChatClient, optionally streaming updates.
  4. Validate and persist the assistant response, usage, and conversation metadata.
  5. Apply retention, redaction, and deletion policies to stored messages.
.NET AND NUGET

Choose the right package boundary

Keep provider-specific setup at the edge of your application and use a common interface in application code when it fits. IChatClient makes common chat operations and middleware composable; it does not make every provider's tools, options, model behavior, or billing identical.

NuGet package What it provides Use it when
Microsoft.Extensions.AI Shared IChatClient and message/options types, plus composable middleware such as function invocation, caching, and telemetry. You want application services to depend on a provider-neutral chat contract.
Microsoft.Extensions.AI.OpenAI Adapters between the OpenAI .NET SDK and Microsoft.Extensions.AI interfaces. You use OpenAI or a compatible endpoint and want to work through IChatClient.
OpenAI Official .NET clients for OpenAI APIs, including chat and Responses API capabilities. You need OpenAI-specific API features or a direct SDK client.
Azure.AI.OpenAI Azure OpenAI client construction and Azure credential support; the chat client can be adapted to IChatClient. Your model is deployed in Azure and your application uses an Azure resource and deployment name.
Anthropic Official Claude C# SDK with an IChatClient adapter. You need Claude models or Anthropic-specific request features.
Google.GenAI Google's official Gemini .NET SDK, including an IChatClient implementation. You use Gemini; select the correct authentication and service for Gemini Developer API or Vertex AI.
Microsoft.SemanticKernel Higher-level orchestration, prompt functions, connectors, and plugin composition. Your application needs framework-level orchestration beyond a direct chat call. Verify connector support for the exact provider feature you need.

This application currently references Microsoft.Extensions.AI 10.11.0, Microsoft.Extensions.AI.OpenAI 10.11.0, OpenAI 2.14.0, Azure.AI.OpenAI 2.1.0, Anthropic 13.3.0, and Google.GenAI 1.28.0. Keep related abstraction and adapter packages on compatible versions and verify the current provider feature matrix before upgrading.

CORE PATTERN

Use IChatClient for a provider-neutral chat call

The following example creates an OpenAI-backed client once at the application's composition root. The same application service can receive a different adapter in tests or when a provider is changed. Store the API key in user-secrets during local development or a managed secret store in production; never put it in a browser bundle or commit it to source control.

using Microsoft.Extensions.AI;
using OpenAI;
using System.ClientModel;

string apiKey = configuration["OpenAI:ApiKey"]
    ?? throw new InvalidOperationException("OpenAI:ApiKey is not configured.");
string model = configuration["OpenAI:Model"]
    ?? throw new InvalidOperationException("OpenAI:Model is not configured.");

builder.Services.AddSingleton<IChatClient>(_ =>
    new OpenAIClient(new ApiKeyCredential(apiKey))
        .GetChatClient(model)
        .AsIChatClient());

A provider adapter translates the common request to a provider's API. Configure one client per trusted application configuration, then inject it into a chat service. Avoid constructing a client inside every UI render or accepting an arbitrary endpoint from an untrusted request.

using Microsoft.Extensions.AI;

public sealed class AssistantService(IChatClient chatClient)
{
    public async Task<string> ReplyAsync(
        string question,
        CancellationToken cancellationToken)
    {
        var messages = new[]
        {
            new ChatMessage(ChatRole.System,
                "You are a concise support assistant. Do not invent account details."),
            new ChatMessage(ChatRole.User, question)
        };

        ChatResponse response = await chatClient.GetResponseAsync(
            messages,
            new ChatOptions { MaxOutputTokens = 800 },
            cancellationToken);

        return response.Text;
    }
}
MULTI-TURN CHAT

Send bounded history on every turn

Each request needs the relevant prior turns. Keep conversation state scoped to the authenticated user and conversation—not in a singleton mutable list shared across requests. Store durable history in a database when users need to resume later; keep only a bounded window in the prompt to control latency and token cost. For long conversations, summarize older turns or retrieve only relevant history.

using Microsoft.Extensions.AI;

// Load only messages the current user is authorized to see.
List<ChatMessage> history = await conversationStore.LoadRecentAsync(
    userId, conversationId, cancellationToken);

var messages = new List<ChatMessage>
{
    new(ChatRole.System, instructions)
};
messages.AddRange(history.TakeLast(12));
messages.Add(new ChatMessage(ChatRole.User, userMessage));

ChatResponse response = await chatClient.GetResponseAsync(
    messages,
    new ChatOptions
    {
        MaxOutputTokens = 1200,
        Temperature = 0.3f
    },
    cancellationToken);

await conversationStore.AppendAsync(
    userId,
    conversationId,
    userMessage,
    response.Text,
    cancellationToken);
History is context, not memory. The model can only use what the application sends. Apply authorization before loading messages, set a retention policy, and treat retrieved or user-provided text as untrusted input.
PROVIDER ADAPTERS

Connect different providers without rewriting chat logic

Provider-specific client construction belongs in dependency injection or another composition root. The examples below use the official or first-party adapters already referenced by this application. Use managed identity or a secret manager in production, and keep endpoint selection under trusted configuration.

Use a custom endpoint only when the application owner has explicitly approved that provider and host.

using Microsoft.Extensions.AI;
using OpenAI;
using System.ClientModel;

var options = new OpenAIClientOptions
{
    Endpoint = new Uri("https://api.openai.com/v1")
};
IChatClient chat = new OpenAIClient(
        new ApiKeyCredential(apiKey), options)
    .GetChatClient(model)
    .AsIChatClient();

Azure uses a resource endpoint and a deployment name. Prefer Microsoft Entra ID where supported instead of a long-lived API key.

using Azure;
using Azure.AI.OpenAI;
using Microsoft.Extensions.AI;

var endpoint = new Uri(configuration["AzureOpenAI:Endpoint"]
    ?? throw new InvalidOperationException("Azure endpoint is missing."));
var credential = new AzureKeyCredential(
    configuration["AzureOpenAI:ApiKey"]
    ?? throw new InvalidOperationException("Azure API key is missing."));
string deployment = configuration["AzureOpenAI:Deployment"]
    ?? throw new InvalidOperationException("Azure deployment is missing.");

IChatClient chat = new AzureOpenAIClient(endpoint, credential)
    .GetChatClient(deployment)
    .AsIChatClient();

using Anthropic;
using Microsoft.Extensions.AI;

IChatClient chat = new AnthropicClient
{
    ApiKey = apiKey
}.AsIChatClient(model);

Use the authentication flow for the selected Gemini service; a Gemini Developer API key is not interchangeable with Vertex AI credentials.

using Microsoft.Extensions.AI;

IChatClient chat = new Google.GenAI.Client(apiKey: apiKey)
    .AsIChatClient(model);

For a broader package and model comparison, see the .NET NuGet playground and the .NET LLM guide.

PRODUCTION CHECKLIST

Make the experience dependable

Reliability

Pass cancellation tokens, set request timeouts, handle provider rate limits, and retry only transient failures with bounded backoff. Log request IDs and timing, not secrets or full private prompts.

Cost and context

Limit input history and output tokens, track provider-reported usage, and set per-user quotas. Token usage and feature support can differ by provider and model.

Safety and privacy

Do not treat model output as trusted HTML or authoritative policy. Minimize personal data, define retention and deletion behavior, and use authorization checks before adding retrieved or account-specific context.

Testing

Unit-test orchestration with a fake IChatClient. Separately evaluate representative prompts and use provider integration tests for credentials, streaming, limits, and model-specific behavior.

HANDS-ON · SERVER-SIDE .NET

Try a .NET chat assistant

Choose a configured provider, set the assistant instructions, and send a multi-turn conversation through its .NET SDK and IChatClient.

Where the API key goes

Keys remain in this browser's saved AI Agent settings. When you send a message, the selected provider's key is transferred over this Interactive Server circuit to the server, where its .NET SDK makes the HTTPS request. The key is not written to server storage or returned with the answer. Use this demo only with a server you trust; production applications should authenticate users and use a server-side secret manager.

Loading AI Agent settings…
An unhandled error has occurred. Reload 🗙

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please retry or reload the page.