Library

Volume 2 · Agentic AI Systems

Notebook
Sign in

Section 34

Production Agentic Systems

994 words · about 5 min

34.1 Infinite Loop Prevention

Iteration limits — a hard cap on total agent iterations (e.g., max 50 steps per task); a per-sub-agent call limit (e.g., diagnosis agent max 10 tool calls). On hitting the limit, escalate to a human with a summary of findings rather than silently terminating.

Loop detection — hash each proposed action; if the identical action is proposed twice, flag a potential loop. Watch for oscillation patterns (scale up → scale down → scale up). Circuit-break if the same error recurs 3 times — stop and escalate rather than retrying indefinitely.

class LoopGuard:
    def __init__(self, max_repeats: int = 2):
        self.action_history: list[str] = []
        self.max_repeats = max_repeats

    def check(self, action_signature: str) -> bool:
        """Return True if this action looks like a loop and should be blocked."""
        recent = self.action_history[-6:]
        if recent.count(action_signature) >= self.max_repeats:
            return True
        self.action_history.append(action_signature)
        return False

34.2 Cost Budgets

Track cumulative token usage (input + output) per task. Set a per-task cost ceiling scaled to task priority/value (e.g., a small budget for a routine lookup, a larger one for a P1 incident). When ~80% of budget is consumed, switch to a cheaper model or stop and report rather than continuing to spend unchecked.

class CostBudget:
    def __init__(self, max_usd: float):
        self.max_usd = max_usd
        self.spent_usd = 0.0

    def record(self, input_tokens: int, output_tokens: int, price_per_1k: tuple[float, float]):
        cost = (input_tokens / 1000) * price_per_1k[0] + (output_tokens / 1000) * price_per_1k[1]
        self.spent_usd += cost
        return self.spent_usd

    def should_downgrade(self) -> bool:
        return self.spent_usd >= 0.8 * self.max_usd

    def should_halt(self) -> bool:
        return self.spent_usd >= self.max_usd

34.3 Progress Detection

After every N steps, explicitly evaluate: “Am I making progress?” using metrics like new information gained, hypotheses narrowed, or actions remaining. If there’s no measurable progress across the last 5 steps, force a strategy change or escalate — don’t let the agent grind indefinitely on a dead end.

34.4 Timeout Architecture

Per-tool call:        30 second timeout
Per-agent step:       2 minute timeout
Per-task total:       30 minute timeout (P1) / 60 minute (P2)
Approval wait:        5 minute timeout → escalate

34.5 Failure Recovery

Immediate (automated): a circuit breaker trips and stops routing to the failed component; the system falls back to a simpler deterministic path or queues the item for a human; on-call is alerted.

Root cause analysis: was it LLM reasoning error, a tool/API failure, or a data-quality issue? Each has a distinct fix — improve the prompt/add few-shot examples for reasoning errors, fix the tool implementation and add input/output validation for tool failures, fix the upstream pipeline for data issues.

Prevention: add the failure case to the golden evaluation dataset, implement a regression test for it, add or tighten a guardrail for the specific pattern, and consider adding a dedicated verification step for that class of scenario going forward.

34.6 Top Production Lessons

  1. Start with workflows, add agency gradually. Identify the minority of decision points that genuinely benefit from LLM reasoning; keep the rest deterministic.
  2. Deterministic where possible, agentic where necessary. If/else for known paths, LLM only for ambiguous decisions.
  3. Observability is non-negotiable. Trace every LLM call, tool invocation, and decision point — you will need to debug production issues, and a black-box agent is undebuggable.
  4. Cost explodes without controls. A single runaway agent loop can cost thousands; implement hard limits from day one, not after the first incident.
  5. Human-in-the-loop is not optional for enterprise. Every production-mutating action needs an approval path.
  6. Memory management is the hardest engineering problem, not the reasoning itself. Invest in summarization and structured state early.
  7. Tool reliability determines agent reliability. A flaky downstream API makes an otherwise well-designed agent look unreliable — invest accordingly.
  8. Evaluation is harder than building. Testing a non-deterministic system requires golden datasets, LLM-as-judge, and regression suites — not just unit tests.
  9. Users don’t trust agents initially. Start with transparency (show reasoning), build trust incrementally, then increase autonomy.
  10. Latency is the silent killer. Multi-step agents can take 30+ seconds; use streaming, show progress indicators, and optimize the critical path.
  11. Payer/domain rules (or any frequently-changing external policy) must be updatable without redeployment. Use RAG over policy documents rather than hardcoding rules into prompts or code.
  12. Multi-agent adds complexity exponentially. Start single-agent; only split when a single agent genuinely can’t handle the workflow.

Section 34 — Interview Q&A

Q1: How do you design a multi-agent system that avoids infinite loops and runaway costs? Combine five controls: hard iteration limits (overall and per-sub-agent), cost budgets tracked cumulatively per task with a downgrade threshold before the hard ceiling, progress detection that forces a strategy change after N steps with no measurable progress, loop detection via action-signature hashing plus a circuit breaker on repeated identical errors, and a nested timeout architecture (per-tool-call, per-step, per-task-total, per-approval-wait) so no single layer can hang indefinitely.

Q2: How do you handle agent failures in production end to end? Immediate automated response — circuit breaker trips, fallback to a deterministic path or human queue, on-call alerted. Then root-cause analysis by category (LLM reasoning vs. tool failure vs. data issue), each with a distinct remediation. Then prevention — add the case to the golden eval set, write a regression test, tighten the relevant guardrail, and consider a dedicated verification step for that failure class going forward.

Q3: What metrics do you track for a production agentic system, and how do you evaluate a non-deterministic system? Task completion rate, accuracy/precision-recall on domain-specific outcomes, efficiency (steps taken vs. optimal, tokens consumed, latency), safety (sensitive-data leaks and unauthorized actions — both must be zero), and cost per task. Evaluation methods: golden-dataset regression testing, A/B testing agent-assisted vs. fully-manual outcomes, LLM-as-judge scoring of reasoning traces, periodic human review of a sampled set of agent decisions, and real-time production dashboards tracking all the above continuously rather than only at release time.