What Actually Runs in One AI Agent Turn
One turn of a production AI agent is not one model call. Between the request and the reply sits a pipeline: mask and screen the input, gather context in parallel, route the turn to the right model, build a cache-friendly prompt, run the model inside a stack of middleware that bounds the loop, fall back if the provider is down, screen the output, stream it, then do the expensive bookkeeping after the user already has the answer.
I'm Mahmoud Zalt, an AI systems architect, and most of my week goes into Sistava, where autonomous agents do real business work for paying customers.
This article walks through one turn in order, layer by layer, the way it runs in our system. The lesson I want you to take away is simple: the model call is the cheapest part of the design to get right. Almost every production failure I have debugged lived in the layers around it, in what was fetched, what was cached, what was allowed to repeat, and what happened after the reply.
Here is the whole turn in one table before we go deep.
| Layer | What it does | Runs |
|---|---|---|
| Input masking | Redacts PII before anything else sees the text | Inline, no model |
| Input rail | Safety and policy check on the message | Concurrently with preparation |
| Context gather | History, memory, documents, duties, team, tools | One parallel fan-out |
| Semantic router | Small talk to a cheap model, work to the full one | Once per turn, before the main model |
| Prompt build | Static prefix, dynamic tail | Once per turn |
| Middleware + model loop | Think, call tools, bounded by guards and approvals | Every model call |
| Provider fallback | One retry on a different provider on outage | On 5xx, timeout, connection failure |
| Output rail | Safety check on the reply | Before delivery |
| Post-turn jobs | Billing, sampled evals, memory, outcome signals | Async, after the reply |
1. Mask First, Then Screen the Input in Parallel
The first thing that touches a user message is PII masking. We use Presidio for this, applied by the engine rather than as a model call, so it costs nothing and adds no meaningful latency. A card number pasted into a support chat is replaced before the text reaches a log, a trace, an embedding call or a prompt. Masking has to come first because every later layer is a place the raw value could leak to.
Then comes the input rail. Ours is built on NeMo Guardrails: a self-check on the input for harmful or manipulative content, plus our own actions for blocked topics and data-leak attempts, each toggleable per organisation. If a rail stops the message, the turn raises a non-retryable policy violation and an activity record is written. Nothing downstream runs.
The design decision that matters here is concurrency. On the streaming path, the input rail runs at the same time as the rest of the preparation, not in front of it. A safety check that sits serially in front of everything adds its full latency to every single turn. Running it alongside context gathering means the user pays for the slower of the two, not the sum. The agent cannot act until the rail clears, so you lose nothing in safety.
2. Gather Every Context Source in One Fan-Out
Before the model writes a token, the agent needs to know who it is talking to and what it already knows. In our system that is one parallel fan-out: a single asyncio.gather over every context source, with return_exceptions=True. Recent conversation history, long-term memory facts, retrieved passages from the user's documents, the agent's duties, its teammates, its tools and the user's active connections all load at once.
Two rules make this safe in production:
- Every source has a typed default. If memory search times out, the agent gets an empty fact list, not an exception. One slow dependency degrades the context; it never kills the turn. Each failure is logged with enough of a prefix to find it later.
- Every source has its own timeout. Knowledge search in particular has a hard budget and fails to an empty result, because document retrieval is the source most likely to be slow on a cold tenant.
Memory here is two systems with different jobs. Long-term facts and episodes live in a temporal knowledge graph built with Graphiti on Neo4j, searched before each reply. Retrieved documents come from a hybrid dense and sparse index in Qdrant, filtered to what the person asking may see before anything is ranked. I cover the retrieval pipeline in depth in a separate article; for the turn, what matters is that it is just one more branch of the fan-out.
3. Route the Turn: Small Talk to a Cheap Model
A large share of messages in a working chat are not work. "Thanks", "perfect", "hi again". Sending those to a frontier reasoning model with a full tool belt is pure waste. So before the main model, a semantic router decides once per turn whether this is chat or work.
The router is a small, deliberate piece of engineering, borrowed in spirit from the open-source semantic-router project:
- An empty message, or one an anchored multilingual regex recognises as a pure greeting or acknowledgement, goes to chat for free, with no embedding call.
- Very long messages skip classification and stay on the full model. You never want to classify a truncated brief.
- Everything else is embedded and compared to example utterances grouped by route. Each route scores the mean of its top matches, and chat has to clear a conservative similarity floor before it wins.
- Any error routes to work. The failure mode of a router must be "spent a little more", never "downgraded real work".
Two lessons from running it. First, a bare approval like "yes, do it now" carries no task of its own. Routed alone it looks like small talk, and we once sent the approval of a heavy multi-step job to the cheap lane. Now a bare approval is embedded together with the assistant message it approves, so it inherits that turn's weight. Second, the router only runs when the selected model is strictly more expensive than the cheap lane. If a user already picked a cheap model, classifying would cost an extra embedding to save nothing.
4. Embed the Message Once, Reuse It Everywhere
Look at the previous two sections and count the embedding calls. The router embeds the message. Memory search embeds it. Document retrieval embeds it. Without care, the same text gets embedded several times in one turn, by different modules that never talk to each other.
We found exactly that in production: the same user message was being embedded up to four times per turn. The fix was structural, not a patch. There is now one embedding service that every caller goes through, with a per-turn memo so the router's vector is reused by memory and retrieval, and a short-lived Redis cache for repeats across turns. A test blocks direct calls to the embedding provider from anywhere else, so the duplication cannot quietly come back.
The general rule: any per-turn derived artifact that more than one layer needs should have exactly one owner. Embeddings are the obvious case, but the same applies to tokenised history, resolved permissions and connection snapshots.
5. Build the Prompt With a Static Prefix and a Dynamic Tail
Provider prompt caching only works on an identical prefix. If anything near the top of your prompt changes between turns, the whole cache misses and you pay full price for tokens you sent a moment ago. So the prompt layout is a cost decision as much as a quality one.
Our layout is strict:
- Static prefix: the system prompt assembled from versioned section files, the agent's role, rules, duties and tool descriptions. This changes rarely, and we mark the cache breakpoint at its end (an explicit
cache_controlmarker for Anthropic, a stable cache key for OpenAI, a session id through OpenRouter). - Conversation: the checkpointed history, trimmed to a bounded window.
- Dynamic tail: retrieved document passages and remembered facts, appended as a trailing message after the conversation, not spliced into the system prompt.
That last point is the one people get wrong. Retrieved context is the most volatile thing in the prompt; it changes every turn. Putting it in the system prompt feels natural and destroys your cache hit rate. Appending it at the end keeps the large static prefix byte-identical turn after turn, so turn two, three and ten of a conversation reprocess far less from scratch.
The same thinking applies inside a long turn. When stale tool results pile up, we replace older ones with a placeholder in the request only (the checkpoint keeps the full results), and we clear them as a stable prefix so the cache boundary only moves near the end.
6. Wrap the Model Call in Middleware That Bounds the Loop
The agent loop itself is LangGraph: call the model, execute any tool calls, feed results back, repeat until the model answers. On its own, that loop will happily spin forever, burn a budget on the same failing tool, or end a long task with an empty message. Everything that prevents that lives in middleware wrapped around each model call.
The categories that earn their place:
| Guard | Failure it prevents |
|---|---|
| Loop detection | Repeating the same tool and arguments, or churning short results that make no progress |
| Tool failure streak | Hammering a tool that keeps erroring |
| Empty response guard | A turn that ends with nothing for the user to read |
| Run ceiling and turn budget | Runaway length; the turn wraps up before the step limit instead of dying on it |
| Context editing and budget | Stale tool output flooding the window; overflow handled by dropping tagged low-priority blocks |
| Human in the loop | Risky actions (payments, deletions, public posts, outside messages) executing without consent |
Three design rules came out of real incidents:
- Every budget ends in a written answer. When a guard ends a turn, the closing model call forbids tool calls at the provider level (tool choice set to none). Asking the model in words is not enough; we watched models answer a "please summarise now" instruction with yet another tool call.
- Guard text never goes into the assistant message. Anything written there is the agent's visible reply. A guard that needs the model to change course sends its directive as a separate message, bounded, and the user only ever sees the model's own words or a fixed, customer-facing fallback.
- Guard state is keyed to the run, not the thread. An approval resume is a new graph run. If your loop counter lives in per-run memory, an approved command can repeat for hours because each resume starts counting from zero. Count from the turn's messages instead.
Approvals deserve a sentence of their own. An approval is scoped to the exact action: same tool, same arguments, same batch order. Any change produces a fresh approval card. Approving "send this email" must never approve "send a different email".
7. Fall Back When the Provider Goes Down
Model providers have outages. An agent that simply stops when its provider does is not production software. Our rule: on a server-side failure (a 5xx, a connection failure, a timeout), retry once on a fallback model from a fallback chain, then give up cleanly. Authentication errors, ordinary rate limits and bad requests fail immediately, because retrying them elsewhere either hides a real bug or spends money for the same error.
The fallback is non-sticky. The user's chosen model resumes on the next request. And it has to cover every entry point that runs the graph, not just the main one. We learned that from a resume path: an approval answered during a provider outage had no fallback chain and ended in a generic "something went wrong". Now a test discovers every public entry point that runs the agent and fails if one does not walk the chain.
Scope matters too. The fallback applies to the main agent and the guardrails. Subsystem models such as embeddings and memory extraction degrade differently: they fail to empty context, which the fan-out in section 2 already tolerates.
8. Screen the Output, Then Stream
The output gets its own rail, separate from the input rail. A harmless question can still produce a reply that should not go out, for example one that echoes data it was never meant to share. The output rail runs a self-check on the reply and our data-leak action; if it trips, the content is replaced with a violation message and an activity record is written.
Streaming has its own sharp edges. Cancellation is checked at step transitions, not per token, so a cancel is cheap and safe. When teammates run as sub-agents, their tokens are filtered so two agents never interleave in one bubble. And a teammate's fixed fallback text is never posted as its own message; its lead answers instead.
9. Do the Expensive Bookkeeping After the Reply
Once the user has the answer, four jobs run in the background. None of them should ever add latency to the reply, and none of them should be able to fail the turn.
- Billing flush. Three callback handlers observe every model call during the turn: one for token billing, one for the activity timeline, one for external tracing in Langfuse. After the turn, billing is flushed. Tracking completion is written before anything else in post-processing, so a downstream failure cannot make finished turns disappear from dashboards.
- Sampled online evals. A sample of turns that used retrieved knowledge is scored afterwards by a separate AI judge for faithfulness, context relevance and answer relevance. It is sampled, never blocking, and alerts when faithfulness drops. Pre-delivery quality checks exist too, but they are opt-in per workspace, because a judge in the critical path costs latency and money on every turn.
- Memory ingestion. Long-term memory is written once the conversation goes quiet, not after every message. Graphiti reads the buffered exchange, extracts entities and facts, and stores them as a graph. Gates skip what is not worth remembering: trivial messages, pure small talk, turns that are mostly tool output, and anything over a per-thread rate cap.
- Outcome signals. Thumbs up and down are recorded, and a follow-up that suggests the previous answer missed ("no, that's the wrong invoice") is reviewed in the background. Users rarely file bug reports; they rephrase. Treating the rephrase as a signal is how you find quality drops before anyone complains.
Durability ties it together. Turns run as Temporal workflows, so a worker restart does not lose a half-finished turn, and errors the agent already handled (a cancelled activity, a provider outage) are marked non-retryable so the orchestrator does not run the same paid work twice.
If You Are Building This, Start Here
You do not need every layer on day one. If I were starting a new agent tomorrow, this is the order I would add them in, based on what failed first for us:
- Bounded loop with a forced final answer. Without it, your first runaway turn will cost more than a month of the rest.
- Exact-action approvals for anything irreversible. Payments, deletions, public posts, outside messages.
- Static prefix, dynamic tail. It is a one-time layout decision and the cost difference compounds on every turn.
- Parallel context gather with typed defaults. Latency and resilience in one change.
- Provider fallback on every entry point, with a test that discovers the entry points for you.
- Input and output rails, PII masking first.
- Async post-turn evals and outcome signals. This is how the system tells you where it is weak.
The semantic router and the embedding memo come last: they are pure cost optimisations, and they only matter once you have the volume to notice.
Frequently Asked Questions
Should guardrails run before or in parallel with the agent?
In parallel with preparation, but blocking before the agent acts. Running the input rail concurrently with context gathering hides its latency; gating the model call on its result keeps the safety guarantee.
Where should retrieved RAG context go in the prompt?
After the conversation, as a trailing message. The system prompt should be a byte-stable prefix so provider prompt caching keeps working. Volatile context at the top of the prompt breaks the cache on every turn.
Is a semantic router worth it?
Only when the gap between your cheap and full model is large and a real share of turns is small talk. Make it fail toward the full model, skip it when the user's model is already cheap, and route bare approvals with the message they approve.
How do I stop an agent loop from running forever?
Bound it in middleware: loop detection, tool-failure streaks, a step ceiling that triggers a wrap-up before the hard limit, and a final call with tool use disabled at the provider so the turn always ends with text.
Should evals run on every turn?
Not in the critical path by default. Sample turns asynchronously after delivery for monitoring, and offer blocking pre-delivery checks as an opt-in for the outputs where a bad result is expensive.
Three Things to Take Away
One. A turn is a pipeline, and the model call is its most commoditised stage. Spend your design time on what surrounds it.
Two. Concurrency and layout are cost features. Parallel rails and context, one owner per embedding, a static prefix with a dynamic tail: each one shows up on every single turn.
Three. Every guard needs an exit that produces a written answer, and every post-turn job must be unable to fail the turn. Users forgive a slow reply far more readily than a silent one.
If you are designing an agent runtime and want a second pair of eyes on the turn pipeline before it meets real users, that is the kind of review I do in an agent development engagement.








