Introduction
In financial services, not all transactions are created equal. A $50 domestic transfer requires a fundamentally different processing path than a $5M cross-border wire to a high-risk jurisdiction. Traditional linear LLM chains fail here because they force every input through the same sequence of operations, wasting compute and introducing latency.
LangGraph solves this by enabling stateful, cyclic, and conditionally routed multi-agent systems. By leveraging Conditional Edges, we can dynamically route transactions to specialized sub-agents (Auto-Approval, Enhanced Due Diligence, or Human-in-the-Loop Compliance) based on real-time risk scoring.
This article provides an end-to-end guide to building a real-time Anti-Money Laundering (AML) and Fraud Detection routing engine using LangGraph.
Prerequisites
Before building this system, ensure your environment meets the following requirements:
Python 3.10+
Required for modern type hinting and asyncio performance.
Core Libraries
langgraph>=0.2.0(For stateful graph orchestration)langchain-core,langchain-openai(For LLM interactions and structured output)pydantic>=2.0(For strict state validation, critical in finance)
API Keys
An OpenAI API key (or equivalent endpoint for models like gpt-4o or locally hosted Llama-3) configured via environment variables.
Conceptual Knowledge
Basic understanding of LangGraph nodes, edges, and the StateGraph paradigm.
Observability Setup (Recommended)
A LangSmith account to trace decision paths for regulatory audits.
Installation
pip install langgraph langchain-openai pydantic
The Real-Time Use Case: Cross-Border Payment Triage
Scenario
A payment gateway receives a high-velocity stream of cross-border wire transfers. Each transaction payload includes sender/receiver details, amount, and jurisdiction.
The Goal
Ingest the transaction.
Use an LLM (augmented with deterministic rules) to assign a
risk_level(LOW,MEDIUM,HIGH).Conditionally route the transaction:
LOW: Route to Auto-Approve Agent (sub-100ms latency).
MEDIUM: Route to EDD Agent (Enhanced Due Diligence) to check mock sanctions lists.
HIGH: Route to Compliance Agent, which triggers a Human-in-the-Loop (HITL) interrupt for manual review.
Step 1: Define the Strict State Schema
In financial systems, state must be strictly typed to prevent hallucinated or malformed data from propagating. We use Pydantic.
from typing import TypedDict, Annotated, List, Literal
from pydantic import BaseModel, Field
import operator
# Define the possible risk levels
RiskLevel = Literal["LOW", "MEDIUM", "HIGH"]
Decision = Literal["APPROVED", "FLAGGED_EDD", "PENDING_MANUAL_REVIEW", "REJECTED"]
class TransactionPayload(BaseModel):
tx_id: str = Field(description="Unique transaction identifier")
amount_usd: float = Field(description="Transaction amount in USD")
sender_country: str = Field(description="ISO 3166-1 alpha-3 code of sender")
receiver_country: str = Field(description="ISO 3166-1 alpha-3 code of receiver")
description: str = Field(description="Payment reference or description")
class GraphState(BaseModel):
transaction: TransactionPayload
risk_level: RiskLevel | None = Field(default=None, description="Assessed risk level")
risk_reasoning: str | None = Field(default=None, description="LLM reasoning for the risk score")
edd_checks: List[str] = Field(default_factory=list, description="Results of EDD sanctions checks")
final_decision: Decision | None = Field(default=None, description="Final routing decision")
messages: Annotated[List[str], operator.add] = Field(default_factory=list, description="Audit trail of agent actions")
Step 2: Define the Agent Nodes
Each node represents a specialized agent or function. We will use gpt-4o-mini for fast, structured risk assessment.
import os
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langgraph.graph import StateGraph, END
# Initialize a fast, structured-output-capable LLM
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.0)
# 1. Triage Node: Assesses initial risk
def triage_node(state: GraphState) -> dict:
tx = state.transaction
prompt = ChatPromptTemplate.from_messages([
("system", """You are an expert AML compliance officer. Assess the risk of this transaction.
Rules:
- HIGH: Amount > $100,000 OR involves high-risk jurisdictions (e.g., 'XXX', 'RUS', 'IRN').
- MEDIUM: Amount between $10,000 and $100,000 OR vague payment descriptions.
- LOW: Amount < $10,000 and clear, legitimate descriptions between low-risk countries.
Output ONLY the risk level and a brief reasoning."""),
("human", "Transaction: {tx_data}")
])
# Use structured output for deterministic parsing
class RiskAssessment(BaseModel):
risk_level: RiskLevel
reasoning: str
structured_llm = llm.with_structured_output(RiskAssessment)
chain = prompt | structured_llm
result = chain.invoke({"tx_data": tx.model_dump_json()})
return {
"risk_level": result.risk_level,
"risk_reasoning": result.reasoning,
"messages": [f"[TRIAGE] Assessed risk as {result.risk_level}: {result.reasoning}"]
}
# 2. Auto-Approve Node (LOW Risk)
def auto_approve_node(state: GraphState) -> dict:
return {
"final_decision": "APPROVED",
"messages": [f"[AUTO-APPROVE] Transaction {state.transaction.tx_id} cleared instantly."]
}
# 3. Enhanced Due Diligence Node (MEDIUM Risk)
def edd_node(state: GraphState) -> dict:
tx = state.transaction
# Mock external API call to a sanctions database (e.g., Refinitiv, LexisNexis)
mock_sanctions_check = "CLEAR" if tx.receiver_country != "XXX" else "MATCH_FOUND"
decision = "REJECTED" if mock_sanctions_check == "MATCH_FOUND" else "FLAGGED_EDD"
return {
"edd_checks": [f"Sanctions check on {tx.receiver_country}: {mock_sanctions_check}"],
"final_decision": decision,
"messages": [f"[EDD] Performed sanctions check. Result: {mock_sanctions_check}. Decision: {decision}"]
}
# 4. Compliance / HITL Node (HIGH Risk)
def compliance_node(state: GraphState) -> dict:
# In a real system, this would trigger a LangGraph "interrupt" to pause execution
# and wait for human approval via an external UI/API.
return {
"final_decision": "PENDING_MANUAL_REVIEW",
"messages": [f"[COMPLIANCE] HIGH RISK DETECTED. Halted transaction {state.transaction.tx_id}. Escalated to human reviewer."]
}


Join the conversation! Your thoughts help the community grow.