How to Build a underwriting Agent Using AutoGen in TypeScript for healthcare
A healthcare underwriting agent reviews member or patient data, policy rules, and clinical constraints to decide whether a case is eligible, needs manual review, or should be declined. It matters because underwriting in healthcare is high-stakes: bad decisions create compliance risk, delayed coverage, and expensive manual ops.
Architecture
- •
Input adapter
- •Normalizes intake from EHR exports, claims summaries, eligibility files, or broker submissions.
- •Redacts unnecessary PHI before the LLM sees it.
- •
Underwriting policy engine
- •Encodes plan rules, exclusions, age bands, waiting periods, and state-specific constraints.
- •Keeps deterministic logic outside the model.
- •
AutoGen agent
- •Interprets the case summary and produces a structured underwriting recommendation.
- •Must be constrained to classification and rationale generation, not free-form medical advice.
- •
Tool layer
- •Fetches policy documents, benefit tables, and audit metadata.
- •Writes decision logs for compliance review.
- •
Human review queue
- •Captures ambiguous or high-risk cases.
- •Required for adverse decisions and edge cases involving protected classes or incomplete records.
- •
Audit store
- •Persists prompt inputs, model outputs, tool calls, and final decision codes.
- •Needed for traceability, appeals, and regulator review.
Implementation
1) Install AutoGen and define your underwriting schema
Use the AutoGen TypeScript package and keep the output shape strict. Underwriting should return a structured object that downstream systems can validate.
npm install @autogenai/autogen openai zod
import { z } from "zod";
export const UnderwritingDecisionSchema = z.object({
decision: z.enum(["approve", "manual_review", "decline"]),
riskScore: z.number().min(0).max(100),
rationale: z.string(),
requiredFollowUp: z.array(z.string()).default([]),
});
export type UnderwritingDecision = z.infer<typeof UnderwritingDecisionSchema>;
2) Create an AutoGen assistant with a strict system prompt
The agent should only assess against plan rules and summarize why. Do not let it invent clinical facts or infer protected attributes.
import { AssistantAgent } from "@autogenai/autogen";
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const underwritingAgent = new AssistantAgent({
name: "healthcare_underwriter",
modelClient: client,
systemMessage: `
You are a healthcare underwriting assistant.
Only use the provided case facts and plan rules.
Do not infer diagnosis beyond what is explicitly provided.
Do not use race, ethnicity, religion, gender identity, or other protected traits in decisions.
Return concise underwriting recommendations with rationale.
If information is missing or ambiguous, choose manual_review.
`,
});
3) Add a tool for policy lookup and run the agent
In production, your policy rules should come from versioned config or a rules service. Here I’m using a simple function as a tool pattern that you can replace with your internal service.
type CaseInput = {
age: number;
state: string;
tobaccoUse: boolean;
chronicConditions: string[];
requestedPlanId: string;
};
function getPlanRules(planId: string) {
const rules = {
basic_hmo_01: {
maxAge: 65,
excludeConditions: ["end_stage_renal_disease"],
requiresReviewConditions: ["recent_cancer_treatment", "organ_transplant"],
},
};
return rules[planId as keyof typeof rules];
}
export async function underwriteCase(input: CaseInput) {
const planRules = getPlanRules(input.requestedPlanId);
const prompt = `
Case:
${JSON.stringify(input)}
Plan rules:
${JSON.stringify(planRules)}
Return JSON with:
decision (approve|manual_review|decline),
riskScore (0-100),
rationale,
requiredFollowUp
`;
const result = await underwritingAgent.run(prompt);
const text = typeof result === "string" ? result : JSON.stringify(result);
return text;
}
4) Parse and validate the response before persisting it
Never trust model output directly. Validate it with Zod and only then write to your decision store.
import { UnderwritingDecisionSchema } from "./schema";
async function main() {
const raw = await underwriteCase({
age: 58,
state: "CA",
tobaccoUse: false,
chronicConditions: ["hypertension"],
requestedPlanId: "basic_hmo_01",
});
const parsed = JSON.parse(raw);
const decision = UnderwritingDecisionSchema.parse(parsed);
console.log("Underwriting decision:", decision);
// Persist to audit log here with request ID, model version, timestamps, and rule version.
}
main().catch((err) => {
console.error(err);
});
Production Considerations
- •
Keep PHI out of prompts where possible
- •Send only the minimum necessary fields. -identified summaries beat raw clinical notes every time.
- •
Log every decision path
- •Store prompt hash, rule version, model version, tool outputs, final JSON response, and reviewer override status.
- •
That gives you auditability for appeals and internal compliance checks.
- •
Pin data residency
- •If you operate in regulated markets, route inference through approved regions only.
- •
Make sure your vendor contract covers storage location and retention of prompt data.
- •
Add hard guardrails
- •Reject outputs that are not valid JSON or that contain unsupported decisions.
- •
Route any decline recommendation to human review if required by policy or jurisdiction.
Common Pitfalls
- •
Using free-form natural language output
- •This breaks downstream automation fast.
- •
Always force structured JSON with schema validation before any business action.
- •
Letting the model make policy
- •The agent should apply rules; it should not invent them.
- •
Keep eligibility thresholds in code or a rules engine so compliance can review changes.
- •
Ignoring protected-class leakage
- •Healthcare data often contains indirect proxies like ZIP code or medications that can correlate with sensitive traits.
- •
Strip unnecessary fields and run regular bias reviews on historical decisions.
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