How to Build a loan approval Agent Using CrewAI in TypeScript for healthcare

By Cyprian AaronsUpdated 2026-04-21
loan-approvalcrewaitypescripthealthcare

A loan approval agent for healthcare evaluates financing requests for clinics, hospitals, and medical practices by pulling financial data, checking policy rules, and producing an approval recommendation with a traceable rationale. It matters because healthcare lending has tighter compliance pressure than generic SME lending: you need fast decisions without exposing protected data, violating residency rules, or producing explanations that can’t stand up to audit.

Architecture

  • Intake layer

    • Receives the loan application payload: borrower profile, requested amount, purpose, jurisdiction, and supporting documents.
    • Validates required fields before any agent runs.
  • Policy retrieval layer

    • Loads lending policy, credit thresholds, and healthcare-specific exclusions.
    • Keeps underwriting logic outside prompts so it can be versioned and audited.
  • Agent layer

    • One agent evaluates financial risk.
    • One agent checks compliance and healthcare constraints.
    • One agent synthesizes the final recommendation.
  • Tooling layer

    • Tools fetch KYC/KYB status, basic financial ratios, and document metadata.
    • Tools should never return raw PHI unless absolutely required.
  • Decision output layer

    • Produces a structured decision: approve, reject, or escalate.
    • Stores reasoning, evidence IDs, policy version, and reviewer trail.

Implementation

1) Install the TypeScript stack

CrewAI’s TypeScript package is still evolving in some environments, so pin versions and keep your runtime simple. You want Node.js 20+, strict TypeScript settings, and a place to wire external tools cleanly.

npm install @crewai/crewai zod dotenv
npm install -D typescript ts-node @types/node

Set up environment variables for your model provider and any internal services:

OPENAI_API_KEY=your_key
POLICY_VERSION=2026-01-01
DATA_REGION=us-east-1

2) Define the loan review tools

Keep tools narrow. For healthcare lending, tools should return only what the agents need to decide, not full source records.

import { z } from "zod";
import { Tool } from "@crewai/crewai";

export const getBorrowerSummary = new Tool({
  name: "get_borrower_summary",
  description: "Fetch sanitized borrower financial summary for underwriting.",
  schema: z.object({
    borrowerId: z.string(),
  }),
  execute: async ({ borrowerId }) => {
    // Replace with real service call
    return JSON.stringify({
      borrowerId,
      annualRevenue: 4200000,
      debtToIncome: 0.31,
      daysCashOnHand: 64,
      delinquentAccounts: false,
      residencyRegion: "us-east-1",
    });
  },
});

export const getHealthcarePolicy = new Tool({
  name: "get_healthcare_policy",
  description: "Return the active healthcare lending policy summary.",
  schema: z.object({
    jurisdiction: z.string(),
    loanAmount: z.number(),
    purpose: z.string(),
  }),
  execute: async ({ jurisdiction }) => {
    return JSON.stringify({
      jurisdiction,
      minDaysCashOnHand: 45,
      maxDebtToIncome: 0.45,
      requiresComplianceReviewAboveAmount: 250000,
      prohibitedPurposes: ["patient care discounts", "PHI-backed collateral"],
    });
  },
});

3) Create specialized agents and tasks

Use separate agents for risk, compliance, and final decisioning. That keeps the reasoning chain auditable and makes it easier to swap policies later.

import { Agent, Task } from "@crewai/crewai";
import { getBorrowerSummary, getHealthcarePolicy } from "./tools";

const riskAgent = new Agent({
  role: "Healthcare Loan Risk Analyst",
  goal: "Assess repayment risk using sanitized financial data.",
  backstory:
    "You underwrite loans for healthcare providers and focus on repayment capacity.",
  tools: [getBorrowerSummary],
});

const complianceAgent = new Agent({
  role: "Healthcare Compliance Reviewer",
  goal: "Check lending request against healthcare policy and residency constraints.",
  backstory:
    "You review loans for compliance issues including data residency and prohibited purposes.",
  tools: [getHealthcarePolicy],
});

const decisionTask = new Task({
  description:
    "Evaluate this healthcare loan application and return a structured recommendation with reasons.\n\nApplication:\n{application}",
});

const riskTask = new Task({
  description:
    "Assess financial risk for this healthcare borrower using available tools.\n\nBorrower ID:\n{borrowerId}",
});

const complianceTask = new Task({
  description:
    "Check this request against healthcare lending policy.\n\nJurisdiction:\n{jurisdiction}\nLoan Amount:\n{loanAmount}\nPurpose:\n{purpose}",
});

4) Run the crew and enforce structured output

The important pattern is to make the final result machine-readable. In production you do not want free-form prose as your only artifact.

import { Crew } from "@crewai/crewai";

async function main() {
  const crew = new Crew({
    agents: [riskAgent, complianceAgent],
    tasks: [riskTask, complianceTask],
    verbose: true,
    process: "sequential",
  });

  
const result = await crew.kickoff({
    borrowerId: "borrower_123",
    jurisdiction: "us-east-1",
    loanAmount: 300000,
    purpose: "equipment_purchase",
    application:
      JSON.stringify({
        borrowerId: "borrower_123",
        loanAmount: 300000,
        purpose: "equipment_purchase",
        jurisdiction: "us-east-1",
        entityType: "outpatient_clinic",
      }),
});

console.log(result);
}

main().catch(console.error);

In practice, add a final parser that converts the output into a decision object like this:

type LoanDecision = {
decisionType:"approve"|"reject"|"escalate";
policyVersion:string;
reasons:string[];
evidenceIds:string[];
}

That gives downstream systems something deterministic to store in your audit log.

Production Considerations

  • Deployment

    • Run the agent in a private VPC or equivalent isolated network.
    • Keep model calls region-bound when handling regulated healthcare data.
    • Separate the underwriting service from document storage so PHI access is tightly controlled.
  • Monitoring

Why does this matter? Track every kickoff() invocation with request ID, policy version, tool calls, latency, and final outcome.

Alert on high escalation rates or repeated “insufficient data” decisions; those usually indicate broken integrations or bad input quality.

  • Guardrails

Block any tool from returning raw clinical notes unless the workflow explicitly requires them.

Add prompt-injection filters on uploaded documents because lenders will receive PDFs with arbitrary text in them.

Enforce deterministic thresholds in code rather than trusting the model to remember policy cutoffs.

  • Auditability

Store the full decision bundle:

input hash, policy version, agent outputs, tool responses, final decision, human override.

That is what you need when compliance asks why a clinic was rejected or escalated.

Common Pitfalls

  1. Mixing underwriting logic into prompts

    • If your approval threshold lives only in natural language instructions, it will drift.
    • Put thresholds in config or policy services and pass them into the agent as read-only context.
  2. Returning too much sensitive data from tools

    • A tool that dumps full patient-adjacent records creates unnecessary exposure.
    • Return sanitized summaries only; redact identifiers unless they are needed for matching or audit.
  3. Skipping human review for edge cases

    • Healthcare loans often involve unusual revenue patterns like seasonal reimbursements or payer concentration.
    • Escalate borderline cases instead of forcing a binary model answer; use human approval above defined risk thresholds.
  4. Ignoring residency requirements

    • If your lender operates across regions, do not route regulated data through an unconstrained global endpoint.
    • Pin compute and storage to approved regions and verify it at runtime before any tool execution.

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