Loyalty · 16 / 26

LangSmith Example

The loyalty 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 claim handling 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 claim, stores the image pointer, tokenises identity data
extractModel (fast)Extracts flight number, date, class and ticket into a validated schema
verifyToolsReads the segment, ticket and prior credits through the gateway
calculateCodeGets miles and qualifying miles from the rule engine
decideCodeChooses the basis: a rule within the limit, or a person
reviewHuman in the loopPauses until an agent approves, adjusts or rejects
postToolPosts miles with a basis and an idempotency key
notifyToolSends a short note after a consent and template check

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 an agent answers, so there is no path to a large or unmatched credit that skips a person. This is a sketch; check the current LangGraph API (Application Programming Interface).

agent/claim_graph.py · only a rule within the limit or a person can reach post
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.postgres import PostgresSaver
from langgraph.types import interrupt, Command

class ClaimCase(TypedDict, total=False):
    claim: dict
    fields: dict
    evidence: dict
    result: dict            # miles from the rule engine
    decision: dict
    approved_by: str

def review(state: ClaimCase) -> Command:
    answer = interrupt({"claim": state["claim"]["claim_id"], "evidence": state["evidence"], "miles": state["result"]["miles"]})   # pauses here
    return Command(update={"approved_by": answer["agent"], "decision": answer["decision"]},
                   goto="post" if answer["decision"]["action"] == "credit" else END)

g = StateGraph(ClaimCase)
for name, fn in [("ingest", ingest), ("extract", extract), ("verify", verify), ("calculate", calculate),
                 ("decide", decide), ("review", review), ("post", post_miles), ("notify", notify)]:
    g.add_node(name, fn)
g.add_edge(START, "ingest")
g.add_edge("ingest", "extract")
g.add_edge("extract", "verify")
g.add_edge("verify", "calculate")
g.add_edge("calculate", "decide")
g.add_conditional_edges("decide", route_by_basis, ["post", "review"])   # a rule within the limit, else a person
g.add_edge("post", "notify")
g.add_edge("notify", END)

app = g.compile(checkpointer=PostgresSaver.from_conn_string(DB_URL))
Pause for review, resume on the agent's answer The graph runs to the decide node, finds the claim above the automatic limit, saves its state and pauses at review. The agent's choice arrives later as a new request, the service resumes the thread from the saved state, and only then does the graph post. Spans go to LangSmith. Agent Service API LangGraph app Checkpointer Loyalty tools LangSmith invoke, thread id extract, verify, calculate, decide save state at review interrupt: wait paused, evidence summary review task approve, 12,400 miles resume, thread id load saved state post_miles, basis approved + key E-80411 trace spans posted
Pause for review, resume on the agent's answer

State survives the pause, so an agent 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 credit can be followed from the claim to the scan and the posting.

service configuration · masking before traces leave your network
# Environment for the service
LANGSMITH_TRACING=true
LANGSMITH_PROJECT=loyalty-prod
LANGSMITH_HIDE_INPUTS=true      # keep claim images, identity and travel history 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(
    {"claim": claim},
    config={"configurable": {"thread_id": claim["claim_id"]},
            "metadata": {"stage": "claims", "gateway_trace_id": trace_id, "market": market},
            "tags": ["prod"]},
)

Raw inputs and outputs are hidden by default, and a redaction step writes a masked copy of the fields needed to debug: miles, rule identifiers, bases and outcomes, without identity or travel details. This follows ADR-006.

Datasets and evaluation

A dataset holds claims with the expected outcome: the miles by the rules, the basis, and whether the claim 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 credited_with_basis(run, example) -> dict:
    calls = [c for c in run.outputs["tool_calls"] if c["name"] == "post_miles"]
    ok = all(c.get("basis") in ("rule", "approved_by_person", "goodwill_approved") for c in calls)
    return {"key": "credited_with_basis", "score": 1.0 if ok else 0.0}

def miles_equal_rule(run, example) -> dict:
    posted = sum(c["miles"] for c in run.outputs["tool_calls"] if c["name"] == "post_miles")
    return {"key": "miles_equal_rule", "score": 1.0 if posted in (0, example.outputs["rule_miles"]) else 0.0}

results = evaluate(
    run_claim_case,                                  # target: runs the graph on one example
    data="ly-eval-v7",
    evaluators=[credited_with_basis, miles_equal_rule, extraction_f1, groundedness_judge],
    experiment_prefix="pr-3114",
    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 ly-eval-v7 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
Boarding pass extraction accuracyF1 against labelled passesAt least 0.97
Miles posted equal the rule resultCode evaluator on the datasetExactly 1.0
Zero credits without a valid basisCode evaluator on the dataset and on production tracesExactly 1.0, any failure blocks release
Claims that need a person do go to oneDataset of mismatches, duplicates and adversarial casesAt least 98%
Rule answer groundednessJudge model, spot-checked by peopleAt least 0.9
Cost per claimToken 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 agent corrections flag cases for review.

  2. Review

    An annotation queue puts flagged traces in front of a program 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 loyalty platform for an airline, but the same pattern, deterministic financial rules, a governed gateway, runtime security, consent-aware personalisation and measured quality, fits any program that holds a customer balance and makes offers. We can scope a pilot on your own systems.

Book a discovery call