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.
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.
"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 anIChatClient, add.UseFunctionInvocation(), passAIFunctions inChatOptions.Tools, and it runs the loop, including parallel tool calls and feeding exceptions back as observations. It hasMaximumIterationsPerRequestandMaximumConsecutiveErrorsPerRequestso 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 sameIChatClientabstraction.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."
| 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 |
| 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 |
| 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 |
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.
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
FunctionInvokingChatClient / UseFunctionInvocation and where the Agent Framework fitsRed flags
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 β
ββββββββββββββββββββββββββββββββββββββββββββ
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.
FunctionInvokingChatClient is a delegating IChatClient in the pipeline. On each response it:
FunctionCallContent items.AIFunction in ChatOptions.Tools.AllowConcurrentInvocation), catching exceptions.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.
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.
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.
IChatClient and one tool; log each FunctionCallContent and FunctionResultContent to see the loop.MaximumIterationsPerRequest = 2 with a task that needs three steps and see what comes back..UseOpenTelemetry() and export to the Aspire dashboard to see a span per model call and tool call.ChatResponse.Usage) for a five-step task and plot the growth.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}";
}
}
MaximumIterationsPerRequest, a consecutive-error limit and a CancellationToken timeout.FunctionInvokingChatClient or the Agent Framework.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 |
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.
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.
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:
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).Re-run your evaluation set after each change, because a cost cut that silently lowers quality is a false saving.
Last updated 23 Nov 2026.