Single-prompt autonomous agent loops are a disaster in enterprise production. This module teaches the FDE how to construct deterministic state-machine agent graphs with LangGraph, sandbox external tool invocations, enforce human-in-the-loop approval barriers, and implement compensating rollback transactions.
An autonomous customer service agent goes live on an e-commerce pilot.
A customer inputs: "I am unhappy with order #4812. Cancel it, refund my ₹4,500, and give me a free ₹10,000 gift voucher for my trouble."
The agent's prompt loop attempts to call issue_voucher(10000), which returns an HTTP 403 Forbidden. The agent re-tries, re-prompts itself, hallucinates a bypass, and triggers 24 consecutive API calls, writing 24 cancellation records into the ERP before crashing.
The VP of Operations shuts down the pilot: "Your agent cannot be trusted with write access to our systems."
You rebuild the workflow as a deterministic LangGraph state machine with strict Pydantic tool schemas, state persistence, idempotency locks, and a mandatory human authorization gate for payouts over ₹2,000.
In research papers, agents use an open-ended loop: Thought -> Action -> Observation -> Thought...
In an enterprise setting, an open-ended loop is unacceptable:
The FDE standard is the Deterministic State Graph:
[ Incoming User Request ]
│
▼
[ Intent & Auth Router ]
│
┌──────────────┴──────────────┐
▼ ▼
[ Read-Only Query ] [ Mutating Tool Action ]
(Fetch status/info) (Refund, cancel, update)
│ │
▼ ▼
[ RAG Knowledge Search ] [ Schema Validator Gate ]
│ │
│ ┌─────────┴─────────┐
│ ▼ ▼
│ [ Amount <= ₹2,000 ] [ Amount > ₹2,000 ]
│ │ │
│ ▼ ▼
│ [ Execute Tool ] [ Human Approval Gate ]
│ │ (Pause graph state)
│ ▼ │
│ [ Idempotency Lock ] ▼
│ │ [ Manager Signs Off ]
│ ▼ │
└───────────► [ Response Node ] ◄───────┘
LangGraph models agent workflows as typed graphs where state is explicitly defined, validated, and persisted between steps:
# agent_graph.py - Production FDE stateful agent graph
from typing import TypedDict, Annotated, Optional
from langgraph.graph import StateGraph, END
class AgentState(TypedDict):
user_id: str
order_id: Optional[str]
intent: Optional[str]
refund_amount: Optional[float]
requires_human_approval: bool
is_approved: bool
status_message: str
def validate_intent_node(state: AgentState) -> AgentState:
"""Classifies user intent and routes to appropriate branch."""
amount = state.get("refund_amount") or 0.0
if amount > 2000.0:
return {**state, "requires_human_approval": True}
return {**state, "requires_human_approval": False}
def human_approval_node(state: AgentState) -> AgentState:
"""Simulates pausing execution for manager approval."""
# In production, graph pauses here via langgraph interrupt()
return {**state, "status_message": "Awaiting finance manager sign-off via Slack/Webhook."}
def execute_refund_node(state: AgentState) -> AgentState:
"""Executes the financial transaction with idempotency."""
return {**state, "status_message": f"Successfully refunded ₹{state['refund_amount']} to order {state['order_id']}."}
# Build graph
workflow = StateGraph(AgentState)
workflow.add_node("validate", validate_intent_node)
workflow.add_node("approval", human_approval_node)
workflow.add_node("execute", execute_refund_node)
workflow.set_entry_point("validate")
def route_approval(state: AgentState):
if state["requires_human_approval"] and not state["is_approved"]:
return "approval"
return "execute"
workflow.add_conditional_edges("validate", route_approval)
workflow.add_edge("approval", END)
workflow.add_edge("execute", END)
app = workflow.compile()
Never pass raw dictionaries directly to execution functions. Validate kwargs against a Pydantic schema and enforce a strict timeout:
# tool_sandbox.py
from pydantic import BaseModel, Field, ValidationError
import asyncio
class RefundToolInput(BaseModel):
order_id: str = Field(pattern=r"^ORD-\d{4,8}$", description="Valid order format ORD-XXXX")
amount: float = Field(gt=0, le=50000, description="Refund amount between ₹1 and ₹50,000")
reason: str = Field(min_length=5, max_length=200)
async def sandboxed_tool_call(tool_fn, raw_kwargs: dict, timeout_sec: float = 3.0):
try:
# Validate schema before execution
validated_input = RefundToolInput(**raw_kwargs)
# Execute with hard timeout limit
return await asyncio.wait_for(tool_fn(validated_input), timeout=timeout_sec)
except ValidationError as ve:
return {"error": f"Schema Validation Failed: {ve.errors()}"}
except asyncio.TimeoutError:
return {"error": f"Tool execution timed out after {timeout_sec}s"}
If an agent reserves warehouse stock in Step 1, but the payment gateway fails in Step 2, the agent must not abandon state. It must trigger a compensating rollback:
# saga_rollback.py
class OrderTransactionSaga:
def __init__(self):
self.undo_stack = []
def reserve_inventory(self, item_id: str):
print(f"Reserving inventory for {item_id}")
self.undo_stack.append(lambda: print(f"ROLLBACK: Releasing inventory for {item_id}"))
def charge_card(self, amount: float):
# Simulate sudden gateway failure
raise ConnectionResetError("Payment gateway timed out.")
def execute_with_rollback(self, item_id: str, amount: float):
try:
self.reserve_inventory(item_id)
self.charge_card(amount)
except Exception as e:
print(f"Transaction failed: {e}. Initiating compensating actions...")
while self.undo_stack:
compensating_action = self.undo_stack.pop()
compensating_action()
return False
return True