📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

Walk me through how an AI agent actually runs. What happens in each turn of the loop of reasoning, tool calls and observations, what state does the agent keep between turns, how does the loop end, and where does that loop live in a .NET app using Microsoft.Extensions.AI?

The mechanics of the agent loop: the model proposing tool calls, the host executing them and feeding results back, conversation state and memory, termination conditions and iteration caps, and how FunctionInvokingChatClient and the Microsoft Agent Framework implement it in .NET.

Intermediate Theory Intermediate agent-loop ai ai-agents microsoft-agent-framework microsoft-extensions-ai tool-calling

🎯 Key points

  • The model never executes anything: it returns tool-call requests, your host code runs them
  • Loop: send messages + tool schemas → model returns text or tool calls → run tools → append results as tool messages → repeat
  • State is the message history (plus optional memory store); the model itself is stateless between requests
  • Ends when the model returns a final answer with no tool calls, or a cap is hit (MaximumIterationsPerRequest, token budget, timeout)
  • In .NET (as of November 2026) the loop is FunctionInvokingChatClient via UseFunctionInvocation, or a Microsoft Agent Framework 1.x AIAgent on top of IChatClient
  • Every iteration costs a full model call: the whole growing history is re-sent, so latency and tokens grow per step
  • At scale: history per request or per thread (never shared mutable state), stateless app instances, and model quota (tokens per minute) as the real bottleneck
  • Tool errors are returned to the model as observations so it can recover, but repeated errors must stop the loop

⏱ 30-second answer

An agent is an LLM running in a loop inside your code. Each turn you send the message history plus the tool schemas; the model replies with either a final answer or one or more tool-call requests (name + JSON arguments). Your host executes those calls, appends the results as tool messages (the observations), and calls the model again. The model is stateless: all the agent's state is the history you keep, plus any memory store you add. The loop ends when the model answers without tool calls, or when you hit a cap: iterations, tokens, time or consecutive errors. In .NET that loop is FunctionInvokingChatClient (via UseFunctionInvocation()) or the Microsoft Agent Framework's AIAgent. The trade-off: autonomy for unpredictability, because every step is another full model call that costs latency and tokens and can go wrong.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"An agent is just an LLM called in a loop by my code, with tools it can ask for. On each turn I send the conversation so far plus the JSON schemas of the tools. The model doesn't run anything: it returns either a final text answer or a list of tool calls, each with a name, a call id and JSON arguments. My host deserialises those, validates them, runs the C# methods, and appends each result as a tool message tied to the call id. Then I call the model again with the longer history. That's the reason–act–observe loop; the 'reasoning' is just the model deciding what to ask for next given what it has seen.

In .NET 10 I rarely write that loop by hand. Microsoft.Extensions.AI gives me FunctionInvokingChatClient: I register an IChatClient, add .UseFunctionInvocation(), pass AIFunctions in ChatOptions.Tools, and it runs the loop, including parallel tool calls and feeding exceptions back as observations. It has MaximumIterationsPerRequest and MaximumConsecutiveErrorsPerRequest so the loop can't spin forever. When I need named agents, threads with persisted state, middleware or multi-agent workflows, I use the Microsoft Agent Framework, which went 1.0 in April 2026 and sits on the same IChatClient abstraction.

The mistake I see is thinking the model 'remembers' or 'does' things. It is stateless; the history is the state, and it grows every iteration, so a ten-step agent re-sends the whole conversation ten times. That's why I always cap iterations, trim or summarise history, and log every step. An agent is a while-loop whose condition is decided by a model, so you own the exit conditions."


One turn of the loop

Step Who What happens
1. Build request Host System prompt + history + tool schemas (ChatOptions.Tools)
2. Decide Model Returns text, or FunctionCallContent items (name, callId, arguments)
3. Act Host Validate arguments, check permissions, invoke the method
4. Observe Host Append FunctionResultContent (callId, result or error) as a tool message
5. Repeat or stop Host Loop to step 1, or stop on final answer / cap

What state an agent keeps

State Where it lives Notes
Short-term (this task) The message list Grows each step; trim or summarise past a token budget
Conversation thread Agent Framework AgentThread, or your DB Serialise it to resume a conversation later
Long-term memory Vector store / database via a context provider Retrieved and injected; never trust it as instructions
Tool side effects Your systems The real-world state; needs idempotency and audit

Ways the loop ends

Condition Healthy?
Model returns text with no tool calls Normal completion
MaximumIterationsPerRequest reached Safety stop: return a partial answer or escalate
Consecutive tool errors exceed a limit Stop; the model is flailing
Token or cost budget / CancellationToken timeout Stop; log for tuning
A tool requires human approval Pause; resume when approved

Production example

In a support triage agent with four read-only tools, a typical request took 3 model calls and about 4 seconds at p50. Without a cap, 1–2% of requests looped on a failing lookup tool for 20+ iterations and cost 15 times the median; setting the iteration cap to 8 and stopping after 3 consecutive tool errors removed the long tail with no measurable drop in resolution rate on the evaluation set.

πŸ” What the interviewer is checking

Checks whether the candidate understands the agent as a host-driven loop over a stateless model, with explicit state and exit conditions, rather than as magic.

Green flags

  • States clearly that the host executes tools and the model only requests them
  • Describes the message history as the state and its cost growth per step
  • Names concrete caps (iterations, consecutive errors, timeout, budget)
  • Knows FunctionInvokingChatClient / UseFunctionInvocation and where the Agent Framework fits
  • Treats tool arguments and results as untrusted

Red flags

  • "The agent remembers" or "the model calls the API" without qualification
  • No answer for how the loop ends
  • Parses free text with regex instead of using native tool calling
  • No mention of cost or latency per step

πŸ“š Learn in depth

1. The model is a function, not a process

A chat completion is a pure-ish function: f(messages, tools, options) β†’ message. Nothing persists on the model side between calls (provider-side conversation features just store the history for you). Everything that looks like memory or planning comes from what you put in messages.

          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚                 HOST (.NET)              β”‚
          β”‚                                          β”‚
 history ─┼─► IChatClient.GetResponseAsync ──► Model β”‚
   β–²      β”‚            β”‚                             β”‚
   β”‚      β”‚            β–Ό                             β”‚
   β”‚      β”‚   text? ──yes──► return final answer     β”‚
   β”‚      β”‚      β”‚no (FunctionCallContent[])         β”‚
   β”‚      β”‚      β–Ό                                   β”‚
   β”‚      β”‚   validate β†’ authorise β†’ invoke tool     β”‚
   β”‚      β”‚      β”‚                                   β”‚
   └──────┼── append FunctionResultContent           β”‚
          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

2. How tool calls are represented

The model is given each tool as a name, description and JSON schema for its parameters. Its reply contains structured tool calls; in Microsoft.Extensions.AI these surface as FunctionCallContent (with CallId, Name, Arguments). The result goes back as FunctionResultContent with the same CallId, inside a message with ChatRole.Tool. The call id matters: with parallel tool calls the model asks for several at once and needs to match each result.

3. What FunctionInvokingChatClient does

FunctionInvokingChatClient is a delegating IChatClient in the pipeline. On each response it:

  1. Looks for FunctionCallContent items.
  2. Finds the matching AIFunction in ChatOptions.Tools.
  3. Invokes it (optionally concurrently with AllowConcurrentInvocation), catching exceptions.
  4. Adds the call and result messages to the history and calls the inner client again.
  5. Stops when there are no calls, or when MaximumIterationsPerRequest or MaximumConsecutiveErrorsPerRequest is reached.

It also creates OpenTelemetry activities for tool invocations when you add .UseOpenTelemetry(), which is how each step becomes visible in a trace.

4. Agents in the Microsoft Agent Framework

The Agent Framework (1.0, April 2026, the successor to Semantic Kernel's agent features and AutoGen) wraps the same loop as an AIAgent with instructions, tools, a thread for persisted conversation state, context providers for memory, middleware to intercept runs and tool calls, and graph-based workflows to combine agents with deterministic steps. Under the hood it still calls an IChatClient.

5. Cost and latency grow with steps

If the history is H tokens and each step adds d tokens, step n sends roughly H + nΒ·d input tokens. Total input over N steps is about NΒ·H + dΒ·NΒ²/2: quadratic in the number of steps. Prompt caching on the provider side reduces the cost of the repeated prefix but not the latency of N sequential round trips. This is why agents with 20 steps feel slow and expensive, and why you summarise or drop old tool output.

6. Failure modes of the loop

  • Looping: the model repeats the same call because the result doesn't satisfy it.
  • Argument drift: invalid or invented arguments; you must validate.
  • Context overflow: big tool results push out the instructions.
  • Premature stop: the model answers before using the tool it needed.
  • Injection through observations: tool results are untrusted input that can contain instructions.

Try it yourself

  1. Build a console app with an IChatClient and one tool; log each FunctionCallContent and FunctionResultContent to see the loop.
  2. Make the tool throw on the first call and watch the model retry with the error as an observation.
  3. Set MaximumIterationsPerRequest = 2 with a task that needs three steps and see what comes back.
  4. Add .UseOpenTelemetry() and export to the Aspire dashboard to see a span per model call and tool call.
  5. Record input tokens per step (ChatResponse.Usage) for a five-step task and plot the growth.

πŸ’» Code

A minimal agent loop with Microsoft.Extensions.AI: the pipeline runs the loop, and the caps make the exit conditions explicit.

// Program.cs (.NET 10, nullable enabled)
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Extensions.AI;

var builder = WebApplication.CreateBuilder(args);

// Managed identity, no keys. Deployment name comes from configuration.
var endpoint = new Uri(builder.Configuration["AzureOpenAI:Endpoint"]!);
var deployment = builder.Configuration["AzureOpenAI:ChatDeployment"]!;

builder.Services.AddSingleton<OrderTools>();
builder.Services
    .AddChatClient(new AzureOpenAIClient(endpoint, new DefaultAzureCredential())
        .GetChatClient(deployment).AsIChatClient())
    .UseFunctionInvocation(configure: c =>
    {
        c.MaximumIterationsPerRequest = 8;        // hard stop on runaway loops
        c.MaximumConsecutiveErrorsPerRequest = 3; // stop when the model keeps failing
    })
    .UseOpenTelemetry(); // a span per model call and tool call

var app = builder.Build();

app.MapPost("/triage", async (TriageRequest req, IChatClient chat, OrderTools tools, CancellationToken ct) =>
{
    List<ChatMessage> history =
    [
        new(ChatRole.System, "You triage support tickets. Use tools to look up facts. Never guess order data."),
        new(ChatRole.User, req.Message)
    ];

    var options = new ChatOptions
    {
        Tools = [AIFunctionFactory.Create(tools.GetOrderStatusAsync)]
    };

    using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
    timeout.CancelAfter(TimeSpan.FromSeconds(30)); // wall-clock budget for the whole loop

    ChatResponse response = await chat.GetResponseAsync(history, options, timeout.Token);
    return Results.Ok(new { response.Text, response.Usage?.TotalTokenCount });
});

app.Run();

public sealed record TriageRequest(string Message);
using System.ComponentModel;

namespace Support.Agents;

public sealed class OrderTools(IOrderRepository orders)
{
    [Description("Gets the status of one order by its order number, e.g. ORD-12345.")]
    public async Task<string> GetOrderStatusAsync(
        [Description("Order number in the form ORD-nnnnn")] string orderNumber,
        CancellationToken ct)
    {
        // Validate: the arguments came from a model, treat them as untrusted input.
        if (!OrderNumber.TryParse(orderNumber, out var id))
            return "Invalid order number format. Expected ORD-nnnnn."; // an observation the model can act on

        var order = await orders.FindAsync(id, ct);
        return order is null ? "No such order." : $"Status: {order.Status}, updated {order.UpdatedUtc:u}";
    }
}

⚠ Common mistakes

  • Mistake: Believing the model executes tools or remembers earlier turns. Why it is wrong: It only returns structured requests and sees only what you send. Instead: Treat your host as the executor and the message list as the state.
  • Mistake: Running the loop with no iteration, token or time cap. Why it is wrong: A model can repeat the same failing call indefinitely and burn cost. Instead: Set MaximumIterationsPerRequest, a consecutive-error limit and a CancellationToken timeout.
  • Mistake: Returning huge tool results (whole tables, full documents). Why it is wrong: They crowd out the instructions and grow cost quadratically across steps. Instead: Return compact, relevant results and page or summarise.
  • Mistake: Throwing exceptions straight to the user when a tool fails. Why it is wrong: The model could often recover with a corrected argument. Instead: Return a clear error as the observation, and stop after repeated failures.
  • Mistake: Trusting tool arguments because the model produced them. Why it is wrong: Arguments can be wrong, invented or injected. Instead: Validate and authorise every call in code.
  • Mistake: Hand-writing the loop with string parsing of model output. Why it is wrong: Native tool calling gives structured, schema-shaped calls. Instead: Use FunctionInvokingChatClient or the Agent Framework.
  • Mistake: Keeping agent history in a singleton or static field. Why it is wrong: Under concurrency, users' conversations mix and leak into each other, and it pins state to one instance. Instead: Keep history per request or per persisted thread (database or distributed cache) so instances stay stateless and can scale out; plan capacity around the model deployment's tokens-per-minute quota, with retries on 429.
  • Mistake: Shipping an agent because a few demos looked right. Why it is wrong: Agents can be confidently wrong or treat groups of users unfairly (biased answers or decisions) in ways demos don't show. Instead: Evaluate on a representative test set, including fairness and safety cases, and keep a human in the loop for decisions that affect people.
  • Mistake: Treating tool results as trusted instructions. Why it is wrong: Retrieved content can carry indirect prompt injection. Instead: Keep tool output as data and gate side-effecting tools.

πŸ› Senior insight: trade-offs

The senior framing is that an agent moves control flow from your code to a model, so you give up predictability in exchange for flexibility. That is worth it only when the path genuinely varies per request. Everything you'd normally get from code (bounded loops, validation, authorisation, logging) you now have to add around the model deliberately. I measure an agent by task success rate on an evaluation set, steps per task, tokens per task and p95 latency, and I watch for the long tail, because the averages hide the runaway loops.

Option When it fits Cost When not to
Single model call, no tools Classification, summarisation, extraction 1 call Needs live data or actions
UseFunctionInvocation loop A few tools, one conversation, ASP.NET endpoint 2–5 calls typical Long-running or multi-agent tasks
Agent Framework AIAgent + threads Persisted conversations, middleware, memory providers Same calls, more structure A single tool call would do
Agent Framework workflows Mix of deterministic steps and agents, checkpoints Most moving parts Simple request/response features

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate says they'd use an agent for a feature Why: Checks whether they can justify an agent over a fixed workflow
    How to answer

    A workflow runs steps you wrote in code and calls the model at known points: classify an email, extract fields, draft a reply. Control flow and state live in your code (or a durable orchestrator), so each step has a known input and output that you can unit-test, retry and cost up front. An agent gets a goal and tools and chooses the steps itself in a loop until it decides it is done. An example is a support assistant that investigates an order across several systems in whatever order the case needs.

    Workflows are cheaper, faster and predictable. Agents handle open-ended tasks with unknown paths, at the cost of more calls, variable latency and harder evaluation. Choose a workflow when you can write the steps down, and an agent only when you can't. Then add an iteration and token cap, least-privilege tools, human approval for actions with real-world effect, and tracing of every step.

  2. When: Candidate mentions describing C# methods as tools Why: Checks the detail of tool schemas, argument validation and limiting what a tool can do
    How to answer

    With tool calling, you describe functions (name, description, JSON schema of parameters) in the request. The model can reply with a tool-call request instead of text; your app executes it and sends the result back, and the model continues. In Microsoft.Extensions.AI, AIFunctionFactory.Create turns a C# method into a tool, you pass it in ChatOptions.Tools, and UseFunctionInvocation() runs the loop.

    The model chooses the arguments, so treat them as untrusted input: validate them, authorise against the signed-in user inside the tool, expose only least-privilege tools, require approval for side effects and cap iterations. The trade-off: tools make the model useful, but every tool widens what a confused or manipulated model can do.

  3. When: Candidate mentions that each step re-sends the history Why: Checks cost control for multi-step LLM features
    How to answer

    Measure first: log input and output tokens per request from ChatResponse.Usage and chart cost per feature and per tenant; set Azure Cost Management budgets and alerts on the Azure OpenAI / Foundry resource so spend never surprises you. Then reduce:

    • Use a smaller model for simple steps (routing, classification, extraction), trim history and system prompts, and use retrieval instead of stuffing whole documents.
    • Cap ChatOptions.MaxOutputTokens, and cache repeated answers with Microsoft.Extensions.AI's UseDistributedCache() on the ChatClientBuilder (it wraps an ASP.NET Core IDistributedCache such as Redis; exact-match only, so it helps for identical prompts).
    • Enforce budgets per user or tenant with rate limiting.

    Re-run your evaluation set after each change, because a cost cut that silently lowers quality is a false saving.

More in AI Agents and MCP

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me