27 November 2026

Microsoft.Extensions.AI for Beginners: Call C# Functions from AI with IChatClient

  Asp.Net CS By Example       27 November 2026

Every AI model provider used to require its own custom SDK, message classes, and tool-calling loop. With Microsoft.Extensions.AI in modern .NET, you write against one standard interface—IChatClient—and plug in OpenAI, Azure, or local models with minimal code changes. In this beginner guide, you will connect IChatClient to a C# helper method so an AI model can look up student exam rooms automatically.

How the pieces connect

User Prompt → ChatClientBuilder + UseFunctionInvocation() → AI Model Requests Tool → AIFunctionFactory C# Method

Why Use Microsoft.Extensions.AI?

  • Provider-agnostic code: Write your chat and tool logic against IChatClient so swapping models later takes one line.
  • Built-in middleware pipeline: Chain logging, caching, or automatic tool invocation via ChatClientBuilder, just like ASP.NET Core middleware.
  • Automatic schema generation: AIFunctionFactory.Create(...) turns regular C# methods and [Description] attributes into tool definitions.

1. Install the NuGet Packages

Create a console project and install Microsoft.Extensions.AI along with an AI provider adapter (such as Microsoft.Extensions.AI.OpenAI):

dotnet new console -n StudentAiHelper
cd StudentAiHelper
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Extensions.AI.OpenAI

2. Build an IChatClient Pipeline with Tool Calling

Set an environment variable named OPENAI_API_KEY, then update Program.cs with the code below:

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

string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
    ?? throw new InvalidOperationException("Set OPENAI_API_KEY first.");

IChatClient innerClient = new OpenAIClient(apiKey)
    .AsChatClient("gpt-4o-mini");

IChatClient client = new ChatClientBuilder(innerClient)
    .UseFunctionInvocation()
    .Build();

[Description("Gets the exam room and start time for a course code such as CS101.")]
static string GetExamSchedule(
    [Description("Course code, for example CS101 or SQL202")] string courseCode)
{
    return courseCode.ToUpperInvariant() switch
    {
        "CS101" => "Room B-204 at 9:30 AM",
        "SQL202" => "Lab C-108 at 2:00 PM",
        _ => "Course schedule not found"
    };
}

ChatOptions options = new()
{
    Tools = [AIFunctionFactory.Create(GetExamSchedule)]
};

var prompt = "Where and when is the CS101 exam?";
await foreach (var update in client.GetStreamingResponseAsync(prompt, options))
{
    Console.Write(update);
}
Console.WriteLine();

Understand the Important Parts

  1. ChatClientBuilder(innerClient).UseFunctionInvocation().Build() wraps the provider client with middleware that runs your C# method whenever the model requests a tool call.
  2. AIFunctionFactory.Create(GetExamSchedule) reads the method signature and [Description] attributes so the model knows what parameter to supply.
  3. GetStreamingResponseAsync(...) streams text tokens to the console as soon as they arrive.

Practice

  1. Add a second C# function named GetInstructorEmail(string courseCode) and register it in options.Tools.
  2. Register IChatClient inside an ASP.NET Core Minimal API using dependency injection (builder.Services.AddChatClient(...)) and expose a /ask endpoint.
  3. Add simple logging middleware inside ChatClientBuilder so every prompt and tool call prints to your terminal.

Continue learning: .NET Core and ASP.NET Core: Student Learning Path.

References: AI for .NET Developers (Microsoft Learn).

logoblog

Thanks for reading Microsoft.Extensions.AI for Beginners: Call C# Functions from AI with IChatClient

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.