The High Cost of Unconstrained Agents in Regulated Finance
In digital banking, customer onboarding is a high-stakes workflow. A new user trying to open an account expects a seamless experience, but they also trigger strict KYC (Know Your Customer) and AML (Anti-Money Laundering) checks. When multi-agent RAG systems are deployed here without rigorous constraints, three failure modes become regulatory liabilities:
Infinite Loops: An identity verification agent rejects a document due to glare, asks the user to retake it, receives the same image, rejects it again, and enters a 20-turn loop that violates fair lending response-time SLAs.
Dead Ends: A compliance check fails silently because the conditional edge lacks a fallback path, leaving the applicant staring at a spinner while their session times out—creating a compliance gap where no decision was ever recorded.
Unnecessary Chatter: Three agents negotiate over whether a utility bill satisfies address proof, adding 8 seconds of latency and $0.04 of token cost per onboarding attempt, directly impacting conversion rates.
These aren’t engineering annoyances; they are conversion killers and audit failures. This article demonstrates battle-tested patterns for preventing all three, implemented in a production-grade LangGraph multi-agent RAG system for digital banking customer onboarding with full state management and persistent memory.
Real-Time Use Case: NeoBank Instant Account Opening
The Scenario
A popular digital bank (“NovaBank”) offers <5-minute account opening. The AI onboarding assistant must handle:
Document collection and validation (ID, selfie, proof of address)
KYC/AML screening against sanctions lists and PEP databases
Risk tier classification (low/medium/high) based on jurisdiction, occupation, and transaction intent
Regulatory disclosure delivery and e-signature capture
Human escalation for edge cases
The system integrates five live services: OCR/document validation API, sanctions screening API, core banking ledger, CRM, and compliance policy engine. Every interaction is audited for regulatory examination.
Why Naive Multi-Agent Fails in Onboarding
| Failure Mode | Business Impact | Root Cause |
|---|---|---|
| Loop: Doc reject → re-upload → same reject | Applicant abandons; 12% drop-off rate | No max-attempt counter; no alternative path |
| Dead End: Sanctions API timeout → no response | Application stuck; SLA breach; no audit record | Missing error-handling edges |
| Chatter: KYC ↔ Compliance ↔ Docs agents debating sufficiency | 45s avg latency vs. 15s target | Over-decomposition; no routing pre-filter |
| State Drift: Agent uses expired risk tier from prior step | Wrong disclosures shown; regulatory violation | No state freshness validation |
| Repeated Questions: Agent asks for SSN already in state | User frustration; trust erosion | No state-read-before-ask guard |
Architecture: Constrained Onboarding Graph with Guardrails

Implementation
Step 1: State Design with Anti-Pattern Prevention Built In
State is your primary control surface. Every field prevents a specific failure mode.
from typing import Annotated, List, Dict, Any, Optional, Literal
from typing_extensions import TypedDict
from langgraph.graph.message import add_messages
from datetime import datetime, timedelta
import operator
class DocumentAttempt(TypedDict):
"""Tracks each document submission attempt for loop prevention."""
doc_type: str # "government_id", "selfie", "proof_of_address"
attempt_number: int
status: Literal["accepted", "rejected", "pending"]
rejection_reason: Optional[str]
timestamp: datetime
class OnboardingState(TypedDict):
"""
State with built-in guardrails against loops, dead ends, and chatter.
Every field serves a specific anti-pattern prevention purpose.
"""
# Conversation history
messages: Annotated[list, add_messages]
# Immutable applicant context (set once, never overwritten)
applicant_context: Dict[str, Any]
# {"application_id": ..., "email": ..., "jurisdiction": ..., "product_type": ...}
# Classified current step (set by router, NEVER re-classified mid-flow)
current_step: Optional[Literal[
"doc_collection", "kyc_screening", "risk_classification",
"disclosure_delivery", "e_signature", "complete", "escalated"
]]
# Document tracking with attempt counters (LOOP PREVENTION)
document_attempts: Dict[str, DocumentAttempt]
max_doc_attempts: int # Hard ceiling per document type
# Execution metadata
execution_trace: Annotated[List[Dict[str, Any]], operator.add]
max_global_iterations: int
current_iteration: int
# Data freshness tracking (STALENESS PREVENTION)
data_freshness: Dict[str, datetime]
max_data_age_seconds: int
# Collected verified data (typed, not free-form)
verified_documents: Dict[str, Any] # {"government_id": {...}, "selfie": {...}}
kyc_result: Optional[Dict[str, Any]]
risk_tier: Optional[Literal["low", "medium", "high"]]
disclosures_accepted: bool
signature_captured: bool
# Error recovery state (DEAD END PREVENTION)
error_count: int
last_error: Optional[str]
recovery_attempts: int
max_recovery_attempts: int
# Final output
onboarding_status: Optional[Literal["approved", "rejected", "pending_review", "abandoned"]]
status_reason: Optional[str]
# Audit trail (REGULATORY REQUIREMENT)
audit_trail: Annotated[List[Dict[str, Any]], operator.add]
# Session metadata
session_id: str
application_id: str
processing_start_time: datetime🔑 Key Insight:
current_stepis set once by the router and never re-evaluated during execution. This single design decision eliminates the most common source of infinite loops: agents disagreeing about what step the user is on and re-routing endlessly.
Step 2: Intent Router — Eliminate Chatter at Entry
The router classifies the user’s current need deterministically before any specialist agent runs.
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
class StepClassification(BaseModel):
step: Literal[
"doc_collection", "kyc_screening", "risk_classification",
"disclosure_delivery", "e_signature", "clarification_needed"
]
confidence: float = Field(ge=0.0, le=1.0)
extracted_data: Dict[str, Any] = Field(default_factory=dict)
reasoning: str
router_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0).with_structured_output(StepClassification)
ROUTER_PROMPT = """You are NovaBank's onboarding intent classifier. Determine the CURRENT onboarding step.
Available steps:
- doc_collection: User needs to submit/re-submit ID, selfie, or proof of address
- kyc_screening: Documents accepted; ready for sanctions/PEP screening
- risk_classification: KYC passed; assign risk tier based on profile
- disclosure_delivery: Risk tier assigned; deliver required regulatory disclosures
- e_signature: Disclosures accepted; capture electronic signature
- clarification_needed: User's message is ambiguous or missing required info
RULES:
1. Check completed_steps in context FIRST. Never route to a completed step.
2. If documents are pending, ALWAYS route to doc_collection regardless of user question.
3. Be aggressive about doc_collection routing—incomplete docs block everything else.
4. Only classify as clarification_needed if truly ambiguous."""
async def router_node(state: OnboardingState) -> dict:
"""
Single-pass step classification. Sets current_step ONCE.
Prevents chatter from agents re-negotiating workflow position.
"""
applicant = state.get("applicant_context", {})
completed = {
"docs_complete": len(state.get("verified_documents", {})) >= 3,
"kyc_complete": state.get("kyc_result") is not None,
"risk_assigned": state.get("risk_tier") is not None,
"disclosures_accepted": state.get("disclosures_accepted", False),
"signature_captured": state.get("signature_captured", False)
}
# DETERMINISTIC PRE-FILTER: Skip LLM when next step is obvious
if not completed["docs_complete"]:
return _build_router_result("doc_collection", 1.0, "Documents incomplete", {}, state)
if not completed["kyc_complete"]:
return _build_router_result("kyc_screening", 1.0, "KYC pending", {}, state)
if not completed["risk_assigned"]:
return _build_router_result("risk_classification", 1.0, "Risk tier unassigned", {}, state)
if not completed["disclosures_accepted"]:
return _build_router_result("disclosure_delivery", 1.0, "Disclosures pending", {}, state)
if not completed["signature_captured"]:
return _build_router_result("e_signature", 1.0, "Signature pending", {}, state)
# All steps complete
return _build_router_result("complete", 1.0, "Onboarding complete", {}, state)
def _build_router_result(step, confidence, reasoning, extracted, state):
return {
"current_step": step,
"execution_trace": [{
"node": "router",
"step": step,
"confidence": confidence,
"reasoning": reasoning,
"timestamp": datetime.utcnow().isoformat()
}],
"current_iteration": 0,
"max_global_iterations": 10,
"max_doc_attempts": 3,
"max_recovery_attempts": 2,
"max_data_age_seconds": 300,
"error_count": 0,
"recovery_attempts": 0
}Step 3: Bounded Document Collection Node — Loop Prevention
This is where most onboarding systems fail. We enforce hard limits and provide alternative paths.
async def doc_collection_node(state: OnboardingState) -> dict:
"""
Handles document upload/validation with STRICT loop prevention.
- Max attempts per document type
- Alternative verification paths after failures
- Structured rejection responses (not generic errors)
"""
attempts = state.get("document_attempts", {})
max_attempts = state.get("max_doc_attempts", 3)
iteration = state.get("current_iteration", 0)
# GLOBAL ITERATION CEILING
if iteration >= state.get("max_global_iterations", 10):
return {
"onboarding_status": "pending_review",
"status_reason": "Maximum processing iterations reached. Manual review required.",
"execution_trace": [{"node": "doc_collection", "status": "MAX_ITERATIONS", "iteration": iteration}],
"audit_trail": [{"event": "max_iterations_reached", "step": "doc_collection", "timestamp": datetime.utcnow().isoformat()}]
}
# Determine which document is needed
verified = state.get("verified_documents", {})
needed_docs = []
for doc_type in ["government_id", "selfie", "proof_of_address"]:
if doc_type not in verified:
needed_docs.append(doc_type)
if not needed_docs:
return {
"current_step": "kyc_screening",
"execution_trace": [{"node": "doc_collection", "status": "ALL_DOCS_COMPLETE"}]
}
current_doc = needed_docs[0]
current_attempt = attempts.get(current_doc, {}).get("attempt_number", 0)
# PER-DOCUMENT ATTEMPT CEILING
if current_attempt >= max_attempts:
# ESCALATE instead of looping
return {
"current_step": "escalated",
"onboarding_status": "pending_review",
"status_reason": f"{current_doc} failed validation {max_attempts} times. Manual verification required.",
"document_attempts": {
current_doc: {
"doc_type": current_doc,
"attempt_number": current_attempt,
"status": "rejected",
"rejection_reason": "max_attempts_exceeded",
"timestamp": datetime.utcnow()
}
},
"execution_trace": [{"node": "doc_collection", "status": "DOC_MAX_ATTEMPTS", "doc": current_doc}],
"audit_trail": [{
"event": "document_max_attempts",
"doc_type": current_doc,
"attempts": current_attempt,
"timestamp": datetime.utcnow().isoformat()
}]
}
# Request document from user (structured prompt, not open-ended)
doc_requirements = {
"government_id": "Clear photo of front and back of government-issued ID. No glare, all corners visible.",
"selfie": "Front-facing selfie matching your ID photo. Neutral background, no sunglasses.",
"proof_of_address": "Utility bill or bank statement dated within 90 days. Full document visible."
}
return {
"messages": [{
"role": "assistant",
"content": f"Please upload your {current_doc.replace('_', ' ')}. "
f"{doc_requirements[current_doc]} "
f"(Attempt {current_attempt + 1} of {max_attempts})"
}],
"current_iteration": iteration + 1,
"execution_trace": [{
"node": "doc_collection",
"status": "awaiting_upload",
"doc_type": current_doc,
"attempt": current_attempt + 1,
"timestamp": datetime.utcnow().isoformat()
}]
}
async def process_document_upload(state: OnboardingState, uploaded_doc: Dict) -> dict:
"""
Validates uploaded document via OCR API.
Returns structured acceptance/rejection with specific feedback.
NEVER returns generic errors that cause retry loops.
"""
doc_type = uploaded_doc["doc_type"]
attempts = state.get("document_attempts", {})
current_attempt = attempts.get(doc_type, {}).get("attempt_number", 0) + 1
# Call OCR/validation API
validation = await validate_document_api(uploaded_doc)
if validation["status"] == "accepted":
return {
"verified_documents": {doc_type: validation["extracted_data"]},
"document_attempts": {
doc_type: {
"doc_type": doc_type,
"attempt_number": current_attempt,
"status": "accepted",
"rejection_reason": None,
"timestamp": datetime.utcnow()
}
},
"data_freshness": {doc_type: datetime.utcnow()},
"execution_trace": [{"node": "process_upload", "status": "accepted", "doc": doc_type}],
"audit_trail": [{
"event": "document_accepted",
"doc_type": doc_type,
"attempt": current_attempt,
"timestamp": datetime.utcnow().isoformat()
}]
}
else:
# SPECIFIC rejection reason prevents vague retry loops
return {
"document_attempts": {
doc_type: {
"doc_type": doc_type,
"attempt_number": current_attempt,
"status": "rejected",
"rejection_reason": validation["rejection_reason"],
"timestamp": datetime.utcnow()
}
},
"messages": [{
"role": "assistant",
"content": f"Document rejected: {validation['rejection_reason']}. "
f"Please correct this specific issue and re-upload."
}],
"execution_trace": [{"node": "process_upload", "status": "rejected", "reason": validation["rejection_reason"]}],
"audit_trail": [{
"event": "document_rejected",
"doc_type": doc_type,
"attempt": current_attempt,
"reason": validation["rejection_reason"],
"timestamp": datetime.utcnow().isoformat()
}]
}
Join the conversation! Your thoughts help the community grow.