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

.NET Playground

Learn the current .NET AI package ecosystem, then compare configured providers through .NET SDKs and IChatClient—not browser-side provider requests.

.NET LLM with NuGet packages: a practical guide

This guide covers the .NET package ecosystem and application patterns for integrating large language models. It deliberately starts with .NET libraries and provider SDKs rather than browser-side API calls.

An SDK still sends a network request. A NuGet package does not run a hosted model locally: provider SDKs send authenticated requests to the provider's service, then deserialize responses. The difference in this playground is that .NET SDKs make those requests from the server; the browser does not call provider endpoints directly. For local inference, use a local runtime such as Ollama with OllamaSharp.

1. The .NET AI package ecosystem

Think in layers. Pick the narrowest layer that meets the application's needs and add orchestration only when required.

Microsoft Agent Framework      Agents, sessions, workflows, multi-agent orchestration
Semantic Kernel                Plugins, filters, memory, connectors; useful in existing apps
Microsoft.Extensions.AI        IChatClient, IEmbeddingGenerator, middleware and DI
Microsoft.Extensions.VectorData Vector-store abstractions
Provider SDKs and adapters     OpenAI, Azure OpenAI, Anthropic, Google, Ollama and others
NuGet package Role When to choose it
Microsoft.Extensions.AI and its abstractions Common IChatClient and IEmbeddingGenerator interfaces, function invocation, caching, telemetry and composable middleware. Recommended starting point for application code that should not depend on one provider.
Microsoft.Extensions.AI.OpenAI Adapts the OpenAI .NET SDK to IChatClient and embedding abstractions. OpenAI and providers offering a compatible endpoint.
OpenAI Official OpenAI .NET SDK. OpenAI-specific models, API features, and compatible endpoints.
Azure.AI.OpenAI Azure OpenAI client, Azure credentials, deployments and Azure service configuration. Azure-hosted deployments and Microsoft Entra ID authentication.
Anthropic Official Claude C# SDK; the current SDK also adapts to IChatClient. Claude-specific models and capabilities. Version 10 and later is the official SDK; the older community package is now tryAGI.Anthropic.
Google.GenAI Google's official Gemini SDK; includes an IChatClient implementation. Gemini Developer API or Gemini Enterprise Agent Platform.
Azure.AI.Inference Azure AI Inference clients for supported Foundry/GitHub Models endpoints. When using those Azure-hosted endpoints; check current service and model support.
Mscc.GenerativeAI.Microsoft Community integration for Gemini with Microsoft.Extensions.AI. An alternative to evaluate when an official SDK adapter does not meet a requirement.
OllamaSharp Connects .NET applications to a local Ollama runtime and supports .NET AI abstractions. Local models, private experiments, and offline development.
Microsoft.SemanticKernel Kernel, plugins, filters, prompt orchestration, memory and provider connectors. Existing Semantic Kernel applications or when its specific connector features are needed.
Microsoft.Agents.AI Agent Framework for agents, sessions, workflows and multi-agent orchestration. Tool-using agents and explicit multi-step workflows. Check the current package status and API.
ModelContextProtocol Official C# Model Context Protocol client/server SDK. Connecting an application to MCP tools or exposing tools to MCP clients.
Microsoft.Extensions.VectorData.Abstractions Typed vector-store interfaces and record/search abstractions. A common vector-store boundary for RAG.
Microsoft.SemanticKernel.Connectors.* Provider connectors such as Microsoft.SemanticKernel.Connectors.InMemory, Qdrant, PostgreSQL/pgvector, Azure AI Search, Redis, SQLite, MongoDB and more. Select the connector for the vector database you operate; check its current version and package name.
Microsoft.Extensions.DataIngestion Document ingestion and chunking pipeline. Evaluate the current release status before adopting it in production.
Betalgo.Ranul.OpenAI, LangChain.NET, LLMTornado Community .NET libraries and alternatives. Evaluate maintenance, feature coverage, licensing and release cadence before adopting.
Aspire integrations such as OpenAI or Ollama hosting integrations Configuration, service orchestration and developer experience in .NET Aspire. Optional local-development and deployment orchestration.

AutoGen and Semantic Kernel agent work are converging toward the Microsoft Agent Framework. For a new provider-neutral application, start with Microsoft.Extensions.AI, add provider adapters, and add Agent Framework when an agent or workflow is actually needed. Keep Semantic Kernel where its existing plugins, filters or connectors already solve a problem.

Recommended combinations

  • Chat and provider portability: Microsoft.Extensions.AI plus the official provider SDK/adapter.
  • Agents: Microsoft.Agents.AI on top of a chat client.
  • RAG: Microsoft.Extensions.VectorData plus a store connector such as Qdrant, PostgreSQL/pgvector or Azure AI Search.
  • External tools: ModelContextProtocol when MCP interoperability is useful; otherwise expose narrow, application-owned functions.
  • Local inference: Ollama plus OllamaSharp. The local runtime still must be installed, started and supplied with a model.

There is no NuGet package that makes every provider, model, feature, token counter, price or data policy interchangeable. IChatClient standardizes useful application-level operations; providers and models still differ in their supported features and limits.

2. Microsoft.Extensions.AI step by step

Install the abstraction and the provider packages

The versions below were checked against NuGet on October 31, 2026. Pin and update packages deliberately; keep related Microsoft.Extensions.AI packages on compatible release versions.

dotnet add package Microsoft.Extensions.AI --version 10.11.0
dotnet add package Microsoft.Extensions.AI.OpenAI --version 10.11.0
dotnet add package OpenAI --version 2.14.0
dotnet add package Azure.AI.OpenAI --version 2.1.0
dotnet add package Anthropic --version 13.3.0
dotnet add package Google.GenAI --version 1.28.0
dotnet add package OllamaSharp --version 5.5.0

The playground in this application uses the first six packages. OllamaSharp is listed as the local-runtime alternative. Versions for Agent Framework, MCP, VectorData and store connectors evolve independently; verify them on NuGet before adding them.

A small OpenAI chat client

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

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

IChatClient chat = new OpenAIClient(new ApiKeyCredential(key))
    .GetChatClient("gpt-6.1-sol")
    .AsIChatClient();

ChatResponse response = await chat.GetResponseAsync(
    "Say hello in Czech.",
    cancellationToken);

Console.WriteLine(response.Text);
Console.WriteLine(
    $"Input/output tokens: {response.Usage?.InputTokenCount}/{response.Usage?.OutputTokenCount}");

Use configuration, environment variables, user secrets for local development, or a production secret manager. Do not commit keys to source control. The provider client belongs on the trusted server, not in a public browser bundle.

One application interface, different provider adapters

The same application-facing interface can be backed by different SDKs:

using Anthropic;
using Google.GenAI;
using Microsoft.Extensions.AI;
using OpenAI;
using System.ClientModel;

IChatClient chat = provider switch
{
    "openai" => new OpenAIClient(new ApiKeyCredential(apiKey))
        .GetChatClient(model).AsIChatClient(),
    "anthropic" => new AnthropicClient { ApiKey = apiKey }
        .AsIChatClient(model),
    "gemini" => new Google.GenAI.Client(apiKey: apiKey)
        .AsIChatClient(model),
    _ => throw new ArgumentOutOfRangeException(nameof(provider))
};

The OpenAI SDK can also be configured with a custom endpoint for an OpenAI-compatible provider. Azure OpenAI has its own client and deployment configuration. An adapter does not guarantee feature parity: model IDs, structured-output schemas, tool formats, system-message rules and token accounting can still be provider-specific. Use the provider's SDK directly or own a narrow adapter when a needed feature is not represented by the common surface.

For example, DeepSeek can be reached through its OpenAI-compatible endpoint, while Azure OpenAI uses an Azure resource and a deployment name:

IChatClient deepSeek = new OpenAIClient(
        new ApiKeyCredential(deepSeekKey),
        new OpenAIClientOptions { Endpoint = new Uri("https://api.deepseek.com") })
    .GetChatClient("deepseek-chat")
    .AsIChatClient();

IChatClient azure = new AzureOpenAIClient(
        new Uri("https://my-resource.openai.azure.com"),
        new AzureKeyCredential(azureKey))
    .GetChatClient("my-deployment-name")
    .AsIChatClient();

For local Ollama inference, start the Ollama runtime and pull the selected model first:

IChatClient local = new OllamaSharp.OllamaApiClient(
    new Uri("http://localhost:11434"),
    "llama3.2");

Chat options, streaming and token usage

var options = new ChatOptions
{
    Temperature = 0.2f,
    MaxOutputTokens = 800,
    ModelId = "gpt-6.1-sol"
};

ChatResponse answer = await chat.GetResponseAsync(
    "Summarize RAG in three bullets.",
    options,
    cancellationToken);

Console.WriteLine(answer.Text);
Console.WriteLine($"Input: {answer.Usage?.InputTokenCount}");
Console.WriteLine($"Output: {answer.Usage?.OutputTokenCount}");
Console.WriteLine($"Total: {answer.Usage?.TotalTokenCount}");

await foreach (var update in chat.GetStreamingResponseAsync(
    "Tell me a short story about a coin.",
    cancellationToken: cancellationToken))
{
    Console.Write(update.Text);
}

Usage fields can be absent, provider-specific, or reported differently. Treat a missing count as unavailable rather than zero. Reasoning tokens may be a breakdown of output tokens; cached-token accounting also varies. Compare the provider's reported totals and billing information rather than adding every detailed field together.

3. Application patterns

3.1 Chat and bounded conversation history

An LLM call is stateless unless the selected API explicitly provides server-side conversation state. In an application-owned conversation, send the history with each request and persist it using an application-controlled store such as a database, EF Core, Redis or Cosmos DB.

var history = new List<ChatMessage>
{
    new(ChatRole.System, "You are a concise coin-collecting expert.")
};

history.Add(new ChatMessage(ChatRole.User, userInput));
ChatResponse reply = await chat.GetResponseAsync(history, cancellationToken: cancellationToken);
history.AddRange(reply.Messages);

Bound the history to the model's context and application budget. One simple policy keeps the system message and the most recent messages:

static List<ChatMessage> KeepRecent(
    IEnumerable<ChatMessage> history,
    int keepLast = 20)
{
    var messages = history.ToList();
    var systemMessages = messages.Where(m => m.Role == ChatRole.System).ToList();
    var conversation = messages.Where(m => m.Role != ChatRole.System)
        .TakeLast(keepLast)
        .ToList();
    return [.. systemMessages, .. conversation];
}

For longer conversations, summarize old turns and retain the summary plus recent messages. Do not trim away required tool-call/result pairs or other structured content. The Agent Framework offers thread/session abstractions, but the application still owns retention, access control and privacy decisions.

3.2 Structured output

Use typed output when the application needs data, then validate business rules after deserialization. Provider support for JSON schema and schema dialects differs.

using System.ComponentModel;

public sealed record CoinInfo(
    [property: Description("Official coin name")] string Name,
    [property: Description("gold, silver, platinum or palladium")] string Metal,
    [property: Description("Fineness, for example 0.999")] double Fineness,
    [property: Description("Weight in grams")] double WeightGrams);

var result = await chat.GetResponseAsync<CoinInfo>(
    "Extract: Silver Czech Lion coin, 1 oz, fineness 999/1000.");

CoinInfo coin = result.Result;
if (coin.WeightGrams <= 0 || coin.Fineness is <= 0 or > 1)
{
    throw new InvalidOperationException("The generated coin data failed domain validation.");
}

Do not treat schema-conforming output as trusted or factually correct. Validate required fields, ranges, permissions and domain invariants.

3.3 Tools and function calling

Tools are application functions exposed to a model. Keep them narrow, deterministic and authorized independently of model output. Add function-invocation middleware to execute supported tool calls:

using Microsoft.Extensions.AI;
using System.ComponentModel;

[Description("Returns the current spot price of a precious metal in USD per troy ounce.")]
static decimal GetSpotPrice(
    [Description("gold, silver, platinum or palladium")] string metal) =>
    metal.ToLowerInvariant() switch
    {
        "gold" => 2650m,
        "silver" => 31.5m,
        "platinum" => 980m,
        "palladium" => 1020m,
        _ => throw new ArgumentException("Unknown metal.")
    };

[Description("Converts troy ounces to grams.")]
static double OuncesToGrams(double ounces) => ounces * 31.1034768;

IChatClient toolChat = chat.AsBuilder()
    .UseFunctionInvocation()
    .Build();

var options = new ChatOptions
{
    Tools =
    [
        AIFunctionFactory.Create(GetSpotPrice),
        AIFunctionFactory.Create(OuncesToGrams)
    ]
};

ChatResponse response = await toolChat.GetResponseAsync(
    "Convert five troy ounces to grams and give the current spot-price estimate for one ounce of gold.",
    options,
    cancellationToken);

Tool invocation is not an authorization boundary. Require human approval for destructive or consequential actions, use an allowlist, validate arguments, apply least privilege and make operations auditable. Never give a model unrestricted access to shell commands, databases, files or accounts.

For approval-required operations, wrap the function in the approval API supported by the installed .NET AI version. Return the approval request to the user, and only send an approval response after an explicit decision. Do not treat the model's request to call a function as user consent.

3.4 Memory

Memory describes different needs; it is not one feature:

Kind Meaning Typical implementation
Short-term Current conversation context. A bounded List<ChatMessage> or an agent thread.
Compacted Older history no longer fits the context budget. Trimming or a generated summary with recent turns retained.
Long-term Facts that should be available across conversations. An authorized database/vector store and explicit Remember/Recall tools.

Long-term memory needs user scoping, retention rules, access checks and a way to inspect or forget stored facts. Do not store sensitive data without a valid purpose and user consent.

A memory tool can keep persistence behind a small application abstraction:

public interface IMemoryStore
{
    Task AddAsync(string userId, string fact);
    Task<IReadOnlyList<string>> SearchAsync(string userId, string query, int top);
}

public sealed class MemoryTools(IMemoryStore store, string userId)
{
    [Description("Stores one durable, non-sensitive fact the user explicitly wants remembered.")]
    public async Task<string> Remember(
        [Description("One short fact to save")] string fact)
    {
        await store.AddAsync(userId, fact);
        return "Saved.";
    }

    [Description("Searches this user's saved facts for information relevant to a question.")]
    public async Task<string> Recall(
        [Description("What to search for")] string query)
    {
        var matches = await store.SearchAsync(userId, query, top: 5);
        return string.Join("\n", matches);
    }
}

Conversation history and durable facts are separate data. Store a conversation as JSON only when the application has a defined retention and access policy; provide a way to delete it.

3.5 Skills

“Skill” is a design pattern, not one .NET package. It can be:

  1. A group of tools (a class of [Description] methods; Semantic Kernel calls these plugins).
  2. A reusable prompt/instruction for a particular task.
  3. An on-demand SKILL.md directory containing instructions and scripts. Progressive disclosure keeps the full text out of the system prompt until it is needed.

An application can give the model a short skill index and expose a LoadSkill(name) function. Validate skill names against an allowlist and restrict file access to the configured skill root; never concatenate an unchecked model-supplied path.

For example, keep only the skill name, description and approved file path in a registry:

public sealed class SkillRegistry
{
    private readonly Dictionary<string, (string Description, string Path)> _skills =
        new(StringComparer.OrdinalIgnoreCase);

    public SkillRegistry(string root)
    {
        var fullRoot = Path.GetFullPath(root);
        foreach (var directory in Directory.GetDirectories(fullRoot))
        {
            var file = Path.GetFullPath(Path.Combine(directory, "SKILL.md"));
            if (file.StartsWith(fullRoot + Path.DirectorySeparatorChar, StringComparison.Ordinal)
                && File.Exists(file))
            {
                _skills[Path.GetFileName(directory)] = ("On-demand skill instructions.", file);
            }
        }
    }

    public string BuildIndex() =>
        "Available skills:\n" +
        string.Join("\n", _skills.Select(skill => $"- {skill.Key}: {skill.Value.Description}"));

    [Description("Loads the full instructions for a skill in the approved skill index.")]
    public string LoadSkill([Description("Skill name from the index")] string name) =>
        _skills.TryGetValue(name, out var skill)
            ? File.ReadAllText(skill.Path)
            : throw new ArgumentException("Unknown skill.");
}

The short index can be included in the system message; the model loads the full instructions only when needed. This reduces prompt context, but loaded instructions are still untrusted input and must not grant permissions by themselves.

3.6 MCP (Model Context Protocol)

MCP standardizes connections to external tools and resources such as files, databases, GitHub or Figma. Install the official C# SDK with:

dotnet add package ModelContextProtocol

An MCP client can list server tools and pass them to an IChatClient as functions. An MCP server can expose application-owned methods using [McpServerToolType] and [McpServerTool]. Treat an MCP server as a privileged integration: authenticate it, restrict available tools and validate each operation. The SDK's transport and APIs can evolve, so follow the versioned official examples.

The shape of a client integration is:

await using var server = await McpClient.CreateAsync(
    new StdioClientTransport(new()
    {
        Name = "approved-files",
        Command = "your-configured-mcp-server",
        Arguments = ["--read-only", "/approved/data"]
    }));

IList<McpClientTool> tools = await server.ListToolsAsync();
var options = new ChatOptions { Tools = [.. tools] };
ChatResponse response = await toolChat.GetResponseAsync(
    "List the approved data files.",
    options,
    cancellationToken);

For a server, annotate a static tool type/method and register it with the configured transport. Publish only tools the caller is allowed to use; a filesystem or database MCP server should not be granted broader permissions than the application itself.

3.7 Agents

An agent combines a model, instructions, tools, optional memory and a control loop in which the model can decide what to do next. UseFunctionInvocation() handles supported function calls for an IChatClient; Agent Framework adds sessions, middleware, observability and workflow orchestration.

dotnet add package Microsoft.Agents.AI

Agent Framework APIs have evolved across releases. Check the current package examples for agent creation, sessions/threads and workflow APIs. A minimal application-owned agent loop still needs an explicit hard step limit, output-token budget, cancellation and authorization checks. Multi-agent orchestration adds latency and multiplies cost; prefer one agent with well-scoped tools unless a workflow genuinely benefits from specialists.

Conceptually, a bounded loop keeps all turns in the request, checks for a final answer and stops after a fixed maximum. The IChatClient passed to this example must already have function invocation configured when it is expected to execute tools:

async Task<string> RunBoundedAgentAsync(
    IChatClient client,
    string task,
    ChatOptions options,
    int maximumTurns = 8,
    CancellationToken cancellationToken = default)
{
    var messages = new List<ChatMessage>
    {
        new(ChatRole.System, "Use only the supplied tools. Finish with FINAL: <answer>."),
        new(ChatRole.User, task)
    };

    for (var turn = 0; turn < maximumTurns; turn++)
    {
        ChatResponse response = await client.GetResponseAsync(messages, options, cancellationToken);
        messages.AddRange(response.Messages);
        var text = response.Text ?? string.Empty;
        var marker = text.IndexOf("FINAL:", StringComparison.Ordinal);
        if (marker >= 0)
        {
            return text[(marker + "FINAL:".Length)..].Trim();
        }

        messages.Add(new ChatMessage(ChatRole.User, "Continue or return a final answer."));
    }

    return "Stopped because the configured step limit was reached.";
}

The IChatClient itself does not decide application permissions. Put authorization in tool implementations and enforce output-token and execution limits for every turn.

Common multi-agent patterns are:

  • Sequential: a pipeline passes each stage's result to the next.
  • Concurrent: independent agents run in parallel and a reviewer combines their output.
  • Handoff: the current agent transfers control to a specialist.
  • Group chat: agents discuss while a moderator controls turns.
  • Agent as a tool: an orchestrator invokes specialist agents as functions.

An inexpensive fan-out/fan-in design can also call one provider concurrently with different instructions, then ask a final reviewer to synthesize the outputs:

async Task<string> AskAsync(IChatClient client, string instructions, string question) =>
    (await client.GetResponseAsync(
        [
            new(ChatRole.System, instructions),
            new(ChatRole.User, question)
        ])).Text;

var question = "Is now a good time to buy gold? Give a balanced analysis.";
var bullish = AskAsync(chat, "Argue the bullish case in at most five bullets.", question);
var bearish = AskAsync(chat, "Argue the bearish case in at most five bullets.", question);
await Task.WhenAll(bullish, bearish);

var verdict = await AskAsync(
    chat,
    "You are a neutral reviewer. Compare both views and avoid personalized financial advice.",
    $"BULL:\n{bullish.Result}\n\nBEAR:\n{bearish.Result}");

Agent Framework workflow APIs can express sequential, concurrent, handoff and group-chat patterns. Treat preview APIs as version-sensitive; set a maximum number of steps/turns and token budgets, and account for the added cost and latency.

3.8 RAG and vector databases

Retrieval-augmented generation (RAG) is a data pipeline:

  1. Load and parse trusted documents.
  2. Split them into chunks while preserving useful context and metadata.
  3. Generate embeddings with one model.
  4. Upsert chunks and vectors into a vector store.
  5. Embed each question and retrieve the top-K relevant records.
  6. Put selected evidence into the model request and ask for grounded answers with citations.

Microsoft.Extensions.VectorData provides typed abstractions; it does not host a database or generate embeddings by itself. A vector record typically has a key, source/text metadata and an embedding whose dimensions and distance function must match the embedding model and index.

Store Typical fit
InMemory Development and tests; data disappears when the process stops.
SQLite with a vector extension Small local or desktop applications.
PostgreSQL with pgvector Keep vectors alongside relational data; good fit when PostgreSQL is already operated.
SQL Server 2025 / Azure SQL Microsoft stack and existing SQL operations.
Qdrant Dedicated self-hosted or cloud vector database with filtering.
Azure AI Search Managed Azure search with vector and full-text/hybrid retrieval.
Redis, MongoDB or Cosmos DB Add vector search when the application already operates the service.
Pinecone, Weaviate or Chroma Managed or alternative vector-store deployments.

Use chunk sizes around 300–1,000 tokens as an initial experiment, with overlap; preserve headings, source, page and access metadata. Hybrid vector-plus-keyword search and reranking can improve retrieval. Keep the embedding model identical for indexing and querying; changing models or dimensions requires a deliberate index migration. Always include citations, allow “I don't know” when evidence is absent, and evaluate retrieval separately from answer generation.

A provider-neutral implementation follows this shape (the concrete collection and search API depends on the selected vector-store connector):

IEmbeddingGenerator<string, Embedding<float>> embedder =
    new OpenAIClient(new ApiKeyCredential(apiKey))
        .GetEmbeddingClient("text-embedding-3-small")
        .AsIEmbeddingGenerator();
var chunks = ChunkDocument(sourceText, targetTokens: 700, overlapTokens: 100);
var vectors = await embedder.GenerateAsync(chunks, cancellationToken);

for (var index = 0; index < chunks.Count; index++)
{
    await collection.UpsertAsync(
        new DocumentChunk
        {
            Id = Guid.NewGuid(),
            Source = sourceName,
            Text = chunks[index],
            Embedding = vectors[index].Vector
        },
        cancellationToken);
}

var queryVector = await embedder.GenerateVectorAsync(question, cancellationToken);
var hits = await SearchTopAsync(collection, queryVector, top: 4, cancellationToken);
var context = string.Join(
    "\n\n",
    hits.Select((hit, index) => $"[{index + 1}] ({hit.Source})\n{hit.Text}"));

var answer = await chat.GetResponseAsync(
    [
        new(ChatRole.System,
            "Answer only from the supplied context, cite sources as [1], and say when evidence is missing."),
        new(ChatRole.User, $"Context:\n{context}\n\nQuestion: {question}")
    ],
    cancellationToken: cancellationToken);

ChunkDocument, SearchTopAsync and the collection are application/connector-specific examples, not built-in methods. An OpenAI embedding adapter, for example, can expose IEmbeddingGenerator<string, Embedding<float>>; Qdrant, pgvector and Azure AI Search each use their own configured collection implementation. InMemory is useful in tests but does not persist data. A Qdrant connector changes the store implementation, not the need to keep the embedding model, dimensions, metadata and access filters consistent.

RAG can also be exposed as an agent tool that searches a knowledge base on demand. Restrict results to the caller's authorized scope before they reach the model; citations are useful only when their source records are accessible and traceable.

RAG content is untrusted data, not instructions. Apply tenant and authorization filters before retrieval, keep citations traceable to source records, and test against questions with known expected sources and answers. Agentic RAG exposes retrieval as a tool when the model should decide whether a search is needed; it still needs authorization and tool-use limits.

3.9 Middleware, observability and budgets

ChatClientBuilder can compose cross-cutting features around a provider client. Depending on the provider and package versions, use middleware such as function invocation, distributed caching, OpenTelemetry and logging:

IChatClient pipeline = chat.AsBuilder()
    .UseFunctionInvocation()
    .UseOpenTelemetry(sourceName: "AiLab")
    .Build();

Add a local budget policy or request wrapper to establish a maximum output-token value and record reported usage. Do not log API keys or whole prompts containing personal information; configure telemetry to avoid sensitive content. Caching can reduce repeated work but must respect user identity, authorization, privacy and freshness.

An application-owned wrapper can apply a default token cap and log only reported usage:

public sealed class BudgetChatClient(
    IChatClient inner,
    ILogger<BudgetChatClient> logger) : DelegatingChatClient(inner)
{
    public override async Task<ChatResponse> GetResponseAsync(
        IEnumerable<ChatMessage> messages,
        ChatOptions? options = null,
        CancellationToken cancellationToken = default)
    {
        options ??= new ChatOptions();
        options.MaxOutputTokens ??= 1000;

        ChatResponse response = await base.GetResponseAsync(
            messages,
            options,
            cancellationToken);
        logger.LogInformation(
            "LLM usage input={InputTokens} output={OutputTokens}",
            response.Usage?.InputTokenCount,
            response.Usage?.OutputTokenCount);
        return response;
    }
}

Middleware and logging APIs can change with package versions; do not capture prompt text or credentials in traces by default.

3.10 Reliability and safety checklist

Concern Practical control
Prompt injection Treat retrieved/web/file content as data, separate it from instructions and restrict tool permissions.
Dangerous tools Approval for consequential actions, allowlists, least privilege and auditable results.
Cost Cap output tokens, input size, agent steps, request concurrency and provider spend; add rate limits.
Privacy Minimize transmitted personal data; assess legal basis, provider retention and region; consider a local model.
Retries Exponential backoff for retryable 429/5xx/network failures (for example Polly or Microsoft.Extensions.Http.Resilience); avoid retrying non-idempotent tools blindly.
Timeouts Pass cancellation tokens and set timeouts; cancel work when the user disconnects.
Logs Keep credentials and sensitive prompt/response content out of logs and telemetry.
Hallucinations Ground with citations, validate structured output, verify important facts and allow “I don't know.”
Testing Use a fake/recording IChatClient for application tests and a separate evaluation set for provider/model behavior.

4. Production checklist

  • Keep API keys out of source control; use user secrets locally and a secret manager or managed/workload identity in production.
  • Scan repository history and builds for accidentally committed credentials; configure provider spend limits and alerts.
  • Have a browser call an authenticated application backend, not a hosted LLM directly, when the application owns the credential.
  • Authenticate and rate-limit the backend, validate input size, and enforce user-level access policies.
  • Keep application code on IChatClient where it is useful; select the concrete adapter through trusted server configuration.
  • Set output-token, step, concurrency and spend limits.
  • Require approval and server-side authorization for consequential tools.
  • Return RAG citations and support an evidence-based “I don't know.”
  • Avoid logging keys or sensitive prompts; use telemetry with sensitive-data collection disabled.
  • Verify package versions, model IDs, provider support and current pricing/lifecycle before deployment.
  • Use an evaluation set and regression checks; consider Microsoft.Extensions.AI evaluation libraries where supported rather than assuming a model upgrade preserves answer quality.

5. Official resources

LIVE COMPARISON · SERVER-SIDE .NET SDKs

Compare the same chat across providers

Each ready provider receives the same user message through its NuGet-backed .NET adapter. Replies and conversation history remain separate per provider for this Blazor circuit.

Understand where your credentials go

Provider keys remain in this browser's saved AI Agent settings until you send a message. On send, this Interactive Server page transfers the keys for ready providers to the Blazor server over its circuit; provider NuGet SDKs then make HTTPS requests from the server. Keys are not written to server storage or included in results. Use this prototype only with a server you trust; production apps should authenticate users and retrieve provider keys from a server-side secret manager.

Configured providers

Keys are never displayed. Readiness checks only whether one is present and the endpoint is supported.

Loading browser settings…

This is a manual comparison: every ready provider is called regardless of its Enabled flag or routing weight. A weight is a relative routing share, not a quality score, token discount or multiplier. Azure uses the API version selected by its .NET SDK; the legacy API version field in browser settings is not applied here. Cohere is routed through its official OpenAI-compatibility endpoint.

Chat prompt

The same message is sent to every ready provider, with each provider's own prior turns.

The first message matches the API Playground prompt. Date-sensitive answers receive no live search data.
Requests run up to 4 provider calls at a time; each request uses the configured timeout and a maximum 4,096 output tokens.

Provider answers

Answers are returned by the configured .NET SDK adapters.

Send a message to compare provider answers.

Run results and token usage

Token values are shown only when the provider SDK reports them.

Results will appear after the first message.

This playground does not capture raw SDK request/response payloads. Missing usage is displayed as an em dash; do not interpret an unavailable token count as zero. Provider tokenization and billing can differ.

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.