Why This Matters at Engineering Leadership Scale
Demo agents look impressive when you hand an LLM ten tools inside an open while(true) loop and watch it improvise. In production fintech, healthcare, or enterprise SaaS platforms, that same open loop is a reliability and compliance liability. One malformed webhook or ambiguous ticket comment can send an unbounded agent into a 40-step retry spiral, burning $40 or more in tokens on a single event while firing duplicate writes to downstream APIs.
Worse, auditors under SOC 2 Type II or APRA CPS 234 do not accept "the model decided to close the control" as change-management evidence. At engineering leadership scale, autonomous capabilities must obey the same state-machine discipline, idempotency guarantees, and access boundaries as any payment or ledger service.
Core Mental Model & Architecture
Production agentic systems follow five non-negotiable engineering rules:
- Workflows Over Free-Roaming Loops: Build an explicit Directed Acyclic Graph (DAG) or finite state machine in code. Use LLMs strictly for bounded steps like classification, evidence extraction, and draft synthesis, while application code controls branching and retries.
- Strict Schema-Constrained Outputs: Enforce JSON Schema or Pydantic Structured Outputs at the model decoding layer so every tool invocation and final response parses cleanly against typed contracts before any function runs.
- Idempotency & Step Budgets: Cap maximum reasoning transitions (for example,
max_steps = 5), enforce hard per-run token and dollar circuit breakers, and require anidempotency_keyon every mutating tool call. - Risk-Tiered Human-in-the-Loop (HITL) Gates: Classify every tool into one of three risk tiers and enforce approval boundaries in the workflow orchestrator, never inside the prompt text.
- Immutable Audit Trail: Persist
correlation_id,prompt_version,model_id,input_hash,tool_arguments,tool_result, andapprover_idto an append-only audit store after every step.
| Tool Risk Tier | Examples | Execution Policy | Audit & Rollback Requirement |
|---|---|---|---|
| Tier 1: Read-Only | Fetch Jira ticket, query pgvector runbooks, read PR diff | Auto-execute inside step and token budget | Log input_hash, tool_arguments, and row count |
| Tier 2: Reversible Draft | Save draft summary, add internal triage comment, tag ticket | Auto-execute + notify owner in Slack or UI | Idempotency key required; reversible via single API call |
| Tier 3: High-Blast-Radius Mutation | Close compliance control, refund invoice, merge PR, email client | Pause DAG, persist checkpoint, require explicit HITL approval | Cryptographic approver_id, timestamp, and diff snapshot |
Step-by-Step Implementation Tutorial
Follow these four steps to ship a safe, auditable multi-agent workflow in Python using Pydantic contracts and deterministic state transitions:
- Define Typed Tool Contracts & Risk Tiers: Declare strict Pydantic models for every step output and tag each tool with its execution tier (
READ_ONLY,REVERSIBLE_DRAFT, orHIGH_BLAST_RADIUS). - Wrap Execution in a Bounded Step & Budget Runner: Track
steps_usedandtokens_usedin workflow state. Abort cleanly to a dead-letter state if either ceiling is crossed. - Checkpoint Before Tier 3 Mutations: When the workflow proposes a high-blast-radius action, serialize the validated payload into a
pending_approvalstable with statusAWAITING_HUMANand terminate the worker cleanly. Resume only via an authenticated approval endpoint carrying the humanapprover_id. - Write Append-Only Audit Records After Every Transition: Record exact model versions, prompt versions, hashed inputs, and tool payloads so security and compliance teams can reconstruct every run deterministically.
# agent_workflow.py - Schema-constrained DAG with step budgets & HITL checkpointing
from enum import Enum
from hashlib import sha256
from typing import Literal
from pydantic import BaseModel, Field
class RiskTier(str, Enum):
READ_ONLY = "read_only"
REVERSIBLE_DRAFT = "reversible_draft"
HIGH_BLAST_RADIUS = "high_blast_radius"
class TriageDecision(BaseModel):
control_id: str = Field(pattern=r"^[A-Z]+-\d{2,5}$")
proposed_action: Literal["request_info", "draft_evidence", "close_control"]
risk_tier: RiskTier
rationale: str = Field(max_length=500)
citation_chunk_ids: list[str] = Field(min_length=1)
class WorkflowBudgetExceeded(RuntimeError):
pass
class BoundedComplianceRunner:
def __init__(self, audit_repo, approval_repo, max_steps=5, max_tokens=12_000):
self.audit_repo = audit_repo
self.approval_repo = approval_repo
self.max_steps = max_steps
self.max_tokens = max_tokens
def execute_step(self, ctx, raw_input: str, llm_call, tool_fn):
if ctx.steps_used >= self.max_steps or ctx.tokens_used >= self.max_tokens:
raise WorkflowBudgetExceeded(
f"Run {ctx.correlation_id} breached budget: "
f"steps={ctx.steps_used}, tokens={ctx.tokens_used}"
)
decision, usage = llm_call(raw_input, response_model=TriageDecision)
ctx.steps_used += 1
ctx.tokens_used += usage.total_tokens
input_hash = sha256(raw_input.encode("utf-8")).hexdigest()
if decision.risk_tier == RiskTier.HIGH_BLAST_RADIUS:
checkpoint_id = self.approval_repo.pause_for_human(
correlation_id=ctx.correlation_id,
idempotency_key=f"{ctx.correlation_id}:step:{ctx.steps_used}",
payload=decision.model_dump(),
)
self.audit_repo.append(
correlation_id=ctx.correlation_id,
prompt_version=ctx.prompt_version,
model_id=ctx.model_id,
input_hash=input_hash,
tool_arguments=decision.model_dump(),
tool_result={"status": "AWAITING_HUMAN", "checkpoint_id": checkpoint_id},
approver_id=None,
)
return {"status": "AWAITING_HUMAN", "checkpoint_id": checkpoint_id}
result = tool_fn(
decision,
idempotency_key=f"{ctx.correlation_id}:step:{ctx.steps_used}",
)
self.audit_repo.append(
correlation_id=ctx.correlation_id,
prompt_version=ctx.prompt_version,
model_id=ctx.model_id,
input_hash=input_hash,
tool_arguments=decision.model_dump(),
tool_result=result,
approver_id="SYSTEM_AUTO_TIER_1_2",
)
return {"status": "COMPLETED", "result": result}Notice that even if a prompt injection convinces the LLM to choose close_control, the server-side mapping forces HIGH_BLAST_RADIUS execution through pause_for_human, never allowing direct mutation without human sign-off.
Worked Production Scenario: Before vs. After
An engineering group running a multi-tenant compliance triage platform across 400 enterprise accounts built an agent to inspect GitHub PR diffs and Jira tickets, gather evidence, and update audit controls.
- Before: The initial prototype used an open-ended ReAct agent loop with read and write Jira tools. When a malformed webhook delivered a circular thread of ticket comments, the agent looped 38 times, burned
$43.60in API tokens on a single event, and posted six duplicate comments before timing out. During internal red-teaming, an injected instruction inside a Jira description convinced the agent to transition an open audit control toClosedwithout human review. Security blocked the launch immediately. - After: The team rebuilt the agent as a deterministic 4-step DAG (
Classify -> Retrieve Evidence -> Synthesize Draft -> Propose Action) capped atmax_steps = 5and12,000tokens per run. All outputs were constrained via Pydantic schemas, write tools enforced idempotency keys, control closures paused in an approval queue requiring an authenticatedapprover_id, and every step logged to an append-only Postgres audit table. Worst-case cost per malformed event dropped from$43.60to$0.11, duplicate mutations dropped to zero, and Enterprise Risk signed off for production rollout under SOC 2 and APRA CPS 234.
Common Failure Modes & Anti-Patterns
- Enforcing Approval Rules Inside the System Prompt: Writing "Always ask a human before deleting records" inside prompt text fails the first time indirect prompt injection overrides instructions. Structural Fix: Enforce risk-tier checks and HITL pauses in deterministic orchestrator code outside the model's control, and withhold write credentials from the model runtime entirely until an approval token is present.
- Omitting Idempotency Keys on Agent Tool Calls: Network timeouts cause the workflow engine to retry a tool call, posting duplicate Jira comments, duplicate refunds, or duplicate compliance attestations. Structural Fix: Generate a deterministic
idempotency_keyfrom(correlation_id, step_name)and require every mutating tool endpoint to deduplicate against it. - Mutable or Incomplete Execution Logs: Logging only final answers hides which retrieved chunks, prompt version, or tool arguments led to a bad proposal, making post-incident forensics impossible. Structural Fix: Write every state transition to an append-only audit store capturing
prompt_version,model_id,input_hash, arguments, tool results, andapprover_id.
How to Handle Pushback in the Room
Pushback 1 (Enterprise Security & Risk Lead): "How do we know a malicious Jira ticket will not trick this agent into closing an audit control or modifying production state without oversight?"
Verbatim Response: "We do not rely on prompt instructions to stop unauthorized mutations. Every tool is classified in server-side code by blast radius: read-only lookups and internal drafts run inside a five-step budget, while any state-changing control closure automatically pauses the workflow, persists the schema-validated proposal, and requires an authenticated human approver ID recorded in an append-only audit log."
Pushback 2 (Senior Product Engineer): "If we lock the agent into a four-step state machine with strict schemas, aren't we losing the flexibility of autonomous agents?"
Verbatim Response: "We are keeping the parts where LLMs excel, which are classification, evidence synthesis, and drafting, while moving control flow and permissions back into deterministic code where we can test and audit them. That trade-off lets us pass enterprise security reviews, bound our worst-case token cost per run, and ship to regulated customers this quarter instead of stalling in red-team reviews."
Key Takeaways & This Week's Action Rep
- Default to deterministic state machines and DAGs instead of open
while(true)agent loops in production workloads. - Enforce Pydantic or JSON Schema validation at the decoding layer so malformed arguments never reach tool functions.
- Split tools into Read-Only, Reversible Draft, and High-Blast-Radius Mutation tiers, enforcing Human-in-the-Loop pauses in orchestrator code rather than prompt text.
- Protect every run with
max_steps, token budgets, idempotent tool calls, and an append-only audit trail loggingprompt_version,model_id, andapprover_id.
This Week's Action Rep: Review one existing or proposed AI workflow in your org. List every tool it can invoke, assign each tool to Tier 1, Tier 2, or Tier 3, and add an explicit max_steps and per-run token cap before the next release.