How to Build a underwriting Agent Using LlamaIndex in TypeScript for payments
A underwriting agent for payments decides whether a merchant, transaction flow, or payout request should be approved, reviewed, or blocked based on policy, risk signals, and internal controls. It matters because payment teams need fast decisions without losing auditability, compliance coverage, or control over fraud and chargeback exposure.
Architecture
- •
Policy ingestion layer
- •Loads underwriting rules from PDFs, markdown, internal docs, and change logs.
- •Keeps the agent grounded in current policy instead of model memory.
- •
Retriever
- •Pulls the most relevant policy chunks for a given merchant or transaction case.
- •Uses LlamaIndex
VectorStoreIndexplus a retriever built from embedded documents.
- •
Decision engine
- •Converts retrieved policy into a structured underwriting decision.
- •Returns
approve,review, ordeclinewith reasons and evidence.
- •
Risk context adapter
- •Injects payment-specific data like MCC, geography, chargeback rate, refund rate, KYC status, velocity metrics, and processor history.
- •Keeps the agent from making decisions on policy text alone.
- •
Audit logger
- •Stores prompts, retrieved sources, final decisions, and timestamps.
- •Required for compliance review and dispute handling.
- •
Guardrail layer
- •Blocks unsupported actions and prevents the model from inventing policy.
- •Enforces “cite source or escalate” behavior.
Implementation
1) Install dependencies and load underwriting policy documents
Use LlamaIndex’s TypeScript package with an embedding model and a simple document loader. In production you’ll usually swap the file loader for S3, SharePoint, or a document management system.
npm install llamaindex dotenv
import "dotenv/config";
import {
Document,
VectorStoreIndex,
Settings,
OpenAIEmbedding,
} from "llamaindex";
import fs from "node:fs/promises";
import path from "node:path";
Settings.embedModel = new OpenAIEmbedding({
apiKey: process.env.OPENAI_API_KEY!,
});
async function loadPolicyDocs(dir: string): Promise<Document[]> {
const files = await fs.readdir(dir);
const docs: Document[] = [];
for (const file of files) {
if (!file.endsWith(".md") && !file.endsWith(".txt")) continue;
const fullPath = path.join(dir, file);
const text = await fs.readFile(fullPath, "utf8");
docs.push(
new Document({
text,
metadata: {
source: file,
domain: "payments-underwriting",
},
})
);
}
return docs;
}
2) Build the index and retriever
The agent should not answer from raw memory. Build a vector index over your policy corpus so every decision is grounded in current underwriting rules.
async function buildIndex() {
const docs = await loadPolicyDocs("./policy");
const index = await VectorStoreIndex.fromDocuments(docs);
const retriever = index.asRetriever(4);
return { index, retriever };
}
3) Create a structured underwriting decision workflow
For payments you want deterministic output. The pattern below uses retrieval plus an LLM prompt that forces a strict decision format with evidence references.
import {
OpenAI,
} from "llamaindex";
type UnderwritingInput = {
merchantId: string;
mcc: string;
country: string;
monthlyVolumeUsd: number;
chargebackRate: number;
refundRate: number;
};
type UnderwritingDecision = {
decision: "approve" | "review" | "decline";
reasons: string[];
};
const llm = new OpenAI({
apiKey: process.env.OPENAI_API_KEY!,
});
async function underwriteMerchant(input: UnderwritingInput) {
const { retriever } = await buildIndex();
const query = `
Underwrite this payment merchant:
Merchant ID: ${input.merchantId}
MCC: ${input.mcc}
Country: ${input.country}
Monthly volume USD: ${input.monthlyVolumeUsd}
Chargeback rate: ${input.chargebackRate}
Refund rate: ${input.refundRate}
Return only an underwriting decision based on policy.
`;
const nodes = await retriever.retrieve({ query });
})
---
## Keep learning
- [The complete AI Agents Roadmap](/blog/ai-agents-roadmap-2026) — my full 8-step breakdown
- [Free: The AI Agent Starter Kit](/starter-kit) — PDF checklist + starter code
- [Work with me](/contact) — I build AI for banks and insurance companies
*By Cyprian Aarons, AI Consultant at [Topiax](https://topiax.xyz).*
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