Anatomy of a Tool-Using LLM Agent and Its Control Flow
Machine LearningModel answerLast updated
Describe the building blocks of a language-model agent, what each is responsible for, and how they cooperate across a multi-step task with safety and evaluation in mind.
You are asked to explain how an agent built around a large language model is put together.
- List the main components of such an agent.
- For each one, say what it is responsible for and what design choices matter.
- Walk through a concrete multi-step task and show how the components hand work to one another from the initial request to the final answer.
State your assumptions up front. For example, say whether the agent runs fully autonomously or with a person approving risky actions, and whether you are describing a single agent or several cooperating ones. Mention how you would keep the agent safe and how you would measure whether it works.
Hints
Hint 1
Start from the loop: the agent observes, decides, acts and observes again. Then ask which parts of the system support each stage of that loop.
Hint 2
Separate what lives inside the model call (reasoning, choosing an action) from what lives outside it (tool execution, storage, permission checks, budgets).
Hint 3
Pick one concrete task, such as researching a question and writing a short report, and trace every component it touches, including what happens when a tool call fails.
Hint 4
Do not forget the unglamorous parts: stopping conditions, cost and step limits, logging, and an evaluation set with both final-answer and trajectory metrics.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
I assume an LLM-centered agent that works mostly autonomously, with human approval required for irreversible or high-risk actions. I describe a single agent first and note multi-agent extensions at the end.
Core components
1. Model (reasoning core). The LLM reads the current context and produces either a next action (a tool call) or a final answer. Design choices: model size versus latency and cost, whether to use native function calling or structured output, temperature (low for reliable tool use), and whether to route easy steps to a smaller model.
2. Instructions (system prompt and policy). These define the goal, the persona, the allowed behaviors, the output format, and when to ask for help or stop. Keep them specific and testable. Vague instructions are a common source of looping or overreach.
3. Tools. Tools are how the agent perceives and changes the world: search, code execution, database queries, APIs, file access. Each has a name, a description, and a typed schema (JSON schema). The model emits a call, the runtime validates arguments against the schema, executes the tool, and returns the result as an observation. Good practice: few, well-named, non-overlapping tools; clear error messages the model can act on; idempotent operations or idempotency keys; timeouts and retries in the runtime rather than in the model.
4. Memory and context management.
- Short-term (working) memory: the running transcript of thoughts, calls and observations inside the context window. It must be trimmed or summarized as it grows, and large tool outputs should be truncated or stored by reference.
- Long-term memory: an external store (vector index, key-value store, relational DB) holding user preferences, past task outcomes and documents. Retrieval is typically embedding similarity plus metadata filters. Decide what to write, when, and how to expire or correct stale entries.
5. Planning and the control loop. The orchestrator runs: build context, call the model, parse the output, execute the tool, append the observation, repeat. Planning styles range from purely reactive (ReAct-style, one step at a time) to plan-then-execute (draft a plan, run steps, re-plan on failure) to reflection (critique and revise). Reactive is flexible but can wander; explicit plans give structure and are easier to inspect. The loop needs stopping conditions: a final answer, a maximum number of steps, a token or cost budget, a wall-clock limit, and loop detection (the same call with the same arguments repeated).
6. Guardrails and permissions. Input checks (prompt-injection screening, PII handling), tool-level permissions (least privilege, read-only by default, scoped credentials), output validation (schema checks, policy filters), sandboxing for code execution, and human-in-the-loop approval for actions like payments, deletions or external emails. Treat all tool output and retrieved text as untrusted data, never as instructions.
7. Observability and evaluation. Log every step: prompt, tool call, arguments, result, latency, tokens and cost, with a trace ID. Evaluate offline on a fixed task set and online with sampled reviews.
How they work together: example
Task: "Find the three most-cited recent papers on topic X and email me a short summary."
- The orchestrator loads the instructions, retrieves relevant user preferences from long-term memory (e.g., preferred summary length), and sends the request to the model.
- The model proposes a plan: search, rank by citations, read abstracts, summarize, send email.
- It calls
search_papers(query, year_min). The runtime validates arguments, runs the call, and returns a list. The result is appended to working memory (truncated to the fields needed). - The model calls
get_citation_countsandfetch_abstractfor candidates. One call times out; the runtime retries once, then returns a clear error. The model adapts and uses a fallback source. - The model drafts the summary. An output check validates length and format.
- The model calls
send_email. The guardrail layer sees an external, irreversible action and pauses for user approval. After approval, the email goes out. - The agent writes a short note to long-term memory (what was requested, which sources worked) and returns the final answer. The full trace is stored.
Each step is bounded by the step and cost budget, so a misbehaving run is cut off rather than looping forever.
Link to the classical view
This maps to perceive-decide-act: tool observations and memory are perception, the model plus planner is the decision-maker, and tools are actuators. Unlike classic RL agents, the policy is a pretrained model steered by prompts and context rather than trained against a reward for this specific environment.
Evaluation
- Outcome metrics: task success rate, answer correctness (rubric or model-graded with spot-checked human labels).
- Trajectory metrics: number of steps, tool-call validity rate, redundant calls, recovery rate after errors.
- Operational metrics: latency percentiles, cost per task, escalation rate to humans.
- Safety tests: red-team prompts, injection attempts inside retrieved documents, permission-boundary tests.
Use a regression suite so prompt or model changes are compared against a baseline.
Trade-offs
- More autonomy increases capability but also risk and cost; use approval gates for high-impact actions.
- Long contexts are simple but expensive and degrade attention; summarization and retrieval are cheaper but lossy.
- Plan-then-execute is predictable but brittle when the environment surprises it; combine with re-planning.
- Multi-agent setups (planner, worker, critic) help with specialization but add coordination overhead and more failure modes, so start with one agent.
Common mistakes
- Giving the agent too many overlapping tools, which causes wrong tool choices.
- No step or budget limits, leading to runaway loops.
- Dumping raw tool output into context, which burns tokens and distracts the model.
- Trusting retrieved content as instructions (prompt injection).
- Evaluating only the final answer and missing wasteful or unsafe trajectories.
- Storing everything in long-term memory without a policy for relevance and expiry.