Invoicing · 16 / 26

LangSmith Example

The receivables platform built with LangGraph and traced, tested and monitored in LangSmith: graph, tracing, datasets and release gates.

The same platform with LangGraph and LangSmith

LangGraph models cash application as a graph of nodes with explicit state, and LangSmith traces every run, stores datasets and runs evaluations. This build suits teams that want code-level control and a tight test loop. It uses the same tool contracts, gateway and security profile as the other builds.

NodeKindWhat it does
ingestCodeReads the bank line, tokenises account data, stores the document pointer
extractModel (fast)Extracts remittance lines into a validated schema
matchCode and scorerApplies rules and scores candidate invoices
decideCodeChooses the basis: exact rule, score above threshold, or a person
reviewHuman in the loopPauses until a clerk confirms a candidate or rejects the match
applyToolApplies cash with a basis and an idempotency key, reversibly
notifyToolSends a receipt or a note about an open item, after approval where required

The graph in code

State is a typed object. The decide node routes by basis, and the review node interrupts the run and resumes only when a clerk answers, so there is no path to apply scored matches below the threshold that skips a person. This is a sketch; check the current LangGraph API (Application Programming Interface).

agent/cash_graph.py · only a rule, a threshold or a person can reach apply
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.postgres import PostgresSaver
from langgraph.types import interrupt, Command

class CashCase(TypedDict, total=False):
    payment: dict
    remittance: dict
    candidates: list
    decision: dict
    approved_by: str

def review(state: CashCase) -> Command:
    answer = interrupt({"payment": state["payment"]["payment_id"], "candidates": state["candidates"][:3]})   # pauses here
    return Command(update={"approved_by": answer["clerk"], "decision": answer["decision"]},
                   goto="apply" if answer["decision"]["action"] == "apply" else END)

g = StateGraph(CashCase)
for name, fn in [("ingest", ingest), ("extract", extract), ("match", match), ("decide", decide),
                 ("review", review), ("apply", apply_cash), ("notify", notify)]:
    g.add_node(name, fn)
g.add_edge(START, "ingest")
g.add_edge("ingest", "extract")
g.add_edge("extract", "match")
g.add_edge("match", "decide")
g.add_conditional_edges("decide", route_by_basis, ["apply", "review"])   # exact or above threshold, else a person
g.add_edge("apply", "notify")
g.add_edge("notify", END)

app = g.compile(checkpointer=PostgresSaver.from_conn_string(DB_URL))
Pause for review, resume on the clerk's answer The graph runs to the decide node, finds no candidate above the threshold, saves its state and pauses at review. The clerk's choice arrives later as a new request, the service resumes the thread from the saved state, and only then does the graph apply. Spans go to LangSmith. Clerk Service API LangGraph app Checkpointer Receivables tools LangSmith invoke, thread id extract, match, decide save state at review interrupt: wait paused, candidates ranked review task confirm candidate 1 resume, thread id load saved state apply_cash, basis approved + key A-5521 trace spans applied
Pause for review, resume on the clerk's answer

State survives the pause, so a clerk can answer in a minute or an hour, and a restart of the service does not lose the case.

Tracing every unit of work

LangSmith traces each run with nested spans for model calls, tools and retrieval. Metadata ties a trace to a case, a stage and the gateway's trace identifier, so a wrong match can be followed from the bank line to the scan and the posting.

service configuration · masking before traces leave your network
# Environment for the service
LANGSMITH_TRACING=true
LANGSMITH_PROJECT=receivables-prod
LANGSMITH_HIDE_INPUTS=true      # keep documents and bank data out of the tracing vendor
LANGSMITH_HIDE_OUTPUTS=true     # trace a redacted copy instead

# In code: attach the identifiers and a redacted view
result = app.invoke(
    {"payment": payment},
    config={"configurable": {"thread_id": payment["payment_id"]},
            "metadata": {"stage": "cash-application", "gateway_trace_id": trace_id, "region": region},
            "tags": ["prod"]},
)

Raw inputs and outputs are hidden by default, and a redaction step writes a masked copy of the fields needed to debug: amounts, rule identifiers, scores and outcomes, without account numbers or names. This follows ADR-006.

Datasets and evaluation

A dataset holds payments and remittances with the expected outcome: the allocations, the basis, and whether the item should go to a person. Offline runs compare the graph against the dataset on every change.

tests/test_eval.py · offline evaluation as a release gate
from langsmith import Client, evaluate

client = Client()

def applied_with_basis(run, example) -> dict:
    calls = [c for c in run.outputs["tool_calls"] if c["name"] == "apply_cash"]
    ok = all(c.get("basis") in ("exact_rule", "scored_above_threshold", "approved_by_person") for c in calls)
    return {"key": "applied_with_basis", "score": 1.0 if ok else 0.0}

def amount_matches_bank(run, example) -> dict:
    applied = sum(c["amount"] for c in run.outputs["allocations"])
    return {"key": "amount_matches_bank", "score": 1.0 if applied <= example.outputs["payment_amount"] else 0.0}

results = evaluate(
    run_cash_case,                                   # target: runs the graph on one example
    data="ar-eval-v9",
    evaluators=[applied_with_basis, amount_matches_bank, extraction_f1, groundedness_judge],
    experiment_prefix="pr-2207",
    max_concurrency=4,
)
A LangSmith offline experiment CI calls evaluate with the target and a dataset. The client loads the examples, runs the graph on each, scores the outputs with the evaluators and stores an experiment, then CI compares it with the baseline and passes or fails the check. CI LangSmith client Dataset Graph under test Evaluators Experiment evaluate(target, data) load ar-eval-v9 examples run each example outputs, tool calls score outputs scores store experiment results vs baseline gate: pass or fail
A LangSmith offline experiment

Every example runs in its own trace, so a failing score links straight to the case that caused it.

Release gates and online monitoring

CheckHowThreshold
Remittance extraction accuracyF1 against labelled remittancesAt least 0.97
Match accuracy on applied valueCorrect allocations over applied valueAt least 99.5%
Zero applications without a valid basisCode evaluator on the dataset and on production tracesExactly 1.0, any failure blocks release
Items that should go to a person doDataset of ambiguous and adversarial casesAt least 98%
Dispute clause groundednessJudge model, spot-checked by peopleAt least 0.9
Cost per paymentToken and cost metadata on tracesWithin 10% of the last release
Drift in productionOnline evaluators on sampled traces, with alertsAlert on a drop of 5 points

The improvement loop

  1. Sample

    Online evaluators and clerk corrections flag cases for review.

  2. Review

    An annotation queue puts flagged traces in front of an AR (Accounts Receivable) lead, who marks what should have happened.

  3. Add to the dataset

    Reviewed traces become new dataset examples, after redaction.

  4. Fix and compare

    Change the prompt, rule or tool, run the experiment and compare against the baseline on the same dataset.

  5. Release

    The gate passes, the new version is promoted and the online evaluators watch the result.

Build this for your business

This example is a receivables platform for a distributor, but the same pattern, deterministic financial rules, a governed gateway, runtime security, grounded evidence and measured quality, fits any back-office process that moves money. We can scope a pilot on your own systems.

Book a discovery call