How to Build a transaction monitoring Agent Using AutoGen in TypeScript for insurance

By Cyprian AaronsUpdated 2026-04-21
transaction-monitoringautogentypescriptinsurance

A transaction monitoring agent for insurance watches policy, premium, claims, and payout activity for patterns that look suspicious, inconsistent, or non-compliant. It matters because insurers need to catch fraud, money laundering signals, duplicate claims, premium manipulation, and unusual payout behavior before they become losses or regulatory problems.

Architecture

  • Event ingestion layer

    • Pulls transactions from policy admin systems, claims platforms, payment processors, and case management tools.
    • Normalizes each event into a consistent schema with policy ID, claimant ID, amount, timestamp, jurisdiction, and channel.
  • AutoGen agent runtime

    • Uses AssistantAgent to reason over events and classify risk.
    • Uses UserProxyAgent as the execution/orchestration layer for tool calls and controlled action execution.
  • Risk rules + LLM reasoning

    • Combines deterministic checks like threshold breaches and duplicate payouts with LLM-based pattern analysis.
    • Keeps high-confidence compliance rules outside the model.
  • Audit store

    • Persists every alert, model output, tool call, and final decision.
    • Needed for regulator review, internal audit, and dispute handling.
  • Case management connector

    • Pushes flagged transactions into SIU / fraud ops queues.
    • Adds human review status so the agent never becomes the final authority on sensitive decisions.
  • Policy guardrails

    • Enforces data residency, redaction of PII where possible, and jurisdiction-specific rules.
    • Prevents the agent from exposing protected customer data in logs or prompts.

Implementation

1) Install AutoGen and define your transaction shape

For TypeScript in Node.js, use the AutoGen packages that expose AssistantAgent and UserProxyAgent. Keep the transaction payload small and explicit; insurance workflows are full of regulated fields you do not want drifting through prompts uncontrolled.

npm install @autogenai/agent-runtime zod
import { z } from "zod";

export const TransactionSchema = z.object({
  transactionId: z.string(),
  policyId: z.string(),
  claimantId: z.string(),
  amount: z.number().positive(),
  currency: z.string().length(3),
  type: z.enum(["premium_payment", "claim_payout", "refund", "endorsement_adjustment"]),
  jurisdiction: z.string(),
  channel: z.enum(["portal", "agent", "call_center", "bank_transfer"]),
  createdAt: z.string(),
});

export type Transaction = z.infer<typeof TransactionSchema>;

2) Create an assistant that classifies risk

The key pattern is to make the assistant produce structured output only. In insurance monitoring you want a short explanation plus a risk label that downstream systems can route on.

import { AssistantAgent } from "@autogenai/agent-runtime";

export const monitoringAgent = new AssistantAgent({
  name: "insurance_transaction_monitor",
  systemMessage: `
You review insurance transactions for fraud, compliance issues, and unusual activity.
Return only JSON with:
{
  "riskLevel": "low" | "medium" | "high",
  "reason": string,
  "recommendedAction": "approve" | "review" | "escalate"
}
Do not provide legal advice. Do not mention hidden chain-of-thought.
`,
});

3) Add deterministic pre-checks before the model runs

Do not ask the model to rediscover obvious controls like duplicate payouts or threshold violations. Run those first and pass the result into the agent as context. This reduces cost and keeps compliance logic auditable.

type RuleResult = {
  ruleFlags: string[];
};

function evaluateRules(tx: Transaction): RuleResult {
  const ruleFlags: string[] = [];

  if (tx.type === "claim_payout" && tx.amount > 25000) {
    ruleFlags.push("high_value_claim_payout");
  }

  if (tx.type === "refund" && tx.channel === "bank_transfer") {
    ruleFlags.push("refund_to_bank_account");
  }

  if (tx.jurisdiction === "US-NY" && tx.amount > 10000) {
    ruleFlags.push("nyc_high_value_review_threshold");
  }

   return { ruleFlags };
}

4) Orchestrate with UserProxyAgent and persist an audit trail

Use UserProxyAgent to control execution. In production this is where you gate external actions like opening a case or sending alerts. The example below shows the real pattern: validate input, run rules, call the assistant with a structured prompt, then write an audit record.

import { AssistantAgent, UserProxyAgent } from "@autogenai/agent-runtime";
import { TransactionSchema } from "./schema";

const userProxy = new UserProxyAgent({
  name: "monitoring_orchestrator",
});

async function monitorTransaction(rawTx: unknown) {
    const tx = TransactionSchema.parse(rawTx);
    const ruleResult = evaluateRules(tx);

    const prompt = `
Transaction:
${JSON.stringify(tx)}

Deterministic flags:
${JSON.stringify(ruleResult.ruleFlags)}

Classify this transaction for insurance fraud/compliance monitoring.
`;

    const response = await userProxy.initiateChat(monitoringAgent, {
      message: prompt,
    });

    const resultText = response.chatHistory.at(-1)?.content ?? "{}";
    const decision = JSON.parse(resultText);

    await saveAuditRecord({
      transactionId: tx.transactionId,
      policyId: tx.policyId,
      ruleFlags: ruleResult.ruleFlags,
      decision,
      modelName: monitoringAgent.name,
      timestamp: new Date().toISOString(),
    });

    if (decision.recommendedAction === "escalate") {
      await createCaseInFraudQueue(tx.transactionId, decision.reason);
    }

    return decision;
}

async function saveAuditRecord(record: unknown) {
    console.log("AUDIT:", JSON.stringify(record));
}

async function createCaseInFraudQueue(transactionId: string, reason: string) {
    console.log(`CASE CREATED ${transactionId}: ${reason}`);
}

Production Considerations

  • Keep regulated data local

    • Insurance data often has residency constraints by country or state.
    • Redact PII before sending prompts to the model when full identity fields are not required for classification.
  • Make every decision auditable

    • Store raw input hash, rule hits, model version, prompt version, output JSON, and downstream action.
    • Regulators will care more about traceability than model elegance.
  • Separate detection from enforcement

    • The agent should flag and route cases.
    • Final actions like payment holds or claim denial should require human approval or a separate policy engine.
  • Monitor drift by line of business

    • Fraud patterns differ between auto claims, property claims, life payouts, and premium collections.
    • Track false positives per product line so one noisy segment does not poison operations.

Common Pitfalls

  • Putting all compliance logic inside the LLM

    • Bad move. Thresholds, sanctions checks, duplicate detection, and jurisdiction rules should be deterministic.
    • Use the agent for judgment on ambiguous cases only.
  • Skipping structured outputs

    • Free-form text is hard to route into SIU queues or dashboards. ,Force JSON output with a fixed schema so your pipeline can validate it before actioning anything.
  • Ignoring audit requirements ,If you cannot explain why a transaction was flagged six months later, ,you do not have a production system. ,Persist inputs, outputs,,rule flags,,and model metadata for every decision.


Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides