How to Build a loan approval Agent Using AutoGen in Python for healthcare
A loan approval agent for healthcare decides whether a financing request should move forward, be rejected, or be sent to a human underwriter. In healthcare, that matters because the decision often touches patient affordability, provider cash flow, HIPAA-bound data, and regulated lending workflows that need traceability end to end.
Architecture
- •
Intake layer
- •Receives loan applications from clinic billing systems, provider portals, or internal ops tools.
- •Normalizes fields like requested amount, revenue history, payer mix, and entity type.
- •
Policy and compliance agent
- •Checks healthcare-specific rules before any underwriting step.
- •Enforces HIPAA-safe handling, minimum data access, and jurisdiction/data residency constraints.
- •
Underwriting agent
- •Evaluates financial risk using structured application data.
- •Produces a recommendation with reasons, not just a binary approve/reject.
- •
Document review agent
- •Extracts facts from tax returns, bank statements, AR aging reports, and license documents.
- •Flags missing or inconsistent documents for human review.
- •
Supervisor / orchestrator
- •Coordinates the agents and stops the workflow when policy is violated.
- •Escalates ambiguous cases to a human underwriter.
- •
Audit logger
- •Stores every decision input, intermediate output, and final recommendation.
- •Required for model governance, dispute handling, and compliance review.
Implementation
1) Install AutoGen and define the agent roles
Use the modern autogen-agentchat package. For a production service, keep the LLM configuration explicit so you can swap models without changing orchestration code.
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination
from autogen_ext.models.openai import OpenAIChatCompletionClient
model_client = OpenAIChatCompletionClient(
model="gpt-4o-mini",
api_key="YOUR_OPENAI_API_KEY",
)
policy_agent = AssistantAgent(
name="policy_agent",
model_client=model_client,
system_message=(
"You are a healthcare lending policy reviewer. "
"Check HIPAA-safe handling, consent requirements, data residency constraints, "
"and whether the case must be escalated to a human."
),
)
underwriter_agent = AssistantAgent(
name="underwriter_agent",
model_client=model_client,
system_message=(
"You are a loan underwriting analyst for healthcare providers. "
"Use only the supplied application facts. "
"Return approve/reject/escalate with concise reasons."
),
)
auditor_agent = AssistantAgent(
name="auditor_agent",
model_client=model_client,
system_message=(
"You are an audit logger. Summarize the decision path in a structured way "
"for compliance review."
),
)
2) Build the orchestration flow
This pattern keeps policy review first. If policy fails, you stop before underwriting touches sensitive data. The termination condition below ends the chat when the auditor produces a final record.
termination = TextMentionTermination("AUDIT_COMPLETE")
team = RoundRobinGroupChat(
participants=[policy_agent, underwriter_agent, auditor_agent],
termination_condition=termination,
)
application = """
Loan request:
- Borrower: Riverside Cardiology Group
- Entity type: medical practice
- Requested amount: $750000
- Purpose: equipment financing
- Monthly revenue: $220000
- Debt service coverage ratio: 1.45
- Documents: bank statements, AR aging report, provider license
- Data residency: US-only storage required
- Patient data present in source docs: yes
"""
result = await team.run(task=application)
print(result.messages[-1].content)
3) Add explicit guardrails in the policy agent
For healthcare lending you do not want free-form reasoning over raw clinical content. Force the policy agent to classify risk first and only pass sanitized facts downstream.
policy_task = """
Review this healthcare loan application for policy issues only.
Return exactly one of:
- CLEAR_TO_UNDERWRITE
- ESCALATE_HUMAN_REVIEW
- REJECT_POLICY_VIOLATION
Rules:
- If patient PHI appears in source docs without need for credit decisioning, escalate.
- If US-only storage is required but cannot be guaranteed, reject.
- If missing consent or authorization is implied for document processing, escalate.
"""
policy_result = await policy_agent.run(task=policy_task + "\n\n" + application)
print(policy_result.messages[-1].content)
4) Capture an audit trail with structured outputs
In production you want machine-readable records. Store the raw inputs plus each agent’s response so compliance can reconstruct the decision later.
import json
from datetime import datetime
audit_record = {
"timestamp": datetime.utcnow().isoformat(),
"borrower": "Riverside Cardiology Group",
"request_amount": 750000,
"policy_result": policy_result.messages[-1].content,
"final_decision": result.messages[-1].content if result.messages else None,
}
with open("loan_audit_log.jsonl", "a", encoding="utf-8") as f:
f.write(json.dumps(audit_record) + "\n")
Production Considerations
- •
Data residency
- •Pin inference endpoints to approved regions.
- •Block cross-region logging if borrower data must remain in-country or within a specific cloud boundary.
- •
HIPAA and PHI handling
- •Strip unnecessary PHI before sending text to the model.
- •Treat document OCR output as sensitive until redaction passes run successfully.
- •
Monitoring
- •Track escalation rate, false approvals, policy rejects, and average time to decision.
- •Alert on sudden changes in approval patterns by specialty group or geography.
- •
Guardrails
- •Use allowlisted fields only for underwriting decisions.
- •Require human sign-off for borderline DSCR values, incomplete documentation, or any case involving patient-level financial hardship data.
Common Pitfalls
- •
Letting underwriting read raw clinical notes
- •Avoid this by separating credit features from medical content.
- •Only pass revenue, repayment history, entity metadata, and approved document extracts into the underwriting step.
- •
Skipping an explicit policy gate
- •Do not let the underwriter agent decide first and “check compliance later.”
- •Put
policy_agentahead of everything else and fail closed on ambiguity.
- •
No auditability
- •If you cannot reconstruct why an approval happened, you cannot defend it during an internal review.
- •Log prompts, model outputs, timestamps, versioned policies, and final disposition in immutable storage.
- •
Treating all healthcare borrowers the same
- •A solo clinic buying imaging equipment is not identical to a multi-site hospital group refinancing receivables.
- •Tune thresholds by borrower type and require human escalation when structure changes materially.
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