How to Build a fraud detection Agent Using AutoGen in TypeScript for healthcare
A fraud detection agent for healthcare ingests claims, eligibility events, and provider/member signals, then flags suspicious patterns like upcoding, duplicate billing, phantom services, and identity misuse. It matters because healthcare fraud is not just a financial problem; it directly affects patient trust, reimbursement integrity, and compliance posture.
Architecture
- •
Claim ingestion layer
- •Pulls claims from a queue, API, or batch file.
- •Normalizes CPT/HCPCS codes, ICD-10 codes, provider IDs, member IDs, dates, and amounts.
- •
Policy and rules engine
- •Applies deterministic checks first.
- •Catches obvious violations like duplicate claim submissions, impossible service dates, and out-of-network anomalies.
- •
AutoGen agent group
- •Uses specialized agents for investigation:
- •
AssistantAgentfor reasoning over the claim context - •
UserProxyAgentfor tool execution and orchestration
- •
- •Produces a structured fraud risk assessment.
- •Uses specialized agents for investigation:
- •
Evidence retrieval tools
- •Queries internal systems for claim history, provider profile, prior authorizations, and eligibility.
- •Keeps the agent grounded in auditable facts.
- •
Decision and case routing layer
- •Converts the agent output into
approve,review, orescalate. - •Opens a case in the SIU workflow when risk crosses a threshold.
- •Converts the agent output into
Implementation
1) Install AutoGen and define a strict claim schema
For healthcare workflows, do not let the agent reason over free-form blobs. Shape the input into a typed object so your downstream audit trail stays clean.
npm install @autogenai/autogen zod
import { z } from "zod";
const ClaimSchema = z.object({
claimId: z.string(),
memberId: z.string(),
providerId: z.string(),
facilityId: z.string().optional(),
serviceDate: z.string(), // ISO date
submittedAt: z.string(), // ISO date
totalAmount: z.number(),
diagnosisCodes: z.array(z.string()),
procedureCodes: z.array(z.string()),
placeOfService: z.string(),
});
type Claim = z.infer<typeof ClaimSchema>;
2) Create an AutoGen assistant that scores fraud risk
Use AssistantAgent to analyze the claim context. Keep the system message narrow: risk scoring only, no medical advice, no coverage determination.
import { AssistantAgent } from "@autogenai/autogen";
export const fraudAnalyst = new AssistantAgent({
name: "fraud_analyst",
systemMessage: [
"You are a healthcare fraud detection analyst.",
"Assess claims for fraud indicators using only provided evidence.",
"Return concise findings with risk score from 0 to 100.",
"Do not infer protected health information beyond the input.",
"Do not provide clinical advice or coverage decisions."
].join(" "),
});
3) Add tool execution with UserProxyAgent
In AutoGen TypeScript workflows, UserProxyAgent is the control plane. Use it to call internal tools and pass evidence back to the assistant. This pattern keeps PHI access explicit and auditable.
import { UserProxyAgent } from "@autogenai/autogen";
async function fetchClaimHistory(memberId: string) {
return {
priorClaims30d: 4,
duplicateProviders: ["PRV-8821"],
highValueClaims90d: true,
};
}
async function fetchProviderProfile(providerId: string) {
return {
specialty: "Dermatology",
excludedFromNetwork: false,
priorInvestigations: true,
};
}
const orchestrator = new UserProxyAgent({
name: "orchestrator",
});
export async function assessClaim(claimInput: unknown) {
const claim = ClaimSchema.parse(claimInput);
const [history, provider] = await Promise.all([
fetchClaimHistory(claim.memberId),
fetchProviderProfile(claim.providerId),
]);
const prompt = `
Claim:
${JSON.stringify(claim)}
Member history:
${JSON.stringify(history)}
Provider profile:
${JSON.stringify(provider)}
Task:
Identify fraud indicators such as duplicate billing, upcoding signals,
phantom services, unbundling patterns, or suspicious utilization.
Return JSON with fields:
riskScore:number,
decision:"approve"|"review"|"escalate",
reasons:string[],
evidence:string[]
`;
const result = await orchestrator.initiateChat(fraudAnalyst, prompt);
return result;
}
4) Parse the response and route cases
Do not let raw model text drive production decisions. Enforce JSON parsing and threshold-based routing outside the model.
type FraudResult = {
riskScore: number;
decision: "approve" | "review" | "escalate";
reasons: string[];
evidence: string[];
};
export function routeFraudCase(resultText: string): FraudResult {
const parsed = JSON.parse(resultText) as FraudResult;
if (parsed.riskScore >= 85) return { ...parsed, decision: "escalate" };
if (parsed.riskScore >= 50) return { ...parsed, decision: "review" };
return { ...parsed, decision: "approve" };
}
Production Considerations
- •Compliance first
Use HIPAA-aligned access controls around every tool call. The agent should never see more PHI than it needs for the specific investigation.
- •Auditability
Log the input claim ID, retrieved evidence IDs, model output JSON, final routing decision, and human reviewer actions. In healthcare audits, you need to show why a case was flagged.
- •Data residency
Keep inference inside your approved region. If your organization has residency constraints for PHI or payer data, deploy AutoGen services in-region and avoid cross-border telemetry exports.
- •Guardrails
Use deterministic rules before LLM reasoning. The agent should assist investigators, not replace adjudication logic or make final payment decisions without human review on high-risk cases.
Common Pitfalls
- •
Sending raw PHI into prompts
- •Avoid full charts or notes unless they are necessary.
- •Redact names where possible and pass only claim-relevant fields.
- •
Letting the model decide without structured thresholds
- •Do not accept free-form “this looks fraudulent” outputs.
- •Require JSON with numeric risk scores and route cases using code.
- •
Skipping evidence retrieval
- •A fraud agent without historical context produces noisy alerts.
- •Always enrich claims with provider history, duplicate billing signals, authorization status, and prior utilization before asking for a judgment.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
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