How to Build a transaction monitoring Agent Using LlamaIndex in TypeScript for investment banking
A transaction monitoring agent watches payment, trade, and account activity for patterns that could indicate fraud, market abuse, sanctions exposure, or AML risk. In investment banking, that matters because the cost of missing a suspicious pattern is not just financial loss — it is regulatory action, audit findings, and broken controls.
Architecture
- •
Transaction ingestion layer
- •Pulls events from Kafka, S3, a database replica, or a streaming bus.
- •Normalizes fields like
counterparty,jurisdiction,amount,currency,timestamp, anddesk.
- •
Risk rules and enrichment layer
- •Adds KYC data, sanctions lists, client risk ratings, and historical behavior.
- •Flags deterministic issues before the LLM sees anything.
- •
LlamaIndex retrieval layer
- •Uses
VectorStoreIndexto retrieve policy snippets, escalation playbooks, typologies, and prior case notes. - •Keeps the agent grounded in internal controls instead of guessing.
- •Uses
- •
Agent reasoning layer
- •Uses a
ReActAgentor tool-enabled workflow to classify alerts and draft analyst notes. - •Produces structured outputs for downstream case management.
- •Uses a
- •
Audit and evidence store
- •Persists input payloads, retrieved context, prompts, tool calls, and final decisions.
- •Required for model governance and regulator review.
- •
Case management integration
- •Sends suspicious cases to Actimize, FircoSoft-style workflows, ServiceNow, or an internal queue.
- •Supports human review and override.
Implementation
1. Install the packages and define your data model
Use the TypeScript LlamaIndex package and keep your transaction schema explicit. In banking systems, schema drift is how controls break.
npm install llamaindex zod
import { z } from "zod";
export const TransactionSchema = z.object({
transactionId: z.string(),
accountId: z.string(),
counterparty: z.string(),
amount: z.number(),
currency: z.string(),
jurisdiction: z.string(),
desk: z.string(),
timestamp: z.string(),
});
export type Transaction = z.infer<typeof TransactionSchema>;
2. Build a policy knowledge base with VectorStoreIndex
Load internal monitoring policies, typologies, and escalation rules into a retrieval index. This is what keeps the agent aligned with bank-specific controls.
import {
Document,
Settings,
VectorStoreIndex,
} from "llamaindex";
async function buildPolicyIndex() {
const docs = [
new Document({
text: "Escalate transactions over USD 1m involving high-risk jurisdictions unless pre-cleared by compliance.",
metadata: { source: "AML_POLICY_001", version: "v3" },
}),
new Document({
text: "Watch for rapid in-and-out movement across multiple counterparties within a short time window.",
metadata: { source: "TM_TYPLOGY_014", version: "v2" },
}),
new Document({
text: "All alerts must include rationale, evidence references, and analyst decision for audit purposes.",
metadata: { source: "CASE_PLAYBOOK_002", version: "v5" },
}),
];
return await VectorStoreIndex.fromDocuments(docs);
}
3. Create tools for deterministic checks and retrieval
Do not let the model decide basic compliance logic. Put thresholds and enrichment checks in tools, then let LlamaIndex reason over them.
import {
FunctionTool,
ReActAgent,
} from "llamaindex";
function buildTools(policyIndex: VectorStoreIndex) {
const retrievePolicyTool = FunctionTool.from(
async ({ query }: { query: string }) => {
const retriever = policyIndex.asRetriever();
const nodes = await retriever.retrieve(query);
return nodes.map((n) => ({
text: n.node.getContent(),
score: n.score,
metadata: n.node.metadata,
}));
},
{
name: "retrieve_policy",
description: "Retrieve internal monitoring policies and typologies relevant to a transaction.",
}
);
const thresholdCheckTool = FunctionTool.from(
async ({ amount }: { amount: number }) => {
return {
exceedsHighValueThreshold: amount >= 1000000,
thresholdCurrencyAgnostic: true,
};
},
{
name: "threshold_check",
description: "Apply hard-coded high-value transaction thresholds.",
}
);
return [retrievePolicyTool, thresholdCheckTool];
}
4. Run the agent and force structured alert output
The agent should return a clear decision that can be stored in a case system. Keep the prompt narrow and make it explainable.
import { OpenAI } from "@llamaindex/openai";
async function main() {
Settings.llm = new OpenAI({ model: "gpt-4o-mini" });
const policyIndex = await buildPolicyIndex();
const tools = buildTools(policyIndex);
const agent = new ReActAgent({
tools,
llm: Settings.llm,
systemPrompt:
"You are a transaction monitoring analyst for an investment bank. Use only provided tools and retrieved policy context. Return JSON with fields decision, riskLevel, rationale, evidenceRefs.",
});
const tx = TransactionSchema.parse({
transactionId: "TXN-9001",
accountId: "ACC-4421",
counterparty: "Ocean Gate Trading Ltd",
amount: 2500000,
currency: "USD",
jurisdiction: "AE",
desk: "Prime Brokerage",
timestamp: new Date().toISOString(),
});
const response = await agent.chat(`
Assess this transaction:
${JSON.stringify(tx)}
Use threshold_check on amount ${tx.amount}.
Use retrieve_policy for high-value cross-border transaction monitoring.
`);
console.log(response.message.content);
}
main().catch(console.error);
Production Considerations
- •
Keep data residency tight
- •Store prompts, embeddings, and case data in-region if your bank has jurisdictional constraints.
- •Do not send raw PII or full trade details to external services unless legal approved it.
- •
Persist an audit trail
- •Log the original transaction payload, tool outputs, retrieved document IDs, final response, model version, and timestamp.
- •Regulators care about reproducibility more than clever reasoning.
- •
Add guardrails before the model
- •Sanitize free-text fields from counterparties and payment narratives.
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