AI Agents8 min read

Building a Fraud Review Agent with LangGraph

A LangGraph tutorial: rules and a scikit-learn model score each transaction, an LLM only summarises evidence, and interrupt() hands unclear cases to an analyst.

By AI Agents DirectoryLast checked
Abstract diagram-style background pattern

Most “AI fraud agent” tutorials put a large language model in the middle of the payment decision. That is the wrong place for it. A card authorisation has to be answered quickly and consistently, and a chat model is slow, costs money per call, and can give different answers to the same input. This tutorial builds a fraud review workflow in LangGraph where deterministic rules and a trained scikit-learn classifier make the automatic calls, an LLM is used only to write a readable evidence summary, and a human analyst decides every case the model is unsure about.

All code below is illustrative. It follows the current LangGraph and scikit-learn documentation, but the features, thresholds and rules are placeholders you would replace with your own data and policies. For how a large bank describes its own fraud work, see how JPMorgan Chase uses AI against fraud.

The shape of the workflow

StepWho or what decidesRuns in the payment path?
Hard rules (limits, blocked merchants, sanctioned countries)Your codeYes
Risk scorescikit-learn classifierYes
Low risk: approve, high risk: declineThresholds you setYes
Medium risk: hold the paymentThresholds you setYes
Evidence summaryLLMNo
Final call on held casesHuman analystNo

LangGraph fits this because, in its own words, it lets you “mix deterministic steps with LLM-driven steps in the same graph”, and it ships persistence and human-in-the-loop pausing as runtime features rather than things you build yourself.

Step 1: train and save the scorer

scikit-learn’s HistGradientBoostingClassifier is a good fit for tabular transaction features. Its documentation says it learns how to route missing values at each split, so you don’t need to impute every gap, and it is much quicker than the older GradientBoostingClassifier on datasets of ten thousand rows or more. Fraud labels are heavily imbalanced, so the class_weight="balanced" option, which reweights classes inversely to how often they appear, is worth trying.

# train.py (illustrative)
import skops.io as sio
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.calibration import CalibratedClassifierCV

base = HistGradientBoostingClassifier(class_weight="balanced", random_state=0)
model = CalibratedClassifierCV(base, method="isotonic", cv=5)
model.fit(X_train, y_train)          # your engineered features and fraud labels
sio.dump(model, "fraud_model.skops")

Two choices here deserve a note. First, the thresholds later in the graph treat the output of predict_proba as a probability. scikit-learn explains that only a well calibrated classifier gives scores you can read as a confidence level, and its CalibratedClassifierCV fits a sigmoid or isotonic calibrator on cross-validated predictions. Check calibration curves on held-out data before you trust any threshold.

Second, the model file format. scikit-learn warns that pickle, joblib and cloudpickle files can run arbitrary code when loaded and should only come from a trusted, verified source. skops.io loads only types you explicitly trust, which is safer for an artefact that moves between teams. The docs also say loading a model saved with a different scikit-learn version is unsupported, so pin the version in the serving image.

Step 2: define the state and the fast nodes

A LangGraph graph is built from a shared state schema, nodes that read state and return partial updates, and edges that pick the next node. The state here is a TypedDict.

# graph.py (illustrative)
from typing_extensions import TypedDict
import skops.io as sio

class CaseState(TypedDict, total=False):
    txn: dict            # raw transaction fields
    features: list[float]
    rule_hits: list[str]
    score: float
    status: str          # approved | declined | held | confirmed_fraud | released
    summary: str
    analyst: dict

untrusted = sio.get_untrusted_types(file="fraud_model.skops")
# Review `untrusted` once at build time; only load if you recognise every type.
MODEL = sio.load("fraud_model.skops", trusted=untrusted)

BLOCKED_COUNTRIES = {"XX"}            # placeholder
SINGLE_TXN_LIMIT = 10_000             # placeholder, in account currency
LOW, HIGH = 0.05, 0.90                # placeholders: set from validation data

def check_rules(state: CaseState):
    t, hits = state["txn"], []
    if t["amount"] > SINGLE_TXN_LIMIT:
        hits.append("over_single_txn_limit")
    if t["country"] in BLOCKED_COUNTRIES:
        hits.append("blocked_country")
    return {"rule_hits": hits}

def score(state: CaseState):
    feats = build_features(state["txn"])   # your feature code
    p = float(MODEL.predict_proba([feats])[0][1])
    return {"features": feats, "score": p}

def route(state: CaseState) -> str:
    if state["rule_hits"] or state["score"] >= HIGH:
        return "decline"
    if state["score"] < LOW:
        return "approve"
    return "hold"

Rules run first and win outright: a hard limit should never be overridden by a model score. Nothing in these three functions calls a network service, which is what keeps the decision path fast.

Step 3: the slow branch, with the LLM and the analyst

Only held transactions go further. The summarise node calls a chat model through LangChain’s init_chat_model. The prompt asks for a plain description of the evidence and explicitly forbids a verdict. The model never sees an “approve” or “decline” tool, so it cannot act on the payment.

from pydantic import BaseModel
from langchain.chat_models import init_chat_model
from langgraph.types import interrupt

llm = init_chat_model("claude-sonnet-4-6")   # any supported provider

def approve(state: CaseState):
    return {"status": "approved"}

def decline(state: CaseState):
    return {"status": "declined"}

def hold(state: CaseState):
    publish_status(state["txn"]["id"], "held")   # your queue; make it idempotent
    return {"status": "held"}

def summarise(state: CaseState):
    prompt = (
        "Summarise the evidence for a fraud analyst in five bullet points. "
        "Do not recommend a decision.\n"
        f"Transaction: {state['txn']}\nModel score: {state['score']:.3f}\n"
        f"Recent history: {load_history(state['txn']['account_id'])}"
    )
    return {"summary": llm.invoke(prompt).content}

class AnalystDecision(BaseModel):
    fraud: bool
    note: str | None = None

def analyst_review(state: CaseState):
    decision = interrupt(
        {"txn_id": state["txn"]["id"], "score": state["score"],
         "summary": state["summary"]},
        response_schema=AnalystDecision,
    )
    return {"analyst": decision.model_dump(),
            "status": "confirmed_fraud" if decision.fraud else "released"}

interrupt() is the human checkpoint. The LangGraph docs describe what happens when it fires: the run stops at that line, the current state is written by the checkpointer, the payload goes back to the caller, and the graph waits with no time limit until it is resumed. Passing response_schema (available from langgraph 1.2.12) makes LangGraph validate the analyst’s reply against the Pydantic model, so a malformed decision raises an error instead of slipping through.

Step 4: wire the graph and add persistence

from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.postgres import PostgresSaver

builder = StateGraph(CaseState)
for name, fn in [("check_rules", check_rules), ("score", score),
                 ("approve", approve), ("decline", decline), ("hold", hold),
                 ("summarise", summarise), ("analyst_review", analyst_review)]:
    builder.add_node(name, fn)

builder.add_edge(START, "check_rules")
builder.add_edge("check_rules", "score")
builder.add_conditional_edges("score", route,
    {"approve": "approve", "decline": "decline", "hold": "hold"})
builder.add_edge("approve", END)
builder.add_edge("decline", END)
builder.add_edge("hold", "summarise")
builder.add_edge("summarise", "analyst_review")
builder.add_edge("analyst_review", END)

DB_URI = "postgresql://..."
with PostgresSaver.from_conn_string(DB_URI) as checkpointer:
    checkpointer.setup()          # creates the checkpoint tables on first run
    graph = builder.compile(checkpointer=checkpointer)
    run_worker(graph)             # your loop that consumes transactions

Install the Postgres saver with pip install -U "psycopg[binary,pool]" langgraph langgraph-checkpoint-postgres.

The conditional edge calls route after score runs and maps its return value to the next node. Interrupts need a checkpointer and a thread_id. InMemorySaver is fine in a notebook, but it keeps checkpoints in RAM, so a restart would lose every case waiting for review. The LangGraph persistence page points to PostgresSaver for production, recommends keeping thread IDs below 255 characters, and suggests pruning old checkpoints on a schedule.

Step 5: run a transaction and resume after review

Use the transaction ID as the thread ID, so the analyst’s answer always lands on the right case.

from langgraph.types import Command

config = {"configurable": {"thread_id": txn["id"]}}
result = graph.invoke({"txn": txn}, config)

if "__interrupt__" in result:
    send_to_review_queue(result["__interrupt__"][0].value)

# Later, when the analyst submits a decision in your case tool:
graph.invoke(Command(resume={"fraud": True, "note": "Card not present, new device"}),
             config)

With invoke(), a paused run returns its payload under __interrupt__. To continue, you call the graph again with Command(resume=...) and the same thread_id; the resume value becomes the return value of interrupt() inside the node. LangGraph also offers stream_events(..., version="v3") as its recommended way to drive graphs that may pause.

Keeping the LLM out of the real-time path

In the graph above, a held transaction still waits for summarise before invoke() returns. That is acceptable for a back-office review queue but not for a card authorisation. In practice, split the work:

  • The authorisation service answers the payment network as soon as the router has picked a branch. The hold node publishes “held” to your own queue, which is the signal the authorisation service waits for.
  • The graph runs in a worker that consumes transactions, so the LLM call and the human wait happen after the payment response has been sent.

Because the decision path is just rules plus one predict_proba call, its speed depends on your feature lookups and hosting, not on any LLM. Measure it on your own infrastructure rather than relying on published figures.

Things that will bite you

  • Nodes re-run on resume. The docs are explicit that a resumed node starts again from the top, so any code before interrupt() executes twice. Keep side effects out of analyst_review before the interrupt, and make publish_status idempotent.
  • Don’t wrap interrupt() in a bare try/except. It pauses by raising a special exception; catching it stops the pause from reaching the graph.
  • Payloads must be JSON-serialisable. Pass IDs, scores and the summary text, not model objects.
  • Thresholds are policy, not code. Agree the approve, hold and decline cut-offs with your fraud and risk teams, and record who changed them and when.
  • Model governance still applies. A bank deploying this would need its own model validation, monitoring and audit trail under whatever rules its regulators set. The checkpointer history helps as a record of what each node saw, but it is not a compliance system.

For broader advice on running LangChain-based agents beyond the prototype stage, see LangChain agents in production. The LangChain Agents listing and the agent frameworks hub cover related tools.

#LangGraph#Fraud detection#Human-in-the-loop#scikit-learn#Python
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.