#184 — How Agentic AI works
June 27, 2026·10 min read

Contents
Why it matters: Every AI product you're building — or funding, or competing against — runs on some version of this. If you can't read the architecture, you can't evaluate what you're building or buying, and you won't know why it breaks in production.
What an agent actually is
An agent is a system that perceives its environment, reasons about it, acts, and remembers. What makes an AI agent distinct is that the reasoning step is handled by an LLM — and the range of possible actions extends well beyond a binary output.
Every agent has two separable layers:
- The model — the inference engine that reasons
- The harness — the code that prepares context, runs tool calls, enforces constraints, and persists state
Most agent engineering work happens in the harness, not the model. Understanding that boundary tells you where failures originate — and where to intervene.
What the loop is (and why it exists)
The agent loop is the repeating cycle inside a single agent run: assemble context → reason → act → repeat until a stop condition ends the run.
It exists because hard tasks can't be finished in a single LLM call. Take a deep research task: search for sources, read them, identify contradictions, search again to fill the gaps, synthesize. No single forward pass can do all of that. The loop is the mechanism that makes it possible.
Three modes where the loop is essential:
- Assistant — multi-turn tasks requiring memory of prior context
- Deep Research — iterative search, synthesis, and gap-filling
- Coding — edit, test, observe failure, edit again until it passes
Stop conditions: how the loop ends
A loop with no exit conditions is a liability. Define these explicitly in your harness from day one:
- Model produces a final response with no pending tool calls
- A goal-completion check returns true — not just the absence of tool calls, but actual task verification
- Maximum iteration count reached (10 is a common default)
- Wall-clock timeout expires
- An unrecoverable error occurs
- Failure mode detected — the agent repeats the same tool call with identical arguments 3× in a row. It's stuck, not working. A well-instrumented harness detects this pattern and exits with a diagnostic instead of burning remaining iterations on a stalled run
Critical distinction: A terminal message from the model (no further tool calls) does not mean the user's goal is satisfied. The model may return a partial result or a clarifying question. Your harness — not the model — is responsible for verifying goal completion.
The 3 levels every founder should know
Most production failures — agents that repeat themselves, lose context, or produce inconsistent results across sessions — trace back to a mismatch between task complexity and agent level, not a model problem.
Level 1 — The MVP agent
LLM + tools + a response. No persistent memory. Every session starts cold. The context window is the only memory it has, and it resets completely when the run ends.
Useful for self-contained, single-shot tasks. Structurally broken for anything multi-turn or long-horizon — it will repeat prior work, lose earlier decisions, and contradict its own prior responses within the same session.
Level 2 — The agent with a brain
Memory is read before the model reasons and written after it acts. The loop now has a lifecycle. The agent can track what it's done, who it's talking to, and what it's already retrieved — across sessions, not just within one.
Two distinct classes of agent emerge here:
- Memory-augmented agents retrieve and inject information into context but don't manage it. Memory is something that happens to them.
- Memory-aware agents encode, store, retrieve, inject, and forget — actively managing their cognitive state within each run and across sessions. Level 2 is where you start building the latter.
The six memory types that matter at Level 2:
| Memory Type | What It Stores | How Retrieved |
|---|---|---|
| Conversational | Prior chat history | Thread ID (SQL lookup) |
| Knowledge base | Retrieved documents & facts | Vector similarity search |
| Workflow | Learned action patterns & tool sequences | Semantic similarity |
| Toolbox | Tool definitions & metadata | Vector-indexed semantic discovery |
| Entity | Extracted people, places, systems | Semantic similarity |
| Summary | Compressed context for long sessions | Thread ID, expanded on demand |
Failure modes you'll hit at Level 2 (not edge cases — predictable failures as memory stores grow):
- Noisy retrieval — semantically similar content that isn't actually relevant gets injected, and the model hallucinates downstream. Fix with relevance thresholds and hybrid search with pre/post/in-filtering.
- Stale memory — cached facts or entity records go out of date. Use TTL policies and update-on-write patterns.
- Tool schema overload — passing too many tool definitions at once tanks tool-selection accuracy and inflates token costs. Use vector-indexed semantic tool discovery instead of exhaustive enumeration.
Design mitigation strategies at build time. Retrofitting fixes later is significantly more expensive.
Level 3 — The agent as a system
The harness around the loop becomes as important as the loop itself. Operations now exist both inside and outside the loop, and there are deliberate architectural choices about which side of the boundary each belongs on.
The key decision: what runs automatically vs. what the agent triggers.
| Operation | Automatic | Agent-Triggered |
|---|---|---|
| Load conversation history | ✅ | — |
| Load knowledge base | ✅ | — |
| Load workflow patterns | ✅ | — |
| Resolve entity references | ✅ | — |
| Load summary IDs | ✅ | — |
| Expand full summary | — | ✅ Agent decides when needed |
| Search the web | — | ✅ Agent decides when stored knowledge is insufficient |
| Compact conversation context | — | ✅ Agent decides when tokens are under pressure |
| Write tool output to log | ✅ | — |
Getting this boundary wrong produces either context bloat (too much loaded automatically) or missed context (content that should always be present left to the model's discretion).
Three techniques that only become necessary at Level 3:
- Context window monitoring — track token usage across iterations. Detect when compaction is needed before the window fills and performance degrades.
- Conversation compaction — replace verbose chat history with compressed summaries. Don't delete originals — mark them with a summary ID and keep the full record available for audit and on-demand expansion.
- Tool output offloading — a single web search can return 3,000–4,000 tokens of raw results. Without offloading, every subsequent iteration carries those tokens. With offloading, context receives only a compact one-line reference, and the full output is retrievable by ID when needed.
Semantic tool discovery — at scale, passing every tool schema to the model on every iteration is a known failure mode. Tool selection accuracy degrades as schema lists grow, and token costs climb regardless of relevance. The fix: a vector-indexed tool registry where only semantically relevant tools are surfaced per query, with LLM-enriched metadata so embeddings capture intent and use case, not just function signatures.
Idempotency — tool call failures happen: network errors, rate limits, transient service issues. Naive retries risk executing side-effecting operations twice — writing a record, sending a message, triggering a payment. Assign each tool call a stable key before execution so retries are safely distinguishable from duplicate calls. This is harness engineering, not model reasoning.
Prompt caching and message ordering — most LLM providers implement prefix-based caching: identical prompt prefixes reuse cached computation, reducing latency and cost. Rewriting earlier messages mid-conversation (to clean history or inject new system instructions inline) breaks prefix stability and degrades cache hit rates. Append new instructions — never modify existing message history.
The three loops your agent runs inside
The agent loop doesn't run in isolation. It sits inside a wider system of loops, and understanding all three determines what your system can — and can't — do.
The training loop
The cycle that produced the model: data collection, gradient updates, evaluation, release. It runs offline, over days or weeks. The agent loop runs online, in real time.
Today these are decoupled. When an agent appears to "learn" within a session — recalling prior context, adapting to corrections — that's retrieval, not weight updating. The agent is reading from memory, not learning.
This boundary defines what memory engineering can solve vs. what requires retraining. Know the difference before you promise customers an agent that "learns."
The feedback loop
Every action the agent takes produces feedback: tool results, user corrections, system-level metrics (hallucination rate, task completion, citation accuracy).
At Level 3, a well-instrumented harness makes the feedback loop explicit. Watching whether token counts stabilize across runs tells you whether context engineering is working. More sophisticated systems route evaluation signals back into memory stores, marking retrieved content as reliable or unreliable based on downstream outcomes — gradually improving retrieval quality without retraining. The feedback loop is what turns an agent into a system that compounds. Without it, every invocation starts from the same baseline.
The human-in-the-loop
Long-horizon tasks regularly reach decision points where the agent lacks the information, authority, or confidence to proceed. The human-in-the-loop pattern introduces a deliberate pause condition — not a fallback for when the agent fails.
Design two things explicitly:
- Where the boundaries sit — which decision points in your workflow require human authority, context, or accountability the agent doesn't have
- What the agent surfaces — not a generic request for help, but a precise description of what information or decision is blocking progress
A generic "I need help" is insufficient. A well-designed pause condition surfaces a specific blocking question and waits.
The longer game: where this is heading
The agent loop, the training loop, and the feedback loop are currently operated as separate engineering concerns. That separation is practical, not fundamental.
As agents accumulate experience across millions of runs — episodic memories, entity graphs, workflow patterns, evaluation signals, context growth traces — that output becomes training signal. The training loop will eventually consume the output of the agent loop, closing the circle.
This has a name: continual learning — the ability of a model to acquire new knowledge from a stream of incoming data over time, without retraining from scratch and without forgetting what it already learned. It's a formal machine learning discipline, not a metaphor, and it's the bridge between the two loops.
The bottom line: When that convergence happens, the quality of your memory layer becomes the quality of your training data. Agents with well-engineered memory — clean episodic records, accurately extracted entities, reliable retrieval signals — produce better training data than agents that let context accumulate without structure.
The architectural decisions you make about memory today don't just determine how your agent performs tomorrow. They determine what it can learn from.
Frequently asked questions
What is the difference between an AI agent and an AI workflow?
A workflow follows a fixed, pre-programmed sequence of steps. An agent decides its own sequence at runtime — it perceives its environment, reasons about what to do next, acts, and loops back until the goal is met. The practical implication: workflows are predictable and auditable but brittle when inputs vary. Agents are flexible but require explicit stop conditions and failure-mode detection or they'll loop indefinitely and burn your token budget.
What is an AI agent loop and how does it work?
The agent loop is the repeating cycle a harness runs within a single agent turn: assemble context → invoke the model to reason → act on its decision → repeat until a stop condition ends the run. It exists because long-horizon tasks — research, coding, multi-step workflows — cannot be completed in a single LLM call. Each iteration appends its trace (assistant messages, tool outputs, state updates) back into context before the next reasoning step begins.
What are the three application modes where agent loops are essential?
The three modes are Assistant (multi-turn tasks requiring memory of prior context), Deep Research (iterative search, synthesis, and gap-filling across multiple sources), and Coding (edit, run tests, observe failure, edit again until the build passes). In each case, the task requires reasoning across multiple steps where the output of one step informs the next — impossible in a single LLM call. Claude Code, Codex, and Cursor all operate in coding mode.
What does 'the model is the easy part' actually mean in practice?
Swapping GPT-4o for Claude Sonnet or Gemini Ultra in most production agents changes outcomes far less than fixing the harness around it. The harness — context assembly, memory reads, tool routing, stop conditions, failure detection — determines what the model sees and when it stops. Most production agent failures (repeated tool calls, lost context, inconsistent sessions) are harness failures, not model failures. Budget accordingly: more engineering time in the harness, less time benchmarking models.
How do you stop an agent loop from running forever?
Define explicit stop conditions in the harness. Common patterns: the model produces a final response with no pending tool calls, a goal-completion predicate returns true, a maximum iteration count (10 is the standard default) is reached, a wall-clock timeout expires, an unrecoverable error occurs, or a repetition detector fires — meaning the agent called the same tool with identical arguments 3× in a row. A well-instrumented harness catches that last pattern and exits with a diagnostic instead of burning remaining iterations on a stalled run.
Does a terminal message from the model mean the task is complete?
No — and this is a common production mistake. A terminal message (no further tool calls) means the model has stopped emitting actions. It does not mean the user's goal is satisfied. The harness is responsible for verifying goal completion, not the model. The model may return a partial result, a clarifying question, or a response that requires follow-up. This distinction becomes critical as tasks grow longer and more complex — goal completion checks belong in the harness, not in whether the model stopped talking.
What is the difference between a memory-augmented agent and a memory-aware agent?
A memory-augmented agent retrieves and injects information into context — memory happens to it passively. A memory-aware agent treats memory as a first-class concern: it actively encodes, stores, retrieves, injects, and forgets — managing its own cognitive state within each run and across sessions. The practical difference shows up at scale: memory-augmented agents accumulate stale, irrelevant context over time. Memory-aware agents prune and update, improving retrieval quality rather than degrading it.
What are the six types of agent memory and when do I need each one?
The six types are: Conversational (prior chat history, retrieved by thread ID via SQL — exact lookup, no vector search), Knowledge base (retrieved documents and facts, retrieved by vector similarity), Workflow (learned action patterns and tool sequences, retrieved by semantic similarity), Toolbox (vector-indexed tool definitions enabling semantic discovery), Entity (extracted people, places, and systems persisted across sessions), and Summary (compressed context for long conversations, with on-demand expansion). You need conversational memory from your first multi-turn product. You need the rest as session complexity and user count grow.
What is context window monitoring and why does it matter in production?
Context window monitoring tracks token usage across iterations to detect when compaction is needed before the window fills and performance degrades, not after. Without it, long-running agents silently hit context limits mid-task and produce truncated or incoherent outputs. Watching whether token counts stabilize across runs also tells you whether your context engineering is actually working. It's a primitive but important observability signal — the equivalent of watching memory usage in a long-running server process.
What is conversation compaction and how does it work without losing data?
Conversation compaction replaces verbose chat history with compressed summaries once the context window comes under pressure. The key is to never delete originals — instead, mark messages with a summary_id in the database and keep the full record available for audit and on-demand expansion. The agent loads only the compact summary by default; when it needs the full content (for audit, follow-up, or debugging), it expands by ID. OpenAI's Codex agent uses this pattern explicitly for long multi-step coding runs.
What is tool output offloading and how much does it reduce token costs?
Tool output offloading means persisting full tool results to a log table and replacing them in context with a compact one-line reference (e.g., '[Tool Log ID: 47] Results stored. Call read_tool_log to retrieve.'). Without it, a single web search returning 3,000–4,000 tokens gets carried forward in every subsequent iteration, compounding fast. With offloading, the model only sees the reference until it explicitly needs the content. For a 10-iteration run with 5 search calls, this can reduce per-session token consumption by 60–80%.
What is semantic tool discovery and when does it start mattering?
Semantic tool discovery means using vector search to retrieve only the tools relevant to the current query, rather than passing every tool schema to the model on every call. Tool selection accuracy measurably degrades past roughly 10–15 tool definitions passed simultaneously, and token costs climb regardless of relevance. The fix is a vector-indexed tool registry with LLM-enriched metadata — embeddings that capture intent and use case, not just function names — so only the 3–5 most relevant tools are surfaced per query.
How do I make tool calls safe to retry without triggering duplicate side effects?
Assign each tool call a stable idempotency key before execution — typically a hash of the tool name, arguments, and session context. When the harness retries on a network error or rate limit, it passes the same key. The downstream service (payment processor, database write, email sender) uses that key to detect and skip duplicate calls. Without idempotency, a transient API failure on a payment tool can result in double charges. Build this in from day one — retrofitting it after a production incident is far more expensive.
What is prompt caching and why does breaking it hurt my infrastructure costs?
Most LLM providers (Anthropic, OpenAI, Google) implement prefix-based prompt caching: if the opening of your prompt is identical to a recent request, the provider reuses cached computation — reducing latency by 40–80% and cost by 50–90% on cached tokens. Breaking prefix stability — by rewriting earlier messages to clean history or inject inline instructions — destroys cache hit rates. The correct pattern: append new instructions to the end of your message history, never modify existing messages. OpenAI's Codex agent explicitly preserves old prompts as exact prefixes of new prompts to maintain this benefit across long runs.
How much do agent loops actually cost to run at scale?
Token costs compound fast because each iteration carries the full accumulated context. A 10-iteration run on a 128K-context model can consume 500K–1M tokens per user session without tool output offloading or conversation compaction. At GPT-4o pricing (~$2.50/1M input tokens), that's $1.25–$2.50 per session. At 10,000 daily sessions, that's $12,500–$25,000/month before any engineering mitigation. Context engineering — compaction, tool log offloading, semantic tool retrieval — is directly a margin lever, not just a performance concern.
When should my agent pause for a human vs. proceed autonomously?
Design pause conditions in advance, not reactively. The right pause points are wherever the agent lacks the authority, context, or accountability to proceed — not wherever it's uncertain. Examples: approving a financial transaction, sending an external communication, deleting production data, or making a decision requiring legal judgment. When the agent pauses, it must surface a specific blocking question. An agent asking 'What should I do next?' is a UX failure. An agent asking 'The invoice total ($14,300) exceeds your auto-approve threshold. Approve or reject?' is a product.
What is the difference between the agent loop and the training loop?
The training loop is the cycle that produced the model: data collection, gradient updates, evaluation, release. It runs offline over days or weeks on fixed datasets. The agent loop runs online in real time on live interactions. Today they are decoupled — weights are frozen and the agent loop runs on top of them. What looks like an agent 'learning' within a session is retrieval from memory, not weight updating. This boundary defines what memory engineering can solve vs. what requires retraining — a critical distinction before you promise customers an agent that 'learns.'
What is the feedback loop in an AI agent system?
Every action the agent takes produces feedback: tool results, user corrections, system-level metrics like hallucination rate, task completion, and citation accuracy. At Level 3, a well-instrumented harness makes the feedback loop explicit. More sophisticated systems route evaluation signals back into memory stores, marking retrieved content as reliable or unreliable based on downstream outcomes — gradually improving retrieval quality without retraining. Without a feedback loop, every invocation starts from the same baseline regardless of what the agent has done before.
What is continual learning and is it available in production AI agents today?
Continual learning is the ability of a model to acquire new knowledge from a stream of incoming data over time without retraining from scratch and without catastrophically forgetting prior capabilities. It is not available in current production agents — what you observe is retrieval, not weight updating. The agent loop and training loop are still decoupled. Continual learning is the formal ML discipline that will eventually bridge them: the agent loop generates experience, and continual learning is the process by which the training loop absorbs that experience into model weights.
Do I actually need a multi-agent system, or is a single agent enough?
For most early-stage products, a single well-designed agent is enough — and significantly easier to debug. Multi-agent architectures introduce coordination overhead, inter-agent context passing, and compounding failure modes. Start with a single Level 2 or Level 3 agent. Reach for multi-agent only when a task has clearly separable parallel workstreams (e.g., one agent searches while another synthesizes) or when you need role-isolated trust boundaries. OpenAI's deep research product uses parallel agent subgraphs — but only after years of single-agent iteration.
What is the difference between a Level 2 and Level 3 agent in terms of build cost and team requirements?
A Level 2 agent (memory reads before LLM call, memory writes after) is achievable by a single full-stack engineer in 2–4 weeks using LangChain, a vector database, and a relational store. Level 3 adds context window monitoring, conversation compaction, tool output offloading, semantic tool discovery, idempotency, and prompt caching — typically requiring a dedicated AI infrastructure engineer and 4–8 additional weeks. The upgrade trigger is production data showing token costs growing faster than sessions, or agent quality degrading on long conversations.
Why does memory architecture today affect what my AI model can learn tomorrow?
As agents accumulate experience across millions of runs, the information they generate — episodic memories, entity graphs, workflow patterns, evaluation signals — becomes training signal. Agents with well-engineered memory (clean episodic records, accurately extracted entities, reliable retrieval) produce better training data than agents that let context accumulate without structure. The architectural decisions you make about memory today don't just determine how your agent performs tomorrow — they determine what it can learn from. The memory layer is where the agent loop and the training loop eventually converge.
Keep reading

#185 — Your AI agent has a memory problem. Here's how to fix it.
Most AI agents don't have a memory size problem. They have an architecture problem. Here's a layered approach that separates demos from production.

#186 — The 95:5 rule: Why most of your GTM is wasted
95% of buyers are not in the market for many goods and services at any one time. This is a deceptively simple fact, but it has profound implications.

#187 — Your AI agents are only as good as the tools you give them
Learn how to write high-quality tools and evaluations, and how you can boost performance by using AI to optimize its tools for itself.