Skip to article content
FrontendXLesson 11 / 20

Bounded agent workflows: budgets, approvals, audit

Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.

advanced · about 55 minutes · 5 exercises

  • Predict
  • Explain
  • Implement
  • Interview

What you will be able to do

#
  • Implement an agent loop with an explicit step budget that returns structured outcomes for done and budget-exhausted runs.
  • Add an approval gate that halts before executing a side-effecting tool and records the pending decision.
  • Articulate the four answers that separate a production agent from a demo: budget behavior, tool permissions, failure surfacing and audit.

Overview

#

An agent is a loop with authority

Strip the mystique: an agent is a model plus tools plus a loop plus stop conditions. What separates a production agent from a research demo is rarely the model. It is the discipline around the loop: explicit budgets, an allowlisted tool set, permission scopes, approval gates for side effects, and an audit trail of every step. A demo runs once on a happy path with a human watching; an agent runs unattended, so every unbounded quantity becomes an incident waiting for a trigger.

The four budgets

Every agent loop must terminate on its own. Four budgets do that work:

BudgetWhat it capsTypical failure it prevents
Stepsmodel turns in the loopendless tool ping-pong
Tokenscumulative context and outputsilent cost blowups
Wall clocktotal runtimestuck requests holding resources
Tool callscalls per tool, per runa single tool monopolizing the run

Hitting a budget is not an error; it is a designed outcome with a structured result. The loop below returns budget_exhausted with the transcript so the caller can decide what the user sees.

snippet.javascript
function runBoundedAgent(model, tools, task, opts) {
  const messages = [{ role: "user", content: task }];
  const transcript = [];
  for (let step = 1; step <= opts.maxSteps; step++) {
    const out = model(messages);
    if (out.content) {
      transcript.push({ step, type: "final", content: out.content });
      return { status: "done", steps: step, transcript };
    }
    const result = executeToolCall(out.toolCall, tools);
    transcript.push({ step, type: "tool", name: out.toolCall.name });
    messages.push({ role: "assistant", content: "tool_request" });
    messages.push({ role: "tool", content: result });
  }
  return { status: "budget_exhausted", steps: opts.maxSteps, transcript };
}

With a scripted model that searches an order, checks the refund policy, then answers, maxSteps: 3 ends in done after exactly three steps. Set maxSteps: 2 and the same script ends in budget_exhausted with two tool steps in the transcript. Trace both; the transcript is the audit trail.

Approval gates for side effects

Tool validation (lesson 10) stops the model from calling nonexistent tools. It does not decide whether a real action should happen. That decision belongs to a gate:

snippet.javascript
const AGENT_TOOLS = {
  searchOrders: { args: ["query"], run: (a) => ({ orderId: "A-1042", status: "delivered" }) },
  checkRefundPolicy: { args: ["orderId"], run: (a) => ({ orderId: a.orderId, eligible: true }) },
  sendRefundEmail: { args: ["orderId"], requiresApproval: true, run: (a) => ({ sent: true }) }
};

When the model requests a tool marked requiresApproval, the loop does not execute it. It stops with needs_approval, the pending tool name, and the transcript so far. A human (or a separate policy service) approves or rejects, and the run resumes or terminates. The gate converts "the model decided" into "the model proposed, a named authority decided", which is the accountability structure auditors and incident reviews actually need.

What the audit trail must contain

Per step: the model's request, the tool name and arguments, the result or the gate decision, token usage, and timestamps. This is not bureaucracy; it is how you answer "why did the agent do that" after the fact, and it is the raw material for evaluation (lesson 13). Store prompts and results with the same data-boundary care as any other user data (lesson 12): redact what should not persist.

Agents versus demos, stated plainly

A demo shows one scripted path. An agent system must also define:

  1. What happens at each budget limit, in user-visible terms.
  2. Which tools exist, who may call them, and what requires approval.
  3. How failures inside the loop (tool errors, bad model output) surface.
  4. How every run is recorded and reviewed.

If those four answers do not exist in writing and in code, you have a demo, whatever the pitch deck says. This distinction is the course's recurring theme applied to autonomy: uncertainty handled by abstention, grounding handled by retrieval, safety handled by boundaries, and quality handled by evaluation. Autonomy is not a fifth virtue that excuses the other four.

A note on "reasoning"

Models interpolate over patterns; they do not acquire new capabilities mid-run. If the tool to look up order status does not exist, the agent cannot reason its way around it; it will either say so, guess, or loop. Missing capabilities are roadmap items, not prompting problems. Budget the loop, ship the tools the task actually needs, and let the transcript show you which ones the run really used.

Continue with ai-engineering-prompt-injection-and-data-boundaries: agent tool results are an injection carrier. Lesson ai-engineering-evaluation-against-demos turns agent transcripts into graded evidence.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Implement

    Implement runBoundedAgent(model, tools, task, opts) as specified in the lesson body: loop up to opts.maxSteps; on a model reply with content, record a final step and return { status: "done", steps, transcript }; otherwise execute the requested tool, record a tool step, and continue. After the budget, return { status: "budget_exhausted", steps: opts.maxSteps, transcript }. Log { status, steps, transcriptLength } for maxSteps 3 with the scripted model.

    starter.javascript
    function executeToolCall(call, registry) {
      const tool = registry[call.name];
      if (!tool) return { error: "Unknown tool: " + call.name };
      for (const arg of tool.args) {
        if (typeof call.args?.[arg] !== "string" || call.args[arg].length === 0) {
          return { error: "Missing argument: " + arg };
        }
      }
      return tool.run(call.args);
    }
    
    const AGENT_TOOLS = {
      searchOrders: { args: ["query"], run: (a) => ({ orderId: "A-1042", status: "delivered" }) },
      checkRefundPolicy: { args: ["orderId"], run: (a) => ({ orderId: a.orderId, eligible: true }) }
    };
    
    function scriptedModel(messages) {
      const toolCalls = messages.filter((m) => m.role === "tool").length;
      if (toolCalls === 0) return { toolCall: { name: "searchOrders", args: { query: "A-1042" } } };
      if (toolCalls === 1) return { toolCall: { name: "checkRefundPolicy", args: { orderId: "A-1042" } } };
      return { content: "Refund approved for A-1042." };
    }
    
    function runBoundedAgent(model, tools, task, opts) {
      // Loop up to opts.maxSteps. On a reply with content, push a final
      // transcript entry and return { status: "done", steps, transcript }.
      // On a tool request, execute, push a tool transcript entry, continue.
      // After exhausting the budget return
      // { status: "budget_exhausted", steps: opts.maxSteps, transcript }.
    }
    
    const run = runBoundedAgent(scriptedModel, AGENT_TOOLS, "Process refund for order A-1042", { maxSteps: 3 });
    console.log(JSON.stringify({ status: run.status, steps: run.steps, transcriptLength: run.transcript.length }));

    Reveal the reference answer
    reference.javascript
    function executeToolCall(call, registry) {
      const tool = registry[call.name];
      if (!tool) return { error: "Unknown tool: " + call.name };
      for (const arg of tool.args) {
        if (typeof call.args?.[arg] !== "string" || call.args[arg].length === 0) {
          return { error: "Missing argument: " + arg };
        }
      }
      return tool.run(call.args);
    }
    
    const AGENT_TOOLS = {
      searchOrders: { args: ["query"], run: (a) => ({ orderId: "A-1042", status: "delivered" }) },
      checkRefundPolicy: { args: ["orderId"], run: (a) => ({ orderId: a.orderId, eligible: true }) }
    };
    
    function scriptedModel(messages) {
      const toolCalls = messages.filter((m) => m.role === "tool").length;
      if (toolCalls === 0) return { toolCall: { name: "searchOrders", args: { query: "A-1042" } } };
      if (toolCalls === 1) return { toolCall: { name: "checkRefundPolicy", args: { orderId: "A-1042" } } };
      return { content: "Refund approved for A-1042." };
    }
    
    function runBoundedAgent(model, tools, task, opts) {
      const messages = [{ role: "user", content: task }];
      const transcript = [];
      for (let step = 1; step <= opts.maxSteps; step++) {
        const out = model(messages);
        if (out.content) {
          transcript.push({ step, type: "final", content: out.content });
          return { status: "done", steps: step, transcript };
        }
        const result = executeToolCall(out.toolCall, tools);
        transcript.push({ step, type: "tool", name: out.toolCall.name });
        messages.push({ role: "assistant", content: "tool_request" });
        messages.push({ role: "tool", content: result });
      }
      return { status: "budget_exhausted", steps: opts.maxSteps, transcript };
    }
    
    const run = runBoundedAgent(scriptedModel, AGENT_TOOLS, "Process refund for order A-1042", { maxSteps: 3 });
    console.log(JSON.stringify({ status: run.status, steps: run.steps, transcriptLength: run.transcript.length }));

    Authored expected output: {"status":"done","steps":3,"transcriptLength":3}

    The scripted model uses step 1 for searchOrders, step 2 for checkRefundPolicy and step 3 for the final answer, so the run ends done with three transcript entries: two tool steps and one final.

  2. Exercise 2Predict

    With the same scripted model but maxSteps 2, predict the logged { status, steps, transcriptLength } object.

    starter.javascript
    function executeToolCall(call, registry) {
      const tool = registry[call.name];
      if (!tool) return { error: "Unknown tool: " + call.name };
      for (const arg of tool.args) {
        if (typeof call.args?.[arg] !== "string" || call.args[arg].length === 0) {
          return { error: "Missing argument: " + arg };
        }
      }
      return tool.run(call.args);
    }
    
    const AGENT_TOOLS = {
      searchOrders: { args: ["query"], run: (a) => ({ orderId: "A-1042", status: "delivered" }) },
      checkRefundPolicy: { args: ["orderId"], run: (a) => ({ orderId: a.orderId, eligible: true }) }
    };
    
    function scriptedModel(messages) {
      const toolCalls = messages.filter((m) => m.role === "tool").length;
      if (toolCalls === 0) return { toolCall: { name: "searchOrders", args: { query: "A-1042" } } };
      if (toolCalls === 1) return { toolCall: { name: "checkRefundPolicy", args: { orderId: "A-1042" } } };
      return { content: "Refund approved for A-1042." };
    }
    
    function runBoundedAgent(model, tools, task, opts) {
      // The completed implementation from ex1.
      const messages = [{ role: "user", content: task }];
      const transcript = [];
      for (let step = 1; step <= opts.maxSteps; step++) {
        const out = model(messages);
        if (out.content) {
          transcript.push({ step, type: "final", content: out.content });
          return { status: "done", steps: step, transcript };
        }
        const result = executeToolCall(out.toolCall, tools);
        transcript.push({ step, type: "tool", name: out.toolCall.name });
        messages.push({ role: "assistant", content: "tool_request" });
        messages.push({ role: "tool", content: result });
      }
      return { status: "budget_exhausted", steps: opts.maxSteps, transcript };
    }
    
    const run = runBoundedAgent(scriptedModel, AGENT_TOOLS, "Process refund for order A-1042", { maxSteps: 2 });
    console.log(JSON.stringify({ status: run.status, steps: run.steps, transcriptLength: run.transcript.length }));

    Reveal the reference answer
    reference.javascript
    // Predicted output:
    //
    // {"status":"budget_exhausted","steps":2,"transcriptLength":2}
    //
    // Trace: step 1 requests searchOrders and step 2 requests
    // checkRefundPolicy; both execute and both are recorded. The budget is
    // now spent, so the loop returns the structured exhausted outcome with
    // the two tool steps. The scripted final answer at step 3 never runs,
    // which is exactly the point: budgets change outcomes, predictably.

    Authored expected output: {"status":"budget_exhausted","steps":2,"transcriptLength":2}

    Steps 1 and 2 consume the budget on tool calls; the loop exits without a final answer and returns the structured exhausted outcome with the two tool steps as the audit trail. The third scripted behavior never runs.

  3. Exercise 3Implement

    Extend the loop with an approval gate: when the model requests a tool whose spec has requiresApproval true, do not execute it. Return { status: "needs_approval", pendingTool, steps, transcriptLength } immediately. With the approval-scripted model (searchOrders at step 1, sendRefundEmail at step 2) and maxSteps 5, log the result object.

    starter.javascript
    function executeToolCall(call, registry) {
      const tool = registry[call.name];
      if (!tool) return { error: "Unknown tool: " + call.name };
      for (const arg of tool.args) {
        if (typeof call.args?.[arg] !== "string" || call.args[arg].length === 0) {
          return { error: "Missing argument: " + arg };
        }
      }
      return tool.run(call.args);
    }
    
    const AGENT_TOOLS = {
      searchOrders: { args: ["query"], run: (a) => ({ orderId: "A-1042", status: "delivered" }) },
      checkRefundPolicy: { args: ["orderId"], run: (a) => ({ orderId: a.orderId, eligible: true }) },
      sendRefundEmail: { args: ["orderId"], requiresApproval: true, run: (a) => ({ sent: true }) }
    };
    
    function approvalModel(messages) {
      const toolCalls = messages.filter((m) => m.role === "tool").length;
      if (toolCalls === 0) return { toolCall: { name: "searchOrders", args: { query: "A-1042" } } };
      return { toolCall: { name: "sendRefundEmail", args: { orderId: "A-1042" } } };
    }
    
    function runBoundedAgentWithGate(model, tools, task, opts) {
      // Copy runBoundedAgent from ex1, then add the gate: before executing
      // a requested tool, if tools[name].requiresApproval is true, return
      // { status: "needs_approval", pendingTool: name, steps: step,
      //   transcript } immediately, without executing and without recording
      // a tool step.
    }
    
    const run = runBoundedAgentWithGate(approvalModel, AGENT_TOOLS, "Refund order A-1042 and email the customer", { maxSteps: 5 });
    console.log(JSON.stringify({ status: run.status, pendingTool: run.pendingTool, steps: run.steps, transcriptLength: run.transcript.length }));

    Reveal the reference answer
    reference.javascript
    function executeToolCall(call, registry) {
      const tool = registry[call.name];
      if (!tool) return { error: "Unknown tool: " + call.name };
      for (const arg of tool.args) {
        if (typeof call.args?.[arg] !== "string" || call.args[arg].length === 0) {
          return { error: "Missing argument: " + arg };
        }
      }
      return tool.run(call.args);
    }
    
    const AGENT_TOOLS = {
      searchOrders: { args: ["query"], run: (a) => ({ orderId: "A-1042", status: "delivered" }) },
      checkRefundPolicy: { args: ["orderId"], run: (a) => ({ orderId: a.orderId, eligible: true }) },
      sendRefundEmail: { args: ["orderId"], requiresApproval: true, run: (a) => ({ sent: true }) }
    };
    
    function approvalModel(messages) {
      const toolCalls = messages.filter((m) => m.role === "tool").length;
      if (toolCalls === 0) return { toolCall: { name: "searchOrders", args: { query: "A-1042" } } };
      return { toolCall: { name: "sendRefundEmail", args: { orderId: "A-1042" } } };
    }
    
    function runBoundedAgentWithGate(model, tools, task, opts) {
      const messages = [{ role: "user", content: task }];
      const transcript = [];
      for (let step = 1; step <= opts.maxSteps; step++) {
        const out = model(messages);
        if (out.content) {
          transcript.push({ step, type: "final", content: out.content });
          return { status: "done", steps: step, transcript };
        }
        const requested = out.toolCall.name;
        if (tools[requested] && tools[requested].requiresApproval) {
          return { status: "needs_approval", pendingTool: requested, steps: step, transcript };
        }
        const result = executeToolCall(out.toolCall, tools);
        transcript.push({ step, type: "tool", name: requested });
        messages.push({ role: "assistant", content: "tool_request" });
        messages.push({ role: "tool", content: result });
      }
      return { status: "budget_exhausted", steps: opts.maxSteps, transcript };
    }
    
    const run = runBoundedAgentWithGate(approvalModel, AGENT_TOOLS, "Refund order A-1042 and email the customer", { maxSteps: 5 });
    console.log(JSON.stringify({ status: run.status, pendingTool: run.pendingTool, steps: run.steps, transcriptLength: run.transcript.length }));

    Authored expected output: {"status":"needs_approval","pendingTool":"sendRefundEmail","steps":2,"transcriptLength":1}

    Step 1 executes searchOrders and records one transcript entry. Step 2 requests sendRefundEmail, which requires approval, so the loop halts before executing and before recording a tool step, leaving transcriptLength 1. The side effect is now a pending human decision, not a model decision.

  4. Exercise 4Interview

    Interview question: design a bounded agent that processes refund requests for an e-commerce support team. Walk through your tool set, budgets, permission model, approval gates, failure handling and how you would evaluate it before rollout.

    Reveal the reference answer
    reference.text
    A strong answer covers: (1) Tools: searchOrders and checkRefundPolicy as read-only; issueRefund and sendRefundEmail as side-effecting with requiresApproval true; no tool that can modify user records. (2) Budgets: maxSteps around 6, a token ceiling per run, a wall-clock timeout, and per-tool call caps; every limit returns a structured outcome the UI can render. (3) Permissions: the agent identity can read orders but can only propose refunds; approval lands with a human or a policy service, and the audit trail records requester, approver, arguments and outcome. (4) Failures: tool errors follow the retry taxonomy, non-retryable errors end the run with a clear user-facing state, and the budget-exhausted path offers escalation to a human. (5) Evaluation: an eval set of refund scenarios including ineligible orders, missing orders, conflicting policy and injection attempts through order notes; deterministic graders for abstention and citation, plus review of transcripts. Weak answers skip budgets, let the model execute refunds directly, or claim the demo proves reliability.

    Authored expected output: A structured design covering tools, budgets, permissions, approval gates, failure handling and an evaluation plan

    The question tests whether the candidate designs for the unattended case. The strongest signal is treating autonomy as a set of explicit, audited decisions rather than a demo.

  5. Exercise 5Explain

    Knowledge check: which combination is the minimum that separates a production agent from a demo?

    starter.text
    // Choose the correct option.

    Reveal the reference answer
    reference.text
    Explicit budgets with structured outcomes, an allowlisted tool set with permission scopes and approval gates for side effects, defined failure surfacing, and a per-step audit trail. A demo exercises none of these because it runs once on a happy path with a human watching.

    Authored expected output: Budgets, allowlisted permissions with approval gates, failure surfacing and audit

    Model choice and prompt quality matter, but they are not the boundary between demo and production; governance of the loop is.

Common misconceptions

#
  • Myth: agents can reason their way around missing tools. Fact: without the tool, the run can only answer from memory, guess or loop; capabilities are roadmap items, not prompt tricks.
  • Myth: more steps and more autonomy always help. Fact: each extra step multiplies failure surface and cost; budgets exist because most runs need few steps.
  • Myth: a successful demo proves the agent is production-ready. Fact: production readiness is defined by budget behavior, permissions, failure paths and audit trails, none of which a demo exercises.

Follow-up practice

#
  • ai-engineering-prompt-injection-and-data-boundaries
  • ai-engineering-evaluation-against-demos

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.