Building Dependable Tool-Using LLM Agents End to End
Machine LearningModel answerLast updated
Explain how an LLM agent invokes tools, keeps calls well-formed, recovers from bad calls, and stops runaway tool loops, with concrete engineering trade-offs.
You are responsible for an LLM-powered agent that completes tasks by invoking external tools (functions or APIs). Walk through the four areas below, in order, as you would in a technical discussion.
Context you may want to clarify first
- Is the model a hosted API with native function calling, or an open-weights model where you control decoding?
- Are the tools read-only, or can some cause side effects (writing records, sending messages, spending money)?
- What does "too long" mean: steps, context tokens, latency, or cost?
- How many tools are there, and how often do they change?
Part 1: The mechanics of tool calling Describe the full path of a tool call: what the model is shown, what it outputs, which component actually runs the tool, and how the result returns to the model.
Part 2: Enforcing the call format How do you make sure calls are valid, for example JSON that conforms to each tool's argument schema?
Part 3: Stability and correcting bad tool use How do you make tool use consistent from run to run? What do you do when the model picks the wrong tool, supplies wrong arguments, or fails to call a tool when it should?
Part 4: Loops that run too long How do you handle an agent whose tool-call loop keeps going without finishing?
Aim for a structured answer that names concrete mechanisms, trade-offs, and failure modes rather than generic advice.
Hints
Hint 1
Start from the right mental model: the model only proposes a call as text or structured output; your application code validates and executes it, then feeds the result back as a new message.
Hint 2
For format control, think in layers: clear schemas and examples in the prompt, constrained decoding or native function-calling modes, then validation with a bounded repair or retry step.
Hint 3
For reliability, first build an evaluation set and categorize failures (wrong tool, wrong args, missing call, unnecessary call) so each gets a targeted fix. For loops, combine hard budgets with detection of repeated calls and a graceful final answer.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: How tool calling works
The model never executes anything. It only produces text (or a structured message) that requests a tool call. The application does the rest.
- Context. The prompt includes each tool's name, description, and argument schema (usually JSON Schema), plus the conversation so far.
- Model output. The model either answers in prose or emits a structured call such as
{"name": "search_orders", "arguments": {"customer_id": "c_123", "status": "open"}}. Many models can emit several independent calls in one turn (parallel calls), which is useful for independent lookups. - Runtime loop. The application parses the output, validates it against the schema, runs the function, and appends the result (or an error) as a tool-result message tied to the call ID. It then calls the model again.
- Termination. The loop ends when the model returns a final answer with no call, or when a limit is hit.
Models learn this behavior through fine-tuning on traces of calls and results (supervised, then often preference or RL on task success), so they learn when to call, which tool to choose, and how to fill arguments. Prompt-only approaches work but are less reliable.
Part 2: Controlling the format
Use defense in depth rather than one trick.
- Schema design. Use clear, verb-based names, tight types, enums instead of free strings, required vs optional fields, and short descriptions that state when not to use the tool. Add one or two examples for tricky arguments. Fewer free-form fields means fewer errors.
- Native function-calling or structured-output mode. Hosted APIs often fine-tune for this and can enforce schemas.
- Constrained decoding. With self-hosted models, use grammar- or schema-guided decoding that masks invalid tokens at each step, which guarantees syntactically valid JSON. Trade-offs: some latency and implementation cost, and it guarantees syntax, not semantics (a valid but wrong
customer_idis still wrong). Overly rigid constraints can also hurt reasoning, so let the model think in free text first, then emit the call. - Validation and repair. Always validate with a real schema validator, plus business rules (does the ID exist, is the date range sane). On failure, try cheap deterministic repairs (strip code fences, fix trailing commas, coerce types), then return a precise error message to the model and allow a bounded retry (typically 1 to 3).
Part 3: Stability and fixing incorrect tool use
Measure first. Build an evaluation set of realistic tasks with expected calls or end states. Track:
- Tool selection accuracy
- Argument accuracy (exact match and semantic match)
- Format validity rate
- Missed-call rate and unnecessary-call rate
- End-to-end task success, steps per task, cost and latency
Label failures by category, since each has a different fix. Run each case multiple times to measure variance, not just a single pass.
Inference-time fixes
- Wrong tool: sharpen descriptions, remove overlapping tools, or add a router (retrieval over tool descriptions or a small classifier) so the model sees only the 5 to 15 relevant tools instead of dozens.
- Wrong arguments: tighten schemas, add enums, add examples, and have the application resolve ambiguous values (look up IDs) instead of asking the model to guess.
- Missing call: strengthen the system instruction, or force a call (tool-choice setting) when the task clearly requires one.
- Errors: return structured, actionable error messages ("
datemust be ISO 8601; gotnext Friday") and permit a limited retry. - Variance: use low temperature (or greedy) for call generation, pin model versions, and keep prompts and tool ordering stable.
Training-time fixes
- Fine-tune on corrected traces, including failure-then-recovery examples, and on hard negatives (cases where no tool should be called).
- Preference or RL training against verifiable outcomes (call executed correctly, task solved).
- Regression-test every model or prompt change against the evaluation set before rollout.
Side-effecting tools. Treat them differently: require confirmation or human approval for destructive or costly actions, use idempotency keys so retries do not duplicate effects, prefer dry-run modes, apply least-privilege credentials, and log every call.
Part 4: Loops that run too long
Hard limits. Cap steps (for example 10 to 25), total tokens, wall-clock time, and spend. Enforce them in the runtime, not in the prompt. When a limit hits, do not just crash: make one final model call with tools disabled asking for the best answer so far and an honest statement of what is incomplete, or escalate to a human.
Detecting unproductive loops.
- Hash each (tool, normalized arguments) pair and flag repeats. Two identical calls with identical results is a strong stall signal.
- Detect oscillation (A, B, A, B) and lack of progress, such as no new information in the last N steps.
- On detection, inject a message ("You already tried this; choose a different approach or answer"), remove the offending tool for this run, or stop.
- Cache identical read-only calls so repeats cost nothing and expose the loop quickly.
Managing context. Long loops bloat the prompt, raising cost and degrading accuracy. Truncate or summarize large tool outputs (return only needed fields, paginate), keep a rolling summary of earlier steps, and store bulky data outside the context with a reference the model can fetch on demand.
Prevention and observability. Better planning prompts, narrower tools, and a clear "done" criterion reduce loops. Trace every step with IDs, and alert on steps-per-task outliers so you find loop patterns in production.
Common mistakes
- Believing the model executes tools, or trusting its arguments without validation.
- Relying only on prompt wording for format instead of layering decoding and validation.
- Retrying without telling the model what went wrong, or retrying non-idempotent actions.
- Giving the agent too many overlapping tools.
- Setting limits only in the prompt, or aborting with no useful partial answer.
- Judging reliability from a handful of manual examples instead of a measured evaluation set.