Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    AI/LLM Integration in .NET: back to the course
    Lesson1 / 14

    The .NET AI Stack in 2026: Microsoft.Extensions.AI, Agent Framework and IChatClient

    Trace a conversation that forgets

    A support bot hears a customer’s name. Later the customer asks it to repeat the name in the same conversation and in a fresh call.

    • Predict. Write down which message roles each request sends. Identify who owns the history.
    • Test locally. Keep the support types and program in separate files. Compare the history and fresh-call cases, then inspect Calls, Usage and ModelId.

    Your route through this course

    Use local fakes to test client middleware, streaming, validation, tools, retrieval and recovery. Prompt Engineering for .NET Developers covers how to write prompts for your developer workflow.

    For each lab, record what you predicted, what you observed and one claim the fake cannot establish.

    Check the decision

    Predict which messages each call sends. The decision question follows the complete local program.

    Trace and explain

    RequestMessage roles you expect to sendHistory the response can use
    First turnFill inFill in
    Follow-up in the same conversationFill inFill in
    Fresh callFill inFill in

    Name who owns memory and explain what changes if a provider stores conversation state.

    Reference and worked examples

    Intuition

    IChatClient lets an API depend on a shared chat contract and choose a provider adapter at startup. When switching providers, check supported content, tools, structured output, options, limits and errors.

    Layers of a .NET AI application

    Each arrow shows a dependency. Check which capabilities your chosen provider offers.

    • The app or worker can use IChatClient directly. Microsoft.Extensions.AI supplies middleware, and adapters connect supported providers or a fake to the interface.
    • Agent Framework uses the shared contracts for agents, sessions and workflows.
    • VectorData provides a separate retrieval-storage abstraction when the design needs one.

    Deep dive

    • Microsoft.Extensions.AI (M.E.AI):
      • Microsoft.Extensions.AI.Abstractions defines IChatClient, IEmbeddingGenerator<TInput,TEmbedding>, ChatMessage, ChatOptions and the content types (text, function call/result, usage, data).
      • Microsoft.Extensions.AI adds the middleware: function invocation, caching, logging and OpenTelemetry.
      • Providers ship adapters, for example AsIChatClient() on an OpenAI or Azure OpenAI chat client.
      • The examples pin version 10.10.0.
    • Microsoft Agent Framework (Microsoft.Agents.AI) reached 1.0 in April 2026. It is the successor to Semantic Kernel and AutoGen, built by the same teams, and it adds agents, sessions, multi-agent orchestration and MCP/A2A interop on top of IChatClient. Lesson 9 covers it; this course uses 1.24.
    • Semantic Kernel v1.x is still supported (critical and security fixes, for at least one year after Agent Framework GA). Keep existing SK apps running; evaluate Agent Framework for new agent work, checking the required connector/features and migration cost. The VectorData connector ecosystem includes connectors maintained with Semantic Kernel; it is one route to supported stores, not a requirement that every RAG application use SK or a vector database (Lesson 7).
    • Choosing a layer:
      • A single prompt, classification, extraction or summarization: IChatClient.
      • One common vector-search RAG setup: IChatClient, plus IEmbeddingGenerator, plus a vector store.
      • Multi-turn assistants with tools, persisted state or several cooperating agents: Agent Framework.
    • Conversation state: with a stateless client such as this fake, your code resends the selected history. Some implementations keep server-side state: if they return a non-null ConversationId, carry the latest value into subsequent ChatOptions and send only new messages under that provider contract, rather than duplicating stored history. IDs can change between responses; authorize/isolate them per user or tenant and plan retention. History still contributes to model context and provider-dependent input charges (Lesson 11).
    • What comes back: ChatResponse holds:
      • Messages, with assistant and tool messages;
      • Text, a convenience concatenation across response messages, not a guarantee that it is only the final user-facing answer; inspect message roles/content when tools are involved;
      • optional FinishReason (for example stop, length, tool_calls, content_filter), which can be absent or provider-specific;
      • optional Usage (input/output and potentially other accounting fields);
      • optional ModelId, plus response/conversation identifiers where supplied;
      • provider metadata.

    Capture available usage/finish/model diagnostics without logging secrets or unrestricted prompt/tool content. Metadata may be missing; use the response ModelId for the actual response when supplied, not just a configured default. A length finish indicates a token-limit stop and potentially incomplete output; validate before use, especially structured output or actions.

    The fake model used in this course

    • Set up the project. Use the .NET 10 SDK and a console project with implicit usings. Add Microsoft.Extensions.AI version 10.10.0 and a compatible Microsoft.Extensions.DependencyInjection package. Restore the NuGet packages before running offline.
    • Separate the files. Put the first block in FakeAI.cs and the second in Program.cs. Run the project on your machine. The scripted chat client and hashing embedding generator require no provider URL or API key.
    • Interpret the run. Fake token counts are estimates. The fake builds its complete reply before emitting word-sized updates. It ignores most options, including MaxOutputTokens and provider safety settings. The FAQ script can echo temperature without enforcing it. Use this fixture to test library plumbing.
    • Own request data. Give each request its own mutable messages and options. Shared scripts must support concurrent calls. The hashing generator is lexical, collision-prone and focused on English ASCII text. Fully filtered input yields a zero vector, for which cosine similarity is undefined.
    C#
    // FAKE, DETERMINISTIC AI SERVICES FOR TEACHING. No model, no network, no API key.
    // FakeChatClient implements the real Microsoft.Extensions.AI IChatClient interface, but its "intelligence" is a
    // script you pass in. HashingEmbeddingGenerator implements the real IEmbeddingGenerator interface with a
    // bag-of-words hashing trick, so similar wording gives similar vectors. Swap either for a real provider
    // (Azure OpenAI, OpenAI, Ollama, ...) behind the same abstraction; verify provider capability/option differences.
    using System.Runtime.CompilerServices;
    using System.Text.RegularExpressions;
    using Microsoft.Extensions.AI;
    
    namespace FakeAI;
    
    public delegate ChatMessage Script(IReadOnlyList<ChatMessage> messages, ChatOptions? options);
    
    public sealed class FakeChatClient(Script script, string modelId = "fake-model-1") : IChatClient
    {
        private int _calls;
        public int Calls => Volatile.Read(ref _calls);
    
        public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken ct = default)
        {
            ct.ThrowIfCancellationRequested();
            Interlocked.Increment(ref _calls);
            var list = messages.ToList();
            var reply = script(list, options);
            bool toolCall = reply.Contents.OfType<FunctionCallContent>().Any();
            return Task.FromResult(new ChatResponse(reply)
            {
                ModelId = modelId,
                FinishReason = toolCall ? ChatFinishReason.ToolCalls : ChatFinishReason.Stop,
                Usage = new UsageDetails { InputTokenCount = Tokens.Estimate(list), OutputTokenCount = Tokens.Estimate([reply]), TotalTokenCount = Tokens.Estimate(list) + Tokens.Estimate([reply]) },
            });
        }
    
        public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken ct = default)
        {
            var response = await GetResponseAsync(messages, options, ct);
            var msg = response.Messages[^1];
            foreach (var c in msg.Contents.Where(c => c is not TextContent)) yield return new ChatResponseUpdate(msg.Role, [c]) { ModelId = modelId };
            foreach (Match w in Regex.Matches(msg.Text, @"\S+\s*"))      // artificial word chunks, not model tokens
            {
                ct.ThrowIfCancellationRequested();
                await Task.Yield();
                yield return new ChatResponseUpdate(msg.Role, w.Value) { ModelId = modelId };
            }
            yield return new ChatResponseUpdate { FinishReason = response.FinishReason, Contents = [new UsageContent(response.Usage!)], ModelId = modelId };
        }
    
        public object? GetService(Type serviceType, object? serviceKey = null)
        {
            ArgumentNullException.ThrowIfNull(serviceType);
            if (serviceKey is not null) return null; // this fake exposes only unkeyed services
            return serviceType == typeof(ChatClientMetadata) ? new ChatClientMetadata("fake", null, modelId) :
                serviceType.IsInstanceOfType(this) ? this : null;
        }
        public void Dispose() { }
    }
    
    public static class Tokens
    {
        /// <summary>FAKE token estimate: about 4 characters per token, the usual English rule of thumb. Real counts come from the provider's Usage.</summary>
        public static int Estimate(IEnumerable<ChatMessage> messages) => messages.Sum(m => (m.Text.Length + 3) / 4 + 4);
        public static int Estimate(string text) => (text.Length + 3) / 4;
    }
    
    public sealed class HashingEmbeddingGenerator(int dimensions = 256) : IEmbeddingGenerator<string, Embedding<float>>
    {
        private readonly int _dimensions = dimensions > 0 ? dimensions : throw new ArgumentOutOfRangeException(nameof(dimensions));
        public Task<GeneratedEmbeddings<Embedding<float>>> GenerateAsync(IEnumerable<string> values, EmbeddingGenerationOptions? options = null, CancellationToken ct = default)
        {
            ArgumentNullException.ThrowIfNull(values);
            ct.ThrowIfCancellationRequested();
            var result = new GeneratedEmbeddings<Embedding<float>>(values.Select(v =>
            {
                ct.ThrowIfCancellationRequested();
                return new Embedding<float>(Embed(v, ct)) { ModelId = "fake-hashing-embeddings" };
            }));
            return Task.FromResult(result);
        }
        float[] Embed(string text, CancellationToken ct)
        {
            ArgumentNullException.ThrowIfNull(text);
            var v = new float[_dimensions];
            foreach (var word in Words(text))
            {
                ct.ThrowIfCancellationRequested();
                v[(int)(Fnv(word) % (uint)_dimensions)] += 1f; // stable lexical hash, not semantic understanding
            }
            var norm = MathF.Sqrt(v.Sum(x => x * x));
            if (norm > 0) for (int i = 0; i < v.Length; i++) v[i] /= norm;                    // unit length: cosine = dot product
            return v;
        }
        public static IEnumerable<string> Words(string text) =>
            Regex.Matches(text.ToLowerInvariant(), "[a-z0-9]+").Select(m => m.Value).Where(w => w.Length > 2 && !Stop.Contains(w)).Select(Stem);
        static string Stem(string w) => w.Length > 4 && w.EndsWith('s') ? w[..^1] : w;
        static readonly HashSet<string> Stop = ["the", "and", "for", "are", "with", "that", "this", "you", "can", "how", "what", "does", "from", "your", "not", "but", "has", "have", "into", "when", "which", "its", "our", "use", "was", "will"];
        static uint Fnv(string s) { uint h = 2166136261; foreach (char c in s) h = unchecked((h ^ c) * 16777619); return h; }
        public object? GetService(Type serviceType, object? serviceKey = null)
        {
            ArgumentNullException.ThrowIfNull(serviceType);
            if (serviceKey is not null) return null;
            return serviceType == typeof(EmbeddingGeneratorMetadata) ? new EmbeddingGeneratorMetadata("fake", null, "fake-hashing-embeddings", _dimensions) :
                serviceType.IsInstanceOfType(this) ? this : null;
        }
        public void Dispose() { }
    }

    Code example: IChatClient through DI, history, options

    C#
    // IChatClient basics with a FAKE, scripted client (no model, no key). The calling code is what you would
    // write against a compatible provider adapter; revalidate behavior when changing providers.
    using FakeAI;
    using Microsoft.Extensions.AI;
    using Microsoft.Extensions.DependencyInjection;
    
    // The "model": a script that answers from a tiny FAQ and remembers the user's name from history.
    Script faq = (messages, options) =>
    {
        var last = messages[^1].Text.ToLowerInvariant();
        var name = messages.Where(m => m.Role == ChatRole.User).Select(m => m.Text)
                           .Select(t => t.StartsWith("I am ") ? t[5..].TrimEnd('.') : null).LastOrDefault(n => n is not null);
        string text = last.Contains("refund") ? "Refunds are issued to the original payment method within 5 business days."
                    : last.Contains("my name") ? (name is null ? "You have not told me your name." : $"Your name is {name}.")
                    : last.StartsWith("i am ") ? "Nice to meet you."
                    : "I can answer questions about refunds.";
        if (options?.Temperature is float t) text += $" (temperature {t})";
        return new ChatMessage(ChatRole.Assistant, text);
    };
    
    var services = new ServiceCollection();
    services.AddChatClient(new FakeChatClient(faq));          // real app: new AzureOpenAIClient(...).GetChatClient("deployment").AsIChatClient()
    using var sp = services.BuildServiceProvider();
    var chat = sp.GetRequiredService<IChatClient>();
    
    // 1. One call, and everything that comes back besides the text.
    ChatResponse r = await chat.GetResponseAsync("How long do refunds take?");
    Console.WriteLine($"text:          {r.Text}");
    Console.WriteLine($"model:         {r.ModelId}");
    Console.WriteLine($"finish reason: {r.FinishReason}");
    Console.WriteLine($"usage:         in={r.Usage?.InputTokenCount} out={r.Usage?.OutputTokenCount} total={r.Usage?.TotalTokenCount} (fake estimate)");
    Console.WriteLine($"metadata:      provider={chat.GetService<ChatClientMetadata>()?.ProviderName} defaultModel={chat.GetService<ChatClientMetadata>()?.DefaultModelId}");
    
    // 2. The client is stateless: conversation memory is the list of messages YOU send each time.
    List<ChatMessage> history = [new(ChatRole.System, "You are a support assistant for Contoso. Answer briefly.")];
    foreach (var user in new[] { "I am Priya.", "What is my name?" })
    {
        history.Add(new(ChatRole.User, user));
        var reply = await chat.GetResponseAsync(history);
        history.AddMessages(reply);                               // append the assistant message(s) to the history
        Console.WriteLine($"user: {user,-18} assistant: {reply.Text}   [messages sent: {history.Count - 1}, input tokens ~{reply.Usage?.InputTokenCount}]");
    }
    var fresh = await chat.GetResponseAsync("What is my name?");
    Console.WriteLine($"new conversation, same question: {fresh.Text}");
    
    // 3. ChatOptions travel with each request.
    var opt = await chat.GetResponseAsync("Tell me about refunds", new ChatOptions { Temperature = 0.2f, MaxOutputTokens = 200 });
    Console.WriteLine($"with options: {opt.Text}");
    Console.WriteLine($"history roles: {string.Join(", ", history.Select(m => m.Role.Value))}");

    What causes this fake to remember Priya?

    A The model retained secret server state.
    B The application resends the selected messages.
    C The DI lifetime guarantees every provider remembers.
    D The fake’s token estimate stores the user profile.
    Show answer

    Correct answer: B

    The script searches the messages it receives. Provider-managed state is a separate contract with ownership and retention requirements.

    Option A: The fake finds Priya in the messages passed to this call; hidden provider memory is not exercised.

    Option C: A DI lifetime controls application object ownership, not the conversation-memory contract of every provider.

    Option D: The token estimate is a calculation over text, not a write to a user-profile store.

    Hint: Follow the exact request list.

    Output (.NET 10, Microsoft.Extensions.AI 10.10.0, FAKE model)

    Check which calls receive the earlier messages. Compare response ModelId with configured metadata. Temperature formatting follows the current culture. The sample refund policy is fictional.

    Code walkthrough

    • Choose an implementation in DI. AddChatClient registers the fake behind IChatClient. A real provider adapter needs capability and integration checks.
    • Manage history. AddMessages appends reply messages to the caller’s history. Compare the roles you pass on the follow-up and fresh call.
    • Check options and diagnostics. The fake echoes temperature without sampling at that setting or enforcing the output cap. GetService<ChatClientMetadata>() reports configured metadata. Use response ModelId when present. Usage may be absent, and fake estimates cannot establish real cost.

    Failure modes

    • Writing directly against one provider SDK everywhere, so switching models or adding caching or telemetry means touching every call site.
    • Assuming the model remembers: a bot that forgets the user's name, or one that resends an unbounded history and gets slower and more expensive every turn.
    • Ignoring a token-limit finish or assuming stop proves correctness/completeness. Check provider/model context and output limits and validate the result; a missing finish reason is not automatically success.
    • Starting new agent projects on Semantic Kernel's agent APIs without checking the current status. The successor (Agent Framework 1.x) is GA.
    • Committing API keys to configuration or logs. Prefer managed identity where supported with appropriate authorization; user-secrets is development convenience, not an encrypted production secret store. Use an appropriate production secret manager when keys are required.

    Interview angle

    Scenario: you are adding a summarizer to an ASP.NET Core API.

    • Inject IChatClient and choose the provider, authorization and supported capabilities in startup configuration.
    • Add middleware to match the feature. Consider Agent Framework when the work needs agent sessions or workflow coordination.
    • Use the fake for application tests. Use separate, budgeted provider tests for model and provider behavior.

    Practice questions

    1. What does IChatClient give you that a provider SDK does not?

    Answer: A provider-neutral abstraction with a shared middleware ecosystem (function calling, caching, telemetry). Compatible adapters reduce call-site changes, while capabilities/semantics still require checks. Fakes help test plumbing, not actual provider/model behavior.

    1. Where does conversation memory live?

    Answer: For a stateless client, in the messages your code resends (possibly managed by an agent session). Stateful providers can retain it server-side and use ChatResponse.ConversationId / ChatOptions.ConversationId.

    1. Semantic Kernel or Agent Framework for a new agent project in 2026?

    Answer: Agent Framework, the GA successor. SK v1.x stays supported for existing apps for at least a year after Agent Framework GA.

    1. A response has FinishReason = length. What happened?

    Answer: Generation stopped at a token limit; output may be incomplete. Check supported output/context budgets and validate the result. A shorter request, larger supported budget or deliberate continuation can help; continuation is another operation and is not a guarantee of complete valid output.

    Practice

    Practice test: AI Engineering for .NET: Cheat Sheet Practice6 questions · 1 mark each, no negative marking
    Take the test
    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 24 Nov 2026 ·