What it is
An AI agent is a program that uses a language model to decide its next action in a loop. The runtime sends the model a goal, the conversation so far and a list of tools (name, description, JSON Schema for arguments). The model answers either with text or with a tool call. The runtime executes the call, appends the result as an observation and calls the model again, until the model gives a final answer or the runtime stops it.
Everything around that loop is ordinary software: the tools are APIs, memory is a database, budgets are counters, approval is a workflow step. The model is the only part that is non-deterministic, and the architecture is mostly about containing that.
Why it exists
Some tasks cannot be written as a fixed sequence because the next step depends on what was found: investigate a support case, fix a failing test, research a question across sources. A fixed workflow would need a branch for every possibility. An agent lets the model choose the path at run time while the runtime keeps control of what actually happens.
How it works
The loop. Prompt → model proposes an action → runtime validates and executes it → observation is appended → prompt again. Turns are strictly sequential, because each decision depends on the previous result. Patterns such as ReAct (reason, then act) or plan-and-execute (draft a plan, then run its steps, re-planning on surprises) are variations of this loop.
Tools. A tool is a function the runtime exposes with a schema. The model sees only the description and schema; it never holds credentials or opens connections. Good tools are narrow, well described, return compact results and fail with clear messages the model can act on. Protocols such as MCP standardise how tools are discovered and called, but the loop is the same.
Memory. The model is stateless per call. Short-term memory is the context window: system prompt, recent messages, tool results. It must be trimmed or summarised as conversations grow, because every token is re-read (and paid for) on every turn. Long-term memory is a store the runtime reads before calling the model (often by vector similarity, sometimes by key) and writes after. Scope it per user or tenant and treat it as fallible input.
Budgets. The runtime bounds every run: maximum model calls, maximum tokens, wall-clock timeout, and detection of the same tool call repeating with the same arguments. When a budget is exhausted, the run ends with a partial answer or an escalation, never silently.
Guardrails. Checks in code between the model's proposal and its execution: which tools this user may use, argument limits, rate limits per run, output filters before anything reaches the user. Credentials given to tools are scoped to the current user and task.
Human-in-the-loop. For irreversible or expensive actions the runtime pauses, asks a person, and resumes. Because approval can take minutes or days, run state (conversation, pending action, budget used) is persisted outside the process.
When to use it
- The path through the task genuinely depends on intermediate results.
- Mistakes are cheap to detect and undo, or every risky action can be gated.
- Latency of several seconds to minutes is acceptable.
- You can evaluate outcomes (see the observability lesson), so you know whether the agent is improving.
When not to
- The steps are known in advance: write a workflow and call the model only for the language parts (classify, extract, summarise). It is cheaper, faster and testable.
- Hard latency requirements: each turn costs a full model call.
- Actions are irreversible and cannot be put behind approval.
- One model call with good retrieved context already answers the question.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Agent instead of fixed workflow | Handles unforeseen paths | Latency, cost and variance per run; harder to test |
| More tools | More capability | Worse tool selection, larger prompts, bigger attack surface |
| Tight step budget | Bounded cost and capacity | Some legitimate long tasks stop early |
| Long context instead of summarised memory | Nothing forgotten | Cost and latency on every turn; models use very long contexts less reliably |
| Multi-agent (planner + specialists) | Separation of concerns, smaller prompts | More model calls, coordination failures, harder tracing |
| Human approval | Safety on irreversible actions | Waiting time; needs durable, resumable runs |
Alternatives
- Fixed workflow with model steps: deterministic orchestration (code, a workflow engine or a state machine) that calls the model for specific sub-tasks.
- Single call with retrieval: retrieve context, call once, answer. Covers most question answering.
- Router: one model call classifies the request, then a fixed path handles each class.
Failure modes
- Runaway loops: a failing tool, an ambiguous goal or tools that undo each other keep the loop going. Each run holds a model slot, so a few loops can saturate a shared deployment, as the simulation shows.
- Prompt injection: instructions hidden in tool results, documents, emails or web pages steer the model. Assume it will sometimes succeed and limit what a fooled model can do.
- Wrong tool or wrong arguments: plausible but incorrect calls. Validate arguments against schemas and business rules; make write tools idempotent so retries are safe.
- Context overflow and drift: long runs lose the original goal or exceed the window. Summarise, restate the goal and cap run length.
- Silent partial success: the agent did three of five steps and reported success. Make the runtime, not the model, decide what "done" means where possible.
- Unbounded cost: token usage per run has a long tail. Track it per run and per user.
In production
Keep the agent runtime stateless between turns with run state in a database, so runs survive restarts and can wait for approval. Trace every turn: prompt version, model, tokens, tool calls and results (see AI observability). Put model calls behind an LLM gateway for quotas, fallback and cost tracking. Wrap tools with timeouts, retries with backoff, circuit breakers and idempotency keys like any other remote call. Version prompts and tool descriptions together, and run an evaluation set before changing either. Start with read-only tools and add write tools behind approval.
Common misconceptions
- "The model calls the API." The runtime does. The model only emits a structured request.
- "The system prompt is a security boundary." It is guidance. Enforcement has to be code that runs whatever the model says.
- "Agents remember." They re-read. Memory is retrieval plus prompt assembly.
- "More agents means better results." Each extra agent adds model calls and coordination failure modes; start with one and add structure only when evaluation shows it helps.
- "Loops are a cost problem only." They also hold shared capacity and can take down the agent for everyone.
Interview angle
Expect to sketch the loop and then defend the runtime: where tools execute, how credentials are scoped, how you stop a run (steps, tokens, time, repeated calls), what happens when a tool fails, how state survives a restart or an approval wait, and how you would detect prompt injection and limit its blast radius. Capacity arithmetic stands out: "128 concurrent generations at 4 s per run is about 32 runs per second; if loops push runs to 12 s, we drop to about 11".
Model assumptions
Most of this lesson is a scripted illustration: packets show the order of messages in the agent loop with illustrative timings (model replies 0.8–1.5 s, tool calls about 0.1 s); nothing in those steps is simulated. The three load steps use the queueing simulation with one request per agent run: the runtime does 20 ms of work and calls the LLM once, and the LLM's service time stands for all model calls of the run (about 4 s normally, 12 s with looping, 4.4 s with a budget; lognormal, cv 0.4). The LLM has 128 concurrent slots and room for 128 waiting runs; real deployments release a slot between turns while tools run, which this model ignores. Arrivals are Poisson. Numbers show behaviour and orders of magnitude only, not provider benchmarks.