Forge
Skip to main content

Tutorial: Building a production-ready fraud triage Copilot

Build, evaluate, guard, and monitor an LLM fraud analyst end-to-end with W&B Weave.
Last updated: April 23, 2026

Every declined legitimate transaction costs you a customer. Every approved fraudulent one costs you money. Rule engines catch yesterday's patterns. ML models give you a score but no explanation. What if your fraud analyst never slept, explained every decision in plain English, and got smarter every week?
In this tutorial, we build a fraud-triage copilot, an LLM-powered agent that analyzes transactions, reasons through velocity spikes and geo mismatches, and returns structured approve/decline/escalate verdicts with a full audit trail. Then we take it from prototype to production using the four core products in W&B Weave:
  • Traces give you X-ray vision into every decision.
  • Evaluations replace gut feel with hard numbers across prompt variants.
  • Guardrails intercept dangerous outputs in real time.
  • Monitors catch quality drift before chargebacks spike.
Along the way, we'll use W&B Inference, so the only credential you need is a WANDB_API_KEY. No OpenAI key required.


Table of contents



Fraud triage Copilot tutorial: Step-by-step code breakdown

Prerequisites

Before starting, make sure you have the following:
Basic familiarity with LLM function calling concepts

Step 1: Setting up the environment

Before writing any analyst code, we need to install our dependencies and connect to both Weave (for observability) and W&B Inference (for hosting our LLM):
!pip install -q weave openai pydantic numpy nest_asyncio

import os, json, random, time, asyncio, hashlib
from datetime import datetime, timedelta
from enum import Enum
from typing import Optional
import numpy as np
import nest_asyncio
nest_asyncio.apply()
import weave
from openai import OpenAI
from pydantic import BaseModel, Field
from weave import Scorer
Now, initialize Weave. This single line activates tracing for every function we decorate later, automatically capturing inputs, outputs, latency, and token costs:
WANDB_API_KEY = "you_key"
os.environ["WANDB_API_KEY"] = WANDB_API_KEY

wandb.login(key=os.environ["WANDB_API_KEY"])
weave.init("username/fraud-triage-copilot")
Next, set up the W&B Inference client. Since it exposes an OpenAI-compatible API, we use the familiar OpenAI SDK and just point it at the W&B Inference endpoint:
client = OpenAI(
base_url="https://api.inference.wandb.ai/v1",
api_key=WANDB_API_KEY,
)

AGENT_MODEL = "Qwen/Qwen3-235B-A22B-Instruct-2507"
JUDGE_MODEL = "meta-llama/Llama-3.3-70B-Instruct"
print(f"✓ W&B Inference client ready | Agent: {AGENT_MODEL} | Judge: {JUDGE_MODEL}")
Expected output:
✓ W&B Inference client ready | Agent: Qwen/Qwen3-235B-A22B-Instruct-2507 | Judge: meta-llama/Llama-3.3-70B-Instruct
We chose Qwen3-235B-A22B-Instruct-2507 because it is a mixture-of-experts model with strong structured output capabilities available directly through the W&B Inference model catalog. We define JUDGE_MODEL up front as well. We will use a separate, smaller model to evaluate our analyst later in the Monitors section, avoiding self-evaluation bias.

Step 2: Building the data layer

Unlike a chatbot that operates on free text, a fraud analyst works with structured financial data. We need two things: Pydantic models that define the shape of data at every pipeline stage, and synthetic generators that produce realistic transactions for testing.

Pydantic models

We define models for every stage, from raw transaction through enrichment, decision, guarded output, and judge assessment. This gives us type safety, validation, and clean serialization throughout:
class Verdict(str, Enum):
APPROVE = "approve"
DECLINE = "decline"
ESCALATE = "escalate_to_human"


class Transaction(BaseModel):
transaction_id: str
card_hash: str
amount_usd: float
merchant_name: str
mcc: str
merchant_country: str
channel: str
timestamp: datetime
ip_address: str = ""
billing_zip: str = ""
shipping_zip: str = ""
is_3ds: bool = False


class EnrichedTransaction(BaseModel):
transaction: Transaction
velocity: dict = {}
geo_risk: dict = {}
device: dict = {}
rule_engine_score: float = 0.0
ml_model_score: float = 0.0


class FraudDecision(BaseModel):
transaction_id: str
verdict: Verdict
confidence: float = Field(..., ge=0, le=1)
risk_level: str
risk_score: float
reasoning: str
key_risk_factors: list[str] = []
key_trust_factors: list[str] = []
recommended_actions: list[str] = []


class GuardedDecision(BaseModel):
original_decision: FraudDecision
final_verdict: Verdict
guardrail_overrides: list[str] = []
was_escalated: bool = False
escalation_reason: Optional[str] = None


class JudgeAssessment(BaseModel):
transaction_id: str
judge_agrees: bool
reasoning_quality: float
overall_quality_score: float
judge_suggested_verdict: Verdict
feedback: str
missed_signals: list[str] = []
Each model maps to a real stage in the fraud review pipeline. A transaction is what comes off the payment gateway. EnrichedTransaction adds velocity, geo-risk, and device intelligence from upstream services. FraudDecision is the copilot's structured output, a verdict with full reasoning that a human analyst can audit. GuardedDecision wraps the original decision with guardrail override information, recording what was blocked and why. JudgeAssessment is the schema for the LLM judge that monitors quality in production.



Synthetic transaction generators

Rather than using production data (which carries PII and compliance constraints), we build synthetic generators that produce realistic fraud and legitimate transaction patterns. Each generator encodes domain knowledge about what real fraud looks like, high velocity, geo mismatches, new devices, and risky merchant categories:
LEGIT_MERCHANTS = [
("Amazon.com", "5411", "US"),
("Netflix", "4899", "US"),
("Walmart.com", "5311", "US"),
("Best Buy", "5732", "US"),
("Uber Eats", "5812", "US"),
("Spotify", "4899", "SE"),
]

RISKY_MERCHANTS = [
("CryptoXchange", "6051", "MT"),
("GoldenBet Casino", "7995", "GI"),
("QuickWire", "4829", "NG"),
("FastElectronics99", "5732", "CN"),
]


def _gen_txn(txn_id, merchant, amount, fraud=False):
billing = f"{random.randint(10000, 99999)}"
return EnrichedTransaction(
transaction=Transaction(
transaction_id=txn_id,
card_hash=hashlib.sha256(
f"c{random.randint(0, 999999)}".encode()
).hexdigest()[:12],
amount_usd=amount,
merchant_name=merchant[0],
mcc=merchant[1],
merchant_country=merchant[2],
channel="ecommerce",
timestamp=datetime.utcnow() - timedelta(minutes=random.randint(0, 1440)),
ip_address=(
f"185.{random.randint(100, 255)}.{random.randint(0, 255)}.1"
if fraud
else f"24.{random.randint(0, 255)}.{random.randint(0, 255)}.1"
),
billing_zip=billing,
shipping_zip=(billing if not fraud else f"{random.randint(10000, 99999)}"),
is_3ds=(random.random() < 0.1 if fraud else random.random() < 0.6),
),
velocity={
"txn_count_1h": random.randint(5, 15) if fraud else random.randint(0, 2),
"txn_count_24h": random.randint(8, 25) if fraud else random.randint(1, 5),
"unique_merchants_24h": random.randint(4, 10)
if fraud
else random.randint(1, 3),
"avg_txn_amount_30d": round(
amount * 0.3 if fraud else amount * random.uniform(0.7, 1.3), 2
),
},
geo_risk={
"ip_country": random.choice(["NG", "RU", "CN"]) if fraud else "US",
"ip_is_vpn": random.random() < 0.5 if fraud else False,
"ip_is_tor": random.random() < 0.2 if fraud else False,
"ip_billing_country_match": not fraud,
"billing_shipping_match": not fraud,
},
device={
"device_seen_before": not fraud or random.random() < 0.2,
"multiple_cards_on_device": fraud and random.random() < 0.4,
"device_age_days": 0 if fraud else random.randint(30, 365),
},
rule_engine_score=round(
random.uniform(55, 95) if fraud else random.uniform(5, 30), 1
),
ml_model_score=round(
random.uniform(0.6, 0.98) if fraud else random.uniform(0.02, 0.2), 3
),
)


def gen_legit(txn_id=None):
m = random.choice(LEGIT_MERCHANTS)
return _gen_txn(
txn_id or f"txn-{random.randint(100000, 999999)}",
m,
round(min(np.random.lognormal(3.5, 1), 2000), 2),
)


def gen_fraud(txn_id=None, pattern="mixed"):
pool = (
RISKY_MERCHANTS
if pattern == "risky_merchant"
else LEGIT_MERCHANTS + RISKY_MERCHANTS
)
return _gen_txn(
txn_id or f"txn-{random.randint(100000, 999999)}",
random.choice(pool),
round(min(np.random.lognormal(5.5, 1.2), 12000), 2),
fraud=True,
)
Let us verify it works by generating a sample fraud transaction:
txn = gen_fraud("test-001")
print(f"✓ Sample fraud txn: ${txn.transaction.amount_usd:.2f} at {txn.transaction.merchant_name}")
print(f" Velocity: {txn.velocity['txn_count_1h']} txns/hr | Geo: IP from {txn.geo_risk['ip_country']}")

Expected output:
✓ Sample fraud txn: $43.61 at QuickWire
Velocity: 11 txns/hr | Geo: IP from RU
Notice the telltale fraud signals: high velocity, foreign IP, and a risky crypto merchant. The legitimate generator, by contrast, produces low-velocity domestic transactions at familiar retailers.

Step 3: Building the agent tools

A fraud analyst is only as good as the data they can access. Ours will have enrichment tools that gather velocity, geo-risk, and device intelligence for each transaction. Every tool is decorated with @weave.op(), Weave's core tracing mechanism. Think of @weave.op() like a security camera on a function: it records everything going in and coming out, without changing what the function actually does.
Velocity lookup queries the card's recent activity. In production, this would hit a real-time velocity service; here, we use the data already embedded in our synthetic transactions:
@weave.op()
def lookup_velocity(card_hash: str) -> dict:
"""Query the velocity service for recent card activity."""
return {"source": "velocity_service", "card_hash": card_hash}
Geo-risk lookup checks the IP address against threat intelligence databases for VPN, Tor, and country-mismatch signals:
@weave.op()
def lookup_geo_risk(ip: str) -> dict:
"""Check IP against geo-risk database (VPN, Tor, country mismatch)."""
return {"source": "geo_risk_service", "ip": ip}
Device lookup queries the device fingerprint graph to determine whether this device has been seen before and whether multiple cards are associated with it:
@weave.op()
def lookup_device(fp: str) -> dict:
"""Look up device fingerprint in the device graph."""
return {"source": "device_graph", "fp": fp}
The enrichment orchestrator ties all three lookups together and assembles the analysis payload that the LLM will consume:
@weave.op()
def enrich_transaction(etxn: EnrichedTransaction) -> dict:
"""Orchestrate all enrichment lookups and build the analysis payload."""
t = etxn.transaction
lookup_velocity(t.card_hash)
lookup_geo_risk(t.ip_address)
lookup_device(t.card_hash[:8])
return {
"transaction": {
"id": t.transaction_id,
"amount_usd": t.amount_usd,
"merchant": t.merchant_name,
"mcc": t.mcc,
"country": t.merchant_country,
"channel": t.channel,
"is_3ds": t.is_3ds,
"timestamp": t.timestamp.isoformat(),
},
"velocity": etxn.velocity,
"geo_risk": etxn.geo_risk,
"device": etxn.device,
"scores": {
"rule_engine": etxn.rule_engine_score,
"ml_model": etxn.ml_model_score,
},
}
Let us verify it works:
result = enrich_transaction(gen_legit("test-enrich"))
print(f"✓ Enriched txn {result['transaction']['id']}: {len(result)} sections")
print(f" Merchant: {result['transaction']['merchant']} | MCC: {result['transaction']['mcc']}")

Step 4: The fraud analyst prompt

The analyst loop is the orchestration layer that connects the LLM to our enrichment tools. Unlike a conversational agent that uses multi-turn tool-calling, our fraud analyst works in a single pass: enrich the transaction, present the full evidence package to the LLM, and receive a structured verdict back. This design matches how human fraud analysts work; they see all the signals at once and render a judgment.

First, the system prompt. This is the instruction set that shapes the analyst's reasoning, telling it what signals to examine, in what order, and how to structure its output. We define three prompt variants up front so we can A/B test them later in the Evaluations step:
SYSTEM_PROMPT = (
"You are an expert CNP fraud analyst. Analyze step-by-step:\n"
"1. Amount & merchant risk 2. Velocity anomalies 3. Geo consistency\n"
"4. Device trust 5. Authentication 6. ML/rule scores 7. Synthesize\n\n"
'Respond ONLY with JSON: {"verdict":"approve|decline|escalate_to_human",'
'"confidence":<0-1>,"risk_level":"low|medium|high|critical","risk_score":<0-100>,'
'"reasoning":"<steps>","key_risk_factors":[...],"key_trust_factors":[...],'
'"recommended_actions":[...]}'
)

PROMPTS = {
"v1_structured_cot": SYSTEM_PROMPT,
"v2_concise": (
"You are a fraud-triage AI for CNP transactions. Analyze velocity, geo, device, "
"amount history, auth signals. Bias toward precision.\n\n"
'Respond ONLY with JSON: {"verdict":"approve|decline|escalate_to_human",'
'"confidence":<0-1>,"risk_level":"low|medium|high|critical","risk_score":<0-100>,'
'"reasoning":"<concise>","key_risk_factors":[...],"key_trust_factors":[...],'
'"recommended_actions":[...]}'
),
"v3_adversarial": (
"You are a senior fraud investigator. For each transaction:\n"
"- PROSECUTION: why it's fraud\n- DEFENSE: why it's legitimate\n"
"- Synthesize a fair verdict. False declines hurt customers.\n\n"
'Respond ONLY with JSON: {"verdict":"approve|decline|escalate_to_human",'
'"confidence":<0-1>,"risk_level":"low|medium|high|critical","risk_score":<0-100>,'
'"reasoning":"<prosecution, defense, synthesis>","key_risk_factors":[...],'
'"key_trust_factors":[...],"recommended_actions":[...]}'
),
}

V1 uses a structured seven-step chain-of-thought. V2 is concise, same signal coverage, fewer words. V3 takes an adversarial approach, forcing the model to argue both sides before rendering a verdict. We will compare V1 and V2 in the Evaluations step.
Now the main analyst function. The @weave.op() decorator on this function means Weave will capture the entire execution tree, enrichment lookups, the LLM call, and the parsed decision automatically:
@weave.op()
def run_fraud_analyst(
enriched_transaction: dict,
system_prompt: str = SYSTEM_PROMPT,
) -> dict:
"""Run the fraud analyst on a single enriched transaction."""
etxn = EnrichedTransaction(**enriched_transaction)
enriched_data = enrich_transaction(etxn)

user_msg = (
"Analyze this CNP transaction:\n```json\n"
+ json.dumps(enriched_data, indent=2, default=str)
+ "\n```"
)
t0 = time.time()
resp = client.chat.completions.create(
model=AGENT_MODEL,
temperature=0.1,
max_tokens=1024,
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_msg},
],
)
latency = (time.time() - t0) * 1000
parsed = json.loads(resp.choices[0].message.content)
usage = resp.usage

decision = FraudDecision(
transaction_id=enriched_data.get("transaction", {}).get("id", "?"),
verdict=Verdict(parsed["verdict"]),
confidence=float(parsed["confidence"]),
risk_level=parsed["risk_level"],
risk_score=float(parsed["risk_score"]),
reasoning=parsed["reasoning"],
key_risk_factors=parsed.get("key_risk_factors", []),
key_trust_factors=parsed.get("key_trust_factors", []),
recommended_actions=parsed.get("recommended_actions", []),
)
return {
"decision": decision.model_dump(),
"metadata": {
"model": AGENT_MODEL,
"latency_ms": round(latency, 1),
"prompt_tokens": usage.prompt_tokens if usage else 0,
"completion_tokens": usage.completion_tokens if usage else 0,
"total_tokens": usage.total_tokens if usage else 0,
},
}
Let us test with a known fraud case:
result = run_fraud_analyst(gen_fraud("test-fraud-001").model_dump())
print(f"Verdict: {result['decision']['verdict']}")
print(f"Confidence: {result['decision']['confidence']:.2f}")
print(f"Risk level: {result['decision']['risk_level']}")
print(f"Reasoning: {result['decision']['reasoning'][:100]}...")
print(f"\nLatency: {result['metadata']['latency_ms']:.0f}ms | Tokens: {result['metadata']['total_tokens']}")
Expected output:
Verdict: Verdict.DECLINE Confidence: 0.93 Risk level: high Reasoning: 1. Amount & merchant risk: Transaction at Best Buy (MCC 5732) for $73.16 is moderately high compared... Latency: 17330ms | Tokens: 883

Step 5: Debugging your fraud triage system with W&B Traces

Open your Weave project, then click the Traces tab. You will see the run_fraud_analyst call we just made, along with its entire execution tree.

You can also click on the trace to expand it. The detail view shows a nested call hierarchy:
  • The enrich_transaction call as a parent span, with lookup_velocity, lookup_geo_risk, and lookup_device as child spans
  • The openai.chat.completions.create call with the full request and response
  • The parsed FraudDecision is the final output

This kind of visibility is like having an X-ray for your analyst, instead of adding print statements everywhere and hoping to catch the bug, Traces show you the exact data flow at every step. If the analyst gave a wrong verdict, you can pinpoint whether it was missing enrichment data, a bad LLM interpretation of the signals, or a parsing error in the structured output.
Let us run a few more to build up trace data:
print("Running 5 transactions for trace exploration...\n")

for i in range(2):
txn = gen_legit(f"trace-legit-{i}")
r = run_fraud_analyst(txn.model_dump())
d = r["decision"]
m = r["metadata"]
print(
f" LEGIT {txn.transaction.transaction_id} "
f"${txn.transaction.amount_usd:.2f} -> {d['verdict']} "
f"conf={d['confidence']:.2f} [{m['latency_ms']:.0f}ms {m['total_tokens']}tok]"
)

for i in range(3):
txn = gen_fraud(f"trace-fraud-{i}")
r = run_fraud_analyst(txn.model_dump())
d = r["decision"]
m = r["metadata"]
print(
f" FRAUD {txn.transaction.transaction_id} "
f"${txn.transaction.amount_usd:.2f} -> {d['verdict']} "
f"conf={d['confidence']:.2f} [{m['latency_ms']:.0f}ms]"
)

print("\n✓ Check the Traces tab in your Weave project to explore these calls!")
Expected output:
LEGIT trace-legit-0 $20.76 -> Verdict.APPROVE conf=0.92 [11348ms 838tok] LEGIT trace-legit-1 $46.08 -> Verdict.APPROVE conf=0.94 [7218ms 796tok] FRAUD trace-fraud-0 $623.14 -> Verdict.DECLINE conf=0.94 [12322ms] FRAUD trace-fraud-1 $1223.38 -> Verdict.DECLINE conf=0.98 [7636ms] FRAUD trace-fraud-2 $84.59 -> Verdict.DECLINE conf=0.94 [10078ms]
Weave also automatically captures latency, cost, and token usage for every LLM call. You can sort the Traces table by these columns to find expensive or slow calls.

Step 6: Evaluating the fraud analyst with synthetic data

Running handpicked tests is useful for development, but it does not provide production confidence. What you need is systematic testing: run the fraud analyst against a representative dataset, score every decision, and get hard numbers you can compare across versions. This is exactly what Weave Evaluations provides.

Building the evaluation dataset

We generate a balanced dataset of 40 transactions (30% fraud, 70% legitimate) and publish it as a versioned Weave dataset so every evaluation run is reproducible:
def gen_dataset(n=40, fraud_rate=0.3, seed=42):
random.seed(seed)
np.random.seed(seed)
nf = int(n * fraud_rate)
ds = [
{"enriched_transaction": gen_fraud(f"eval-f-{i:03d}").model_dump(), "is_fraud": True}
for i in range(nf)
]
ds += [
{"enriched_transaction": gen_legit(f"eval-l-{i:03d}").model_dump(), "is_fraud": False}
for i in range(n - nf)
]
random.shuffle(ds)
return ds


eval_dataset = gen_dataset(n=40)
nf = sum(d["is_fraud"] for d in eval_dataset)
print(f"✓ Built evaluation dataset: {len(eval_dataset)} transactions ({nf} fraud / {len(eval_dataset) - nf} legit)")

weave.publish(weave.Dataset(name="fraud-eval-v1", rows=eval_dataset))
print("✓ Published as fraud-eval-v1 in Weave")
Expected output:
✓ Built evaluation dataset: 40 transactions (12 fraud / 28 legit) ✓ Published as fraud-eval-v1 in Weave

Writing the scorers

Scorers are functions that grade the analyst's output on specific dimensions. Each scorer receives the analyst's output and returns a dictionary of metrics. We define two that capture different aspects of quality:
@weave.op()
def fraud_accuracy_scorer(output: dict, is_fraud: bool) -> dict:
"""Did the analyst make the correct approve/decline decision?
This is the most critical metric: wrong verdict = wrong outcome."""
v = output.get("decision", {}).get("verdict", "escalate_to_human")
correct = (is_fraud and v == "decline") or (not is_fraud and v == "approve")
return {
"correct": correct,
"tp": is_fraud and v == "decline",
"fp": not is_fraud and v == "decline",
"tn": not is_fraud and v == "approve",
"fn": is_fraud and v == "approve",
"escalated": v == "escalate_to_human",
}


@weave.op()
def efficiency_scorer(output: dict) -> dict:
"""How fast and how expensive was the decision?"""
m = output.get("metadata", {})
cost = (m.get("prompt_tokens", 0) / 1000) * 0.00015 + (
m.get("completion_tokens", 0) / 1000
) * 0.0006
return {
"latency_ms": m.get("latency_ms", 0),
"tokens": m.get("total_tokens", 0),
"cost_usd": round(cost, 6),
"is_fast": m.get("latency_ms", 0) < 10000,
}

Running evaluations

To use Weave Evaluations, we wrap our analyst in a weave.Model subclass. This lets Weave version the configuration (model name, prompt variant) so we can compare different versions later:
class FraudAnalystV1(weave.Model):
model_name: str = AGENT_MODEL
version_label: str = "v1_structured_cot"

@weave.op()
async def predict(
self,
enriched_transaction: dict,
is_fraud: bool = False,
) -> dict:
return run_fraud_analyst(enriched_transaction)


evaluation = weave.Evaluation(
name="fraud_analyst_eval_v1",
dataset=eval_dataset,
scorers=[fraud_accuracy_scorer, efficiency_scorer],
)

agent_v1 = FraudAnalystV1()
results_v1 = asyncio.run(evaluation.evaluate(agent_v1))
print("V1 Results:", json.dumps(results_v1, indent=2, default=str))
Expected output:
V1 Results: { "fraud_accuracy_scorer": { "correct": {"true_count": 40, "true_fraction": 1.0}, "tp": {"true_count": 12, "true_fraction": 0.3}, "fp": {"true_count": 0, "true_fraction": 0.0}, "tn": {"true_count": 28, "true_fraction": 0.7}, "fn": {"true_count": 0, "true_fraction": 0.0}, "escalated": {"true_count": 0, "true_fraction": 0.0} }, "efficiency_scorer": { "latency_ms": {"mean": 10573.92}, "tokens": {"mean": 822.5}, "cost_usd": {"mean": 0.00029115}, "is_fast": {"true_count": 19, "true_fraction": 0.475} } }
Why these numbers matter: The analyst handles clear-cut cases well, but the structured chain-of-thought prompt is verbose; it produces thorough reasoning at the cost of higher token usage and latency. In production, that verbosity directly translates into a higher cost per transaction. With thousands of transactions per hour, even small inefficiencies compound quickly. The question is whether we can get the same accuracy with a lighter prompt.

Improving and comparing with V2

Looking at the V1 efficiency metrics, the pattern is clear: the seven-step chain-of-thought prompt produces detailed but expensive reasoning. Each decision averages 800+ tokens of output, most of which is redundant narration of obvious signals. The fix is the concise prompt we already defined in our PROMPTS dictionary:
IMPROVED_PROMPT = PROMPTS["v2_concise"]


class FraudAnalystV2(weave.Model):
model_name: str = AGENT_MODEL
version_label: str = "v2_concise"

@weave.op()
async def predict(
self,
enriched_transaction: dict,
is_fraud: bool = False,
) -> dict:
return run_fraud_analyst(enriched_transaction, system_prompt=IMPROVED_PROMPT)


agent_v2 = FraudAnalystV2()
results_v2 = asyncio.run(evaluation.evaluate(agent_v2))
print("V2 Results:", json.dumps(results_v2, indent=2, default=str))
Now open the Evaluations tab and select both V1 and V2 to see them side by side. Weave generates a comparison view with a radar chart and a detailed scorecard.

V2 should match V1 accuracy, but with lower latency and cost, the concise prompt produces shorter reasoning, which means fewer tokens and faster responses.


Step 7: Adding guardrails for runtime safety

Evaluations test your analyst offline, before deployment. But what about the transactions it handles in real time? A fraudster could test an $8,000 purchase, or a transaction could arrive on a crypto exchange MCC that requires mandatory human review. You need a safety layer that intercepts dangerous outputs in real time.
Guardrails are scorers that run synchronously on every request, blocking or modifying unsafe outputs before they reach downstream systems. Think of them like a circuit breaker in an electrical panel: they let normal current flow, but trip immediately when something dangerous happens.
The key difference between guardrails and monitors (that we will set up in the next section):

We will build three guardrails that cover the most common production risks. Each one extends Weave's Scorer class.

Confidence gate guardrail blocks low-confidence decisions. If the model is not sure enough, the transaction gets escalated to a human reviewer rather than being auto-decided:
CONFIDENCE_THRESHOLD = 0.70
HIGH_VALUE_USD = 5000
SENSITIVE_MCCS = ["6051", "7995", "6211", "4829"]


class ConfidenceGateGuardrail(Scorer):
"""Block low-confidence decisions. If the model isn't sure, escalate."""

threshold: float = CONFIDENCE_THRESHOLD

@weave.op()
def score(self, output: dict) -> dict:
confidence = output.get("decision", {}).get("confidence", 0)
if confidence < self.threshold:
return {
"passed": False,
"reason": f"Confidence {confidence:.2f} < {self.threshold}",
}
return {"passed": True, "reason": "Confidence OK"}
Sensitive transaction guardrail blocks auto-decisions on high-value transactions or sensitive merchant category codes (crypto exchanges, gambling, wire transfers):
class SensitiveTransactionGuardrail(Scorer):
"""Block auto-decisions on high-value or sensitive-MCC transactions."""

max_auto_amount: float = HIGH_VALUE_USD

@weave.op()
def score(self, output: dict, enriched_transaction: dict = {}) -> dict:
txn = enriched_transaction.get("transaction", {})
triggers = []

amount = txn.get("amount_usd", 0)
if amount > self.max_auto_amount:
triggers.append(f"High-value: ${amount:,.0f}")

mcc = txn.get("mcc", "")
if mcc in SENSITIVE_MCCS:
triggers.append(f"Sensitive MCC: {mcc}")

if triggers:
return {"passed": False, "reason": "; ".join(triggers)}
return {"passed": True, "reason": "Transaction within limits"}
Content safety guardrail detects cases where the model's reasoning contradicts the evidence, for example, rating a transaction as low risk despite a Tor IP, or approving despite a country mismatch with high velocity:
class ContentSafetyGuardrail(Scorer):
"""Flag decisions where the model's reasoning contradicts the signals."""

@weave.op()
def score(self, output: dict, enriched_transaction: dict = {}) -> dict:
decision = output.get("decision", {})
geo = enriched_transaction.get("geo_risk", {})

if geo.get("ip_is_tor") and decision.get("risk_level") == "low":
return {
"passed": False,
"reason": "Tor IP detected but risk rated as low",
}
if not geo.get("ip_billing_country_match") and decision.get("verdict") == "approve":
velocity = enriched_transaction.get("velocity", {})
if velocity.get("txn_count_1h", 0) > 5:
return {
"passed": False,
"reason": "Country mismatch + high velocity but approved",
}
return {"passed": True, "reason": "Content checks passed"}
Now we wire all three into the analyst pipeline. The key mechanism is .call(), which returns both the result and a Weave Call object. We then apply each guardrail as a scorer on the Call. If any guardrail fails, we wrap the original decision in a GuardedDecision and escalate:
confidence_guard = ConfidenceGateGuardrail()
sensitive_guard = SensitiveTransactionGuardrail()
content_guard = ContentSafetyGuardrail()


@weave.op()
async def run_guarded_analyst(
enriched_transaction: dict,
system_prompt: str = SYSTEM_PROMPT,
) -> dict:
"""Run the fraud analyst with all three guardrails applied."""
result, call = run_fraud_analyst.call(enriched_transaction, system_prompt)

conf_check = await call.apply_scorer(confidence_guard)
sens_check = await call.apply_scorer(
sensitive_guard,
additional_scorer_kwargs={"enriched_transaction": enriched_transaction},
)
content_check = await call.apply_scorer(
content_guard,
additional_scorer_kwargs={"enriched_transaction": enriched_transaction},
)

checks = {
"confidence": conf_check.result,
"sensitive_txn": sens_check.result,
"content_safety": content_check.result,
}

failed = [name for name, c in checks.items() if not c.get("passed", True)]
if failed:
reasons = [checks[n]["reason"] for n in failed]
decision = FraudDecision(**result["decision"])
return {
"decision": GuardedDecision(
original_decision=decision,
final_verdict=Verdict.ESCALATE,
guardrail_overrides=reasons,
was_escalated=True,
escalation_reason=reasons[0],
).model_dump(),
"guardrails": checks,
"escalated": True,
"metadata": result.get("metadata", {}),
}

return {
"decision": result["decision"],
"guardrails": checks,
"escalated": False,
"metadata": result.get("metadata", {}),
}
Let us test all four scenarios:
print("Test 1: Normal legit transaction")
txn_normal = gen_legit("guard-legit")
result = asyncio.run(run_guarded_analyst(txn_normal.model_dump()))
print(f" Escalated: {result['escalated']}")
print(f" Confidence: {result['guardrails']['confidence']}")
print()
Expected output:
Test 1: Normal legit transaction Escalated: False Confidence: {'passed': True, 'reason': 'Confidence OK'}
Expected output:
Test 2: High-value $8,500 transaction Escalated: True Sensitive: {'passed': False, 'reason': 'High-value: $8,500'}
Expected output:
Test 3: Crypto exchange (MCC 6051) Escalated: True Sensitive: {'passed': False, 'reason': 'Sensitive MCC: 6051'}
Expected output:
Test 4: Obvious fraud Escalated: False


Step 8: Monitoring quality in production

Your analyst is built, evaluated, and guarded. But production is unpredictable. Fraud patterns evolve, new merchant categories emerge, and model quality can drift silently. Without monitoring, you only discover these problems when chargebacks spike, and by then the damage is done.
Weave Monitors solves this by sampling production traffic and scoring it with a separate LLM judge in the background, without adding any latency to transaction decisions. If guardrails are the circuit breaker, monitors are the smoke detector; they do not stop anything from happening; they alert you early so you can investigate before a small issue becomes a big one.

Setting up the monitor

Navigate to your Weave project in the W&B UI and click the Monitors tab. Here is how to configure a quality monitor step by step:
  1. Click New Monitor and give it the name fraud_decision_quality
  2. Under Operations, select run_fraud_analyst
  3. Set the Sampling rate to 20%
  4. For the Judge model, select meta-llama/Llama-3.3-70B-Instruct from W&B Inference. This is the JUDGE_MODEL we defined at the top, we intentionally use a different model than the analyst to avoid self-evaluation bias
  5. Set the Scoring prompt to:
You are a senior fraud reviewer auditing an AI analyst's decision. Transaction data: {inputs} Analyst decision: {output} Rate the decision on these dimensions and respond ONLY with a JSON object: {{ "judge_agrees": true or false, "reasoning_quality": 0.0 to 1.0, "missed_signals": ["list of signals the analyst missed"], "overall_quality_score": 0.0 to 1.0, "feedback": "Brief explanation" }}
6. Click Create Monitor

Once active, Weave automatically scores 20% of incoming run_fraud_analyst calls.
In individual traces: Each scored call gets a nested LLMAsAJudgeScorer.score child trace. Click on it to see the judge's full reasoning.

In the monitor dashboard: View aggregate scores over time. This is where you catch drift. If the judge agreement rate drops from 95% to 80% over a week, something changed: a new fraud pattern, a model regression, or a shift in transaction mix, and you need to investigate.

What to watch for

The signals that matter most in production:
  • 📉 Quality drift: A declining judge agreement rate may signal new fraud patterns the analyst was not trained to handle, or degraded enrichment data quality.
  • ⏱️ Latency trends: Rising response times could mean the enrichment services are slow or the model is generating unnecessarily long reasoning. Weave's Traces table lets you sort by latency to find outliers.
  • 💰 Cost trends: If average token usage per transaction is climbing, the model may be producing verbose reasoning. Compare V1 and V2 costs in the Evaluations tab to quantify savings.
  • 🚨 Escalation rate: Track how often guardrails trigger. A rising rate could mean thresholds are too aggressive (hurting good customers), or the analyst is encountering transaction types it cannot handle.

Simulating production traffic

Let us simulate production traffic to generate data for the monitor:
@weave.op()
async def run_production_pipeline(
enriched_transaction: dict,
) -> dict:
"""Production wrapper: guardrails on every call, monitor scores a sample."""
result = await run_guarded_analyst(enriched_transaction)
# The UI-configured monitor automatically scores a sample of
# run_fraud_analyst calls no extra code needed here.
return result


print("Running 15 production transactions...\n")
random.seed(42)
approved = declined = escalated = 0

for i in range(15):
is_fraud = random.random() < 0.3
txn = gen_fraud(f"prod-{i:03d}") if is_fraud else gen_legit(f"prod-{i:03d}")
r = asyncio.run(run_production_pipeline(txn.model_dump()))

decision = r["decision"]
if r["escalated"]:
fv = "escalate_to_human"
escalated += 1
else:
fv = decision.get("verdict", "unknown")
if fv == "approve":
approved += 1
else:
declined += 1

tag = "FRAUD" if is_fraud else "LEGIT"
amt = txn.transaction.amount_usd
merch = txn.transaction.merchant_name
esc_tag = " [ESCALATED]" if r["escalated"] else ""
print(f" [{i+1:2d}] {tag:>5} ${amt:>8,.2f} {merch:<20} -> {fv:<18}{esc_tag}")

print(f"\n✓ Approved={approved} Declined={declined} Escalated={escalated}")
print("✓ Check the Monitors tab in Weave to see judge scores on sampled calls!")
Expected output:
[ 1] LEGIT $ 7.55 Amazon.com -> Verdict.APPROVE [ 2] LEGIT $ 16.12 Spotify -> Verdict.APPROVE [ 3] FRAUD $ 140.78 CryptoXchange -> escalate_to_human [ESCALATED] [ 4] FRAUD $ 870.05 Uber Eats -> Verdict.DECLINE [ 5] FRAUD $ 369.57 CryptoXchange -> escalate_to_human [ESCALATED] [ 6] LEGIT $ 5.68 Spotify -> Verdict.APPROVE [ 7] LEGIT $ 45.79 Amazon.com -> Verdict.APPROVE [ 8] LEGIT $ 22.53 Amazon.com -> Verdict.APPROVE [ 9] FRAUD $ 108.60 Uber Eats -> Verdict.DECLINE [10] LEGIT $ 61.05 Amazon.com -> Verdict.APPROVE [11] LEGIT $ 92.85 Netflix -> Verdict.APPROVE [12] FRAUD $ 748.10 Amazon.com -> Verdict.DECLINE [13] FRAUD $ 89.38 CryptoXchange -> escalate_to_human [ESCALATED] [14] LEGIT $ 24.31 Amazon.com -> Verdict.APPROVE [15] LEGIT $ 46.12 Amazon.com -> Verdict.APPROVE ✓ Approved=9 Declined=3 Escalated=3 ✓ Check the Monitors tab in Weave to see judge scores on sampled calls!

Conclusion

Over the course of this tutorial, we built a fraud triage copilot from the ground up and integrated all four W&B Weave products to make it production-ready.
  1. We started with Traces, which gave us X-ray vision into the analyst's decision-making. Every enrichment lookup, LLM call, and parsed verdict was captured automatically, turning debugging from guesswork into straightforward inspection.
  2. Next, Evaluations let us test the analyst against a synthetic dataset of 40 transactions, compare a verbose V1 prompt against a concise V2, and prove the improvement with hard numbers rather than intuition.
  3. Guardrails added three layers of runtime safety, which are confidence gating, sensitive transaction blocking, and reasoning contradiction detection, that intercept dangerous decisions before they reach downstream systems, with every trigger fully auditable through Traces.
  4. Finally, Monitors closed the loop by sampling production traffic with an LLM judge to detect quality drift before chargebacks spike.

Production checklist

Before deploying your fraud triage analyst, verify:
  • All enrichment tools and the analyst function are decorated with @weave.op()
  • Evaluation scores meet your thresholds (95%+ accuracy, <10s latency per decision)
  • Guardrails tested with edge cases (high-value transactions, sensitive MCCs, contradictory reasoning)
  • At least one monitor is active at 10% to 25% sampling rate
  • Human escalation paths are tested and reachable

Next steps

To take this further, you could replace the synthetic generators with real transaction data pipelines, integrate live velocity and device intelligence APIs, add PII-safe logging using Weave's built-in redaction capabilities, or build a feedback loop in which human analysts label escalated cases, and those labels feed back into future evaluations. Each change produces new traces and evaluation results you can compare directly in the Weave UI. For a deeper dive into Weave, check out the free W&B Weave course.
For more W&B tutorials and guides: