Building an AI Feature in C#: Start with a Measurable Prediction

Editorial illustration.

Originally published 21 June 2023; rewritten and reviewed on 15 October 2026.

Every few months a client or stakeholder asks to “add AI” to an existing C# business application. Before touching a NuGet package or signing up for an API key, the most useful question you can ask is plain and unglamorous: what specific decision should the application make better, and how will we know if it actually got better?

“Add AI” is not a specification. Routing incoming customer support tickets into five departments, flagging suspiciously formatted invoice totals, and drafting a reply to a refund inquiry are completely different engineering problems with different latency budgets, privacy constraints, and failure costs.

Match the tool to the problem—not the hype

In a .NET codebase, you generally have three realistic paths:

  1. Deterministic rules: If you are routing tickets that literally contain "FPX" or "Invoice #" into a billing queue, a 15-line C# rule or lookup table is faster, free, and 100% predictable. Don’t pay per-token latency for something string.Contains or a regex handles reliably.
  2. In-process ML with ML.NET: When you have structured historical records—say, thousands of past support tickets with their final category labels, or tabular sales/churn data—ML.NET lets you train and run a model directly inside your ASP.NET Core process without managing a separate Python microservice.
  3. External LLM APIs: When the task involves unstructured text generation, summarisation, or extracting fields from messy documents where you don’t have a large labelled dataset, calling an LLM endpoint (for example via Microsoft.Extensions.AI or HttpClient against an OpenAI-compatible API) makes sense.

The libraries mentioned in older 2023 tutorials change quickly, so treat any package recommendation as a starting point and check whether it is actively maintained on NuGet before locking it into a production service.

Keep evaluation separate from training and prompts

Whether you train a local ML.NET classifier or tune a system prompt for an LLM, never judge quality by testing on the same examples you used to build it. Set aside a held-out evaluation set of real, anonymised cases—making sure you are actually authorised to use that customer data—and measure against a simple baseline.

More importantly, look at the cost of mistakes, not just overall accuracy. If a classifier is 92% accurate overall, that sounds great on a slide. But if the 8% it misroutes are urgent payment-failure complaints getting dumped into a low-priority general inbox, the feature is hurting your operations rather than helping. Inspect the confusion matrix or failure log by hand.

Wrap the model behind a strict C# boundary

Treat model output the same way you treat untrusted third-party webhook data: validate everything before it touches your database or triggers an email. Give the AI component a typed contract, a strict timeout, and a deterministic fallback.

public sealed record TicketRoutingDecision(string Department, double Confidence, string ModelVersion);

public async Task<TicketRoutingDecision> RouteAsync(string subject, string body, CancellationToken ct)
{
    using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
    timeoutCts.CancelAfter(TimeSpan.FromSeconds(3));

    try
    {
        var decision = await _classifierClient.ClassifyAsync(subject, body, timeoutCts.Token);
        if (!AllowedDepartments.Contains(decision.Department) || decision.Confidence < 0.70)
        {
            return new TicketRoutingDecision("GeneralTriage", decision.Confidence, decision.ModelVersion);
        }

        return decision;
    }
    catch (OperationCanceledException)
    {
        // Timeout or caller cancellation: fall back cleanly instead of blocking ticket creation
        return new TicketRoutingDecision("GeneralTriage", 0.0, "fallback-timeout");
    }
}

Notice three small details that save headaches in production:

  • An allowlist check (AllowedDepartments.Contains): Models occasionally invent categories or return formatting variations.
  • A confidence threshold: Uncertain predictions go straight to human triage instead of silently landing in the wrong queue.
  • A ModelVersion field: When you log decisions, recording which model or prompt version produced them lets you trace why behaviour shifted after an update.

Start with a small, measurable slice—one workflow, a clear fallback, and a handful of real test cases you can re-run after every change. That turns “adding AI” from a fragile demo into normal, maintainable software engineering.