How to Build a customer support Agent Using CrewAI in TypeScript for lending

By Cyprian AaronsUpdated 2026-04-21
customer-supportcrewaitypescriptlending

A customer support agent for lending handles borrower questions, explains loan status, collects missing documents, and routes cases that need human review. It matters because lending support sits at the intersection of customer experience, compliance, and risk: one bad answer can create regulatory exposure or a broken underwriting flow.

Architecture

  • Support intake layer

    • Receives chat, email, or portal requests.
    • Normalizes the message into a structured case object with borrower ID, loan ID, intent, and urgency.
  • Policy and product knowledge layer

    • Pulls from approved lending policies, FAQ content, fee schedules, and servicing rules.
    • Must be versioned so every answer can be traced back to the exact policy snapshot.
  • CrewAI agent layer

    • Uses a SupportAgent to classify intent and draft responses.
    • Uses a ComplianceAgent to check wording against lending rules before anything is sent.
  • Tooling layer

    • Exposes tools for loan lookup, document status checks, repayment schedule retrieval, and ticket creation.
    • Tools should be read-only unless explicitly required for case handling.
  • Escalation layer

    • Routes disputes, hardship requests, adverse action questions, and legal complaints to humans.
    • Logs the reason for escalation for auditability.
  • Audit and observability layer

    • Stores prompts, tool calls, model outputs, final responses, and policy versions.
    • Needed for complaint handling, QA reviews, and regulatory audits.

Implementation

1) Install dependencies and define the support case shape

CrewAI in TypeScript is usually wired around agents plus tools. For lending support, keep your case object strict so you do not pass raw PII through every step.

npm install @crewai/core zod
// support-case.ts
import { z } from "zod";

export const SupportCaseSchema = z.object({
  borrowerId: z.string(),
  loanId: z.string(),
  channel: z.enum(["chat", "email", "portal"]),
  intent: z.enum([
    "payment_status",
    "statement_copy",
    "document_request",
    "repayment_plan",
    "complaint",
    "other",
  ]),
  message: z.string(),
  locale: z.string().default("en-US"),
});

export type SupportCase = z.infer<typeof SupportCaseSchema>;

2) Create lending tools for safe system access

Keep tools narrow. The agent should not invent loan data; it should fetch it from source systems.

// tools.ts
import { Tool } from "@crewai/core";

export const getLoanStatusTool = new Tool({
  name: "get_loan_status",
  description: "Fetch current loan status by loanId.",
  execute: async ({ loanId }: { loanId: string }) => {
    // Replace with real service call
    return {
      loanId,
      status: "current",
      nextDueDate: "2026-05-01",
      outstandingBalance: "18420.55",
      currency: "USD",
    };
  },
});

export const getDocumentChecklistTool = new Tool({
  name: "get_document_checklist",
  description: "Return missing documents for a lending application or servicing request.",
  execute: async ({ borrowerId }: { borrowerId: string }) => {
    return {
      borrowerId,
      missingDocuments: ["Proof of income", "Bank statement"],
      dueDate: "2026-04-28",
    };
  },
});

3) Build the CrewAI agents and wire them into a crew

Use one agent for customer support drafting and another for compliance review. That split keeps your model from mixing helpful language with risky promises.

// crew.ts
import { Agent, Crew, Task } from "@crewai/core";
import { getLoanStatusTool, getDocumentChecklistTool } from "./tools";

const supportAgent = new Agent({
  role: "Lending Support Specialist",
  goal:
    "Answer borrower questions accurately using approved servicing data and escalate anything risky.",
  backstory:
    "You work in regulated lending support. You never guess on balances, fees, eligibility, or legal rights.",
});

const complianceAgent = new Agent({
  role: "Lending Compliance Reviewer",
  goal:
    "Review draft responses for policy violations, misleading statements, and unapproved commitments.",
  backstory:
    "You enforce fair lending, complaint handling standards, data privacy controls, and audit requirements.",
});

supportAgent.tools = [getLoanStatusTool, getDocumentChecklistTool];

export const buildCrew = () =>
  new Crew({
    agents: [supportAgent, complianceAgent],
    tasks: [
      new Task({
        description:
          "Given the incoming support case, retrieve only the needed account facts and draft a concise response.",
        expectedOutput:
          "A customer-ready response plus an escalation flag if the issue requires human review.",
        agent: supportAgent,
      }),
      new Task({
        description:
          "Review the drafted response for compliance issues. Reject any claim about rates, approvals, fees waivers, or legal rights that is not supported by policy.",
        expectedOutput:
          "Approved response or a corrected version with rationale.",
        agent: complianceAgent,
      }),
    ],
    verbose: true,
  });

4) Run the workflow from your API handler

The handler validates input first. Then it hands a normalized case to CrewAI and returns either an approved reply or an escalation path.

// handler.ts
import { SupportCaseSchema } from "./support-case";
import { buildCrew } from "./crew";

export async function handleSupportRequest(input: unknown) {
  const supportCase = SupportCaseSchema.parse(input);
  const crew = buildCrew();

  const result = await crew.kickoff({
    inputs: {
      borrowerId: supportCase.borrowerId,
      loanId: supportCase.loanId,
      channel: supportCase.channel,
      intent: supportCase.intent,
      message: supportCase.message,
      locale: supportCase.locale,
    },
  });

  return {
    caseId: `${supportCase.loanId}-${Date.now()}`,
    output: result,
    needsHumanReview:
      /escalat|complaint|legal|dispute/i.test(String(result)),
  };
}

Production Considerations

  • Deploy in-region

    Keep prompts, tool calls, logs, and retrieved documents inside the same region as your lending data store when possible. Data residency matters if you serve multiple jurisdictions.

  • Log everything needed for audit

    Persist input payloads after redaction, tool outputs, policy document versions, model name/version, timestamps, and final response text. If a regulator asks why the agent said something about repayment terms or fees, you need traceability.

  • Add hard guardrails before generation

    Block unsupported intents like legal advice or credit decision explanations unless you have approved templates. For adverse action or dispute-related topics, force escalation instead of free-form generation.

  • Monitor answer quality by intent

    Track containment rate separately for payment status questions versus complaints versus document requests. In lending support this helps you spot where the agent is overconfident or under-escalating.

Common Pitfalls

  1. Letting the agent answer from memory

    • Mistake: asking it to explain balances or due dates without calling source-of-truth tools.
    • Fix: require tool-backed answers for any account-specific statement.
  2. Mixing compliance review into the same prompt as customer response drafting

    • Mistake: one agent generates both the answer and its own approval.
    • Fix: separate drafting and review into distinct agents or tasks so there is an actual control point.
  3. Ignoring jurisdiction-specific rules

    • Mistake: using one generic response template across all borrowers.
    • Fix: route by locale and product type so disclosures match local lending requirements and servicing policies.
  4. Not redacting sensitive data in logs

    • Mistake: storing full messages with account numbers and identity details in plaintext observability tools.
    • Fix: redact PII before persistence and keep raw payload access tightly scoped to audited systems only.

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