AI Engineering

Building Reliable AI Agents with .NET 10: Boundaries, Tools and Evaluation

A demo agent can look impressive after a few successful prompts. A production agent has a harder job: it must behave predictably when tools fail, evidence conflicts, input is malicious or the model is uncertain.

The difference is not primarily the model. It is the engineering around it.

For .NET 10 applications, I prefer a deliberately small architecture with typed contracts, explicit authority boundaries and measurable failure behavior. The LLM is a reasoning component, not the owner of business invariants.

Start with the workflow, not the agent framework

Suppose an operations assistant investigates an HTTP error spike. It can retrieve metrics, inspect logs, search prior incidents and produce a report.

The workflow should make each responsibility visible:

TEXT
HTTP API / CLI
      |
      v
Request authentication + scope
      |
      v
Investigation orchestrator
      |
      +--> Tool registry / policy enforcement
      |       +--> Metrics adapter
      |       +--> Logs adapter
      |       +--> Incident knowledge adapter
      |
      +--> Model adapter
      |       +--> tool selection
      |       +--> hypothesis generation
      |
      +--> Validation and grounding
      |
      +--> Persisted report + telemetry

This is a modular architecture, not a requirement to deploy microservices. A modular monolith can provide clearer ownership and simpler debugging while the system is still evolving.

Give tools typed, bounded contracts

Avoid a generic Execute(string toolName, object args) interface as the only application-level abstraction. A transport-neutral tool registry is useful, but individual tools still need explicit request and response contracts.

A simplified C# example:

C#
public sealed record LogSearchRequest(
    string Service,
    DateTimeOffset From,
    DateTimeOffset To,
    int Limit);

public sealed record LogEntry(
    DateTimeOffset Timestamp,
    string Source,
    string Message);

public interface ILogSearchTool
{
    Task<IReadOnlyList<LogEntry>> SearchAsync(
        LogSearchRequest request,
        CancellationToken cancellationToken);
}

The interface alone does not enforce security. Before invoking the adapter, validate the service against the authenticated caller's allowed scope, enforce a maximum time window and cap the result size.

Keep tenant identity in trusted execution context rather than accepting it directly from model-generated arguments.

Use structured outputs, then validate semantics

JSON-shaped model output is easier to parse, but valid JSON is not necessarily a valid investigation.

A report might have the right fields while citing a log line that was never retrieved. Or it might claim a dependency failed when the only evidence is a historical ticket.

I separate three layers:

  1. Shape validation: required fields, enums and identifiers.
  2. Evidence validation: cited IDs exist in the evidence collected for this run.
  3. Claim validation: conclusions do not exceed what the evidence actually supports.

A model may propose a hypothesis. The application must decide whether its citations are valid and whether the output can be accepted, marked inconclusive or rejected.

Do not quietly repair unsupported claims into confident prose.

Bound the agent loop

An unconstrained tool loop is an operational risk. Put explicit limits around:

  • Tool calls and model turns per investigation.
  • Per-tool and overall time budgets.
  • Query ranges, result sizes and retry counts.
  • Token and monetary budgets where the provider exposes usage.
  • Which tools may be invoked after which validation steps.

Retries should be selective. Retrying a transient network failure may be reasonable; retrying an authorization denial is not. For operations with side effects, idempotency and approval rules must be designed before adding retries.

Cancellation should propagate through the entire request and into downstream calls. A disconnected client should not leave an unlimited investigation running in the background.

Make failures first-class results

A binary success/failure response often hides important distinctions.

For an investigation workflow, useful outcomes might be:

TEXT
Completed
Inconclusive
PartialEvidence
ToolUnavailable
Unauthorized
BudgetExceeded
Cancelled

These are application-level outcomes, not claims about built-in .NET framework enums. Define them according to your domain and return them consistently through API, CLI and UI layers.

An investigation with partial telemetry can still be useful, provided the report says exactly what was missing.

Keep evidence separate from generated interpretation

Persist the original evidence references and the model's interpretation separately.

A report should make it possible to answer:

  • Which metrics and logs were retrieved?
  • What time window was actually queried?
  • Which evidence supports each hypothesis?
  • Which prior incidents were used only as historical context?
  • Which model and prompt/configuration version produced the analysis?

Historical tickets are particularly easy to misuse. A similar previous incident is a lead, not proof of the current root cause.

This separation also makes later review possible without asking the model to reconstruct what happened.

Evaluate behavior, not just fluent answers

A good evaluation set contains normal cases and deliberate traps:

| Scenario | Expected behavior | | --- | --- | | Clear error spike with supporting logs | Grounded hypothesis with citations | | Metrics available, logs missing | Partial or inconclusive result | | Contradictory evidence | Explicit uncertainty | | Historical ticket resembles current symptoms | Contextual suggestion, not asserted cause | | Cross-tenant tool request | Denied before data access | | Prompt injection inside a log entry | Treated as data, not instruction | | Tool timeout | Bounded retry or graceful degradation | | Invented evidence ID | Rejected by citation validation |

Track more than a single answer-quality score. Measure citation validity, unsupported-claim rate, tool-call success, latency, budget consumption and regression across known scenarios.

Keep deterministic tests for policy and validation logic. Use model-based evaluations as additional signals, not as replacements for executable invariants.

Observe the whole request

For each investigation, record a correlation ID and spans for orchestration, model calls, tool calls, validation and persistence.

Useful operational signals include:

  • End-to-end latency and per-tool latency.
  • Tool failures, timeouts and denial counts.
  • Model input/output token usage where available.
  • Validation failures and inconclusive outcomes.
  • Cost estimates, with explicit treatment of missing provider usage data.

Avoid logging full prompts, raw incident payloads or secrets by default. Telemetry should support debugging without becoming a data-leak channel.

Keep the model replaceable

An agent should not depend on one vendor's message format throughout the domain layer.

Put provider-specific tool-call and response mapping in an adapter. Keep business contracts, validation and authorization independent of whether the model is local or hosted.

That does not mean all models are interchangeable. Different providers vary in tool-call reliability, context handling, structured-output guarantees and latency. Run the same evaluation suite when changing model or configuration.

Vendor neutrality is an architectural option, not a promise of identical behavior.

The production rule

A reliable AI agent does not need to be autonomous at every step. It needs to be accountable for every step.

Let the model choose plausible next questions and synthesize evidence. Let deterministic code enforce identity, scope, budgets, contracts and citations. Make uncertainty visible and preserve enough traceability to review the result.

The model proposes. The application validates. Evidence determines what can be claimed.