Developer Documentation

Integration &
Modification Guide

This guide explains how to extend FraudShield AI — adding new models, wiring up a real Python backend, and planning production-grade improvements. Written for the developer who built this.

Step 01

Add a New Model

The entire UI — Gallery cards, navigation links, Testing Lab forms, and Deep-Dive charts — is generated dynamically from a single file: config/models.ts. To add a new model, you only touch this file and (optionally) lib/mockPredict.ts.

2-file addition checklist:

  • Open config/models.ts and append a new object to the models array.
  • Set a unique id (becomes the URL: /test/[id]).
  • Set type: 'numeric' for structured input or 'image' for document upload.
  • Populate inputFields[] (only needed for numeric type).
  • Add chart data for the deep-dive visualization.
  • Open lib/mockPredict.ts and add a case for your model id in the switch block.

config/models.ts — new entry

typescript
// config/models.ts

export const models: ModelConfig[] = [
  // ... existing models ...

  {
    id: "my-new-model",            // ← URL: /test/my-new-model
    name: "My New Model",
    type: "numeric",               // or "image"
    tagline: "Short one-liner description.",
    description: "Full description shown on the test page.",
    techStack: ["LightGBM", "Optuna", "FastAPI"],
    category: "Wire Transfer Fraud",
    architecture: "Architecture notes…",
    inputFields: [
      { name: "amount", label: "Amount ($)", placeholder: "e.g. 500", type: "number" },
      { name: "risk_score", label: "Risk Score", placeholder: "e.g. 0.7", type: "number" },
    ],
    stats: [
      { label: "Accuracy", value: "98.5%", highlight: true },
      { label: "Latency",  value: "< 20ms" },
    ],
    chartType: "precision-recall",  // or "shap"
    chartData: [                    // Your actual curve data
      { recall: 0.0, precision: 1.0 },
      { recall: 0.5, precision: 0.92 },
      { recall: 1.0, precision: 0.25 },
    ],
    color: "blue",                  // "blue" | "green" | "red"
  },
];

lib/mockPredict.ts — add mock handler

typescript
// lib/mockPredict.ts — add a case for your new model

export async function predict(input: PredictionInput): Promise<PredictionResult> {
  await new Promise((r) => setTimeout(r, 2000)); // Remove in production

  switch (input.modelId) {
    case "my-new-model":
      return mockMyNewModel(input.fields ?? {});
    // ... existing cases
  }
}

function mockMyNewModel(fields: Record<string, string>): PredictionResult {
  const amount = parseFloat(fields.amount ?? "0");
  const score = amount > 5000 ? 85 : 12;
  return {
    riskScore: score,
    verdict: score > 70 ? "FRAUD" : "SAFE",
    confidence: 0.92,
    reasoning: "Explanation of why this was flagged.",
    topFactors: [
      { factor: "Amount", contribution: `$${amount}`, direction: "up" },
    ],
    processingTime: 14,
    modelVersion: "lgbm-v1.0.0",
  };
}

Step 02

Connect a FastAPI Backend

All mock logic lives in lib/mockPredict.ts. The predict() function is the single integration seam — replace its internals with real fetch() calls to your FastAPI endpoints. The UI components are unchanged.

Step A — Build the endpoint

Create a POST route in FastAPI that receives your model inputs and returns the PredictionResult JSON schema.

Step B — Set env var

Add NEXT_PUBLIC_API_URL to your .env.local, pointing at your running FastAPI server.

Python — FastAPI endpoint

python
# Python FastAPI endpoint (backend/main.py)
from fastapi import FastAPI
from pydantic import BaseModel
import joblib, numpy as np

app = FastAPI()
model = joblib.load("models/transaction_xgb.pkl")

class TransactionRequest(BaseModel):
    amount: float
    v1: float
    v2: float
    hour: int

@app.post("/predict/transaction-xgb")
def predict(req: TransactionRequest):
    X = np.array([[req.amount, req.v1, req.v2, req.hour]])
    prob = float(model.predict_proba(X)[0][1])
    score = int(prob * 100)
    return {
        "riskScore": score,
        "verdict": "FRAUD" if score > 70 else "SUSPICIOUS" if score > 35 else "SAFE",
        "confidence": prob,
        "reasoning": f"Probability {prob:.3f} from XGBoost ensemble.",
        "topFactors": [],
        "processingTime": 12,
        "modelVersion": "xgb-v2.4.1"
    }

.env.local

bash
# .env.local
NEXT_PUBLIC_API_URL=http://localhost:8000

# For production:
# NEXT_PUBLIC_API_URL=https://your-api.fly.dev

lib/mockPredict.ts — replace with real fetch()

typescript
// lib/mockPredict.ts — replace the switch block with:

export async function predict(input: PredictionInput): Promise<PredictionResult> {
  const BASE_URL = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000";

  if (input.modelId === "document-cnn" && input.imageFile) {
    // Image model: multipart upload
    const form = new FormData();
    form.append("file", input.imageFile);
    const res = await fetch(`${BASE_URL}/predict/document-cnn`, {
      method: "POST",
      body: form,
    });
    return res.json();
  }

  // Numeric models: JSON POST
  const res = await fetch(`${BASE_URL}/predict/${input.modelId}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ fields: input.fields }),
  });
  return res.json();
}

⚠ CORS Configuration

Add fastapi.middleware.cors.CORSMiddleware to your FastAPI app and allow http://localhost:3000 (or your production domain) as an origin.

Step 03

Future Improvements

XAI Integration

Replace static SHAP chart data with live SHAP values returned per-prediction from your FastAPI endpoint. Add a waterfall chart showing each feature's exact contribution to a specific decision.

SHAPLIMEAnchors

Live Transaction Maps

Integrate Mapbox or deck.gl to render a real-time globe of incoming transactions. Flag fraudulent transactions as red spikes on the map. Filterable by model and verdict.

Mapboxdeck.glWebSockets

Human Feedback Loops

Add thumbs up/down feedback buttons to each Security Report. Store corrections in a Postgres table. Retrain models weekly using active learning with corrected labels.

Active LearningPostgresMLflow

Model Versioning & A/B Testing

Use MLflow Model Registry to version artifacts. Shadow-deploy new model versions alongside production, comparing risk score distributions before full rollout.

MLflowShadow ModeCanary

Reference

System Architecture

Frontend

Next.js 14 + Tailwind

  • Config-driven UI from models.ts
  • Framer Motion animations
  • Recharts visualizations
  • Dynamic /test/[modelId] routes

API Layer

FastAPI (Python)

  • POST /predict/{model_id}
  • Multipart for image models
  • JSON for numeric models
  • CORS + Auth middleware

ML Backend

scikit-learn / PyTorch

  • Serialized model artifacts
  • SHAP explainer objects
  • MLflow experiment tracking
  • Feature preprocessing pipelines
Browser → Next.js (Vercel)fetch() → FastAPI (Fly.io / Railway)joblib.load() → Pickle / ONNX