Semantic Kernel + Lekha: Parse Indian Financial Documents in .NET and TypeScript
Integrate Lekha with Microsoft Semantic Kernel to build financial document agents. Extract bank statements, ITR, and CAS using SK plugins and planners.
Microsoft's Semantic Kernel has become one of the most popular enterprise AI orchestration frameworks. Its plugin system, built-in planners, and first-class support for multi-step reasoning make it a natural fit for financial document workflows — where a single user request often spans extraction, validation, and decision-making across multiple documents.
This guide shows how to wire Lekha into a Semantic Kernel agent using the TypeScript SDK. By the end you will have a working SK plugin that can extract any Indian financial document and a planner-driven agent that uses it to answer complex financial questions.
Why Semantic Kernel for Financial Agents?
Semantic Kernel brings three things that raw LLM calls cannot:
Plugins expose Lekha's extraction capabilities as typed, discoverable functions the kernel can call automatically. No prompt engineering required to tell the model when to extract. Planners decompose a high-level goal ("assess this loan applicant's creditworthiness") into a sequence of plugin calls — fetch bank statement, fetch ITR, compare income, return verdict — without you hard-coding the flow. Memory and state let the kernel accumulate facts across a multi-turn conversation, so a follow-up question ("what were their average monthly inflows?") works without re-uploading the PDF.These features matter more as workflows grow. A simple one-off extraction doesn't need an orchestrator. But a due-diligence pipeline that touches five document types, reasons over discrepancies, and writes a structured report does.
Prerequisites
bun add @microsoft/semantic-kernel
or npm install @microsoft/semantic-kernel
You also need a Lekha API key from lekhadev.com and an OpenAI or Azure OpenAI key for the kernel's reasoning model.
Step 1: Create the Lekha Plugin
Semantic Kernel plugins are plain classes whose methods are decorated with @kernel_function (Python) or annotated with descriptions in TypeScript. The kernel uses these descriptions to decide when to call each function.
// src/plugins/lekha-plugin.ts
import {
KernelFunction,
KernelPlugin,
kernelFunction,
} from "@microsoft/semantic-kernel";
import FormData from "form-data";
import fs from "node:fs";
export class LekhaPlugin {
private readonly apiKey: string;
private readonly baseUrl = "https://api.lekhadev.com/v1";
constructor(apiKey: string) {
this.apiKey = apiKey;
}
@kernelFunction({
description:
"Extract structured data from an Indian bank statement PDF. Returns JSON with account info, transactions, and summary statistics.",
parameters: [
{
name: "filePath",
description: "Absolute path to the bank statement PDF",
type: "string",
isRequired: true,
},
],
})
async extractBankStatement({
filePath,
}: {
filePath: string;
}): Promise {
const form = new FormData();
form.append("file", fs.createReadStream(filePath));
form.append("document_type", "bank_statement");
const response = await fetch(${this.baseUrl}/extract, {
method: "POST",
headers: {
Authorization: Bearer ${this.apiKey},
...form.getHeaders(),
},
body: form as unknown as BodyInit,
});
const result = await response.json();
if (!result.success) throw new Error(result.error.message);
return JSON.stringify(result.data, null, 2);
}
@kernelFunction({
description:
"Extract structured data from an Indian Income Tax Return (ITR) PDF. Returns declared income, deductions, and tax paid.",
parameters: [
{
name: "filePath",
description: "Absolute path to the ITR PDF",
type: "string",
isRequired: true,
},
],
})
async extractITR({ filePath }: { filePath: string }): Promise {
const form = new FormData();
form.append("file", fs.createReadStream(filePath));
form.append("document_type", "itr");
const response = await fetch(${this.baseUrl}/extract, {
method: "POST",
headers: {
Authorization: Bearer ${this.apiKey},
...form.getHeaders(),
},
body: form as unknown as BodyInit,
});
const result = await response.json();
if (!result.success) throw new Error(result.error.message);
return JSON.stringify(result.data, null, 2);
}
@kernelFunction({
description:
"Extract portfolio holdings from a Consolidated Account Statement (CAS) PDF. Returns mutual fund holdings, NAV, and total portfolio value.",
parameters: [
{
name: "filePath",
description: "Absolute path to the CAS PDF",
type: "string",
isRequired: true,
},
],
})
async extractCAS({ filePath }: { filePath: string }): Promise {
const form = new FormData();
form.append("file", fs.createReadStream(filePath));
form.append("document_type", "cas");
const response = await fetch(${this.baseUrl}/extract, {
method: "POST",
headers: {
Authorization: Bearer ${this.apiKey},
...form.getHeaders(),
},
body: form as unknown as BodyInit,
});
const result = await response.json();
if (!result.success) throw new Error(result.error.message);
return JSON.stringify(result.data, null, 2);
}
}
Each method has a plain-English description — this is exactly what the SK planner reads to decide which function to invoke and when.
Step 2: Register the Plugin and Build the Kernel
// src/agent.ts
import {
Kernel,
OpenAIChatCompletion,
HandlebarsPlanner,
} from "@microsoft/semantic-kernel";
import { LekhaPlugin } from "./plugins/lekha-plugin.js";
const kernel = new Kernel();
// Add the LLM service
kernel.addService(
new OpenAIChatCompletion({
modelId: "gpt-4o",
apiKey: process.env.OPENAI_API_KEY!,
serviceId: "openai",
}),
);
// Register Lekha as a plugin
kernel.addPlugin(new LekhaPlugin(process.env.LEKHA_API_KEY!), "LekhaPlugin");
// Create a planner that can use the plugin
const planner = new HandlebarsPlanner();
export { kernel, planner };
Step 3: Run a Multi-Document Financial Assessment
With the kernel configured, you can ask a natural-language question that requires pulling data from multiple documents. The planner figures out the sequence of plugin calls automatically.
// src/assess.ts
import { kernel, planner } from "./agent.js";
async function assessApplicant(bankStatementPath: string, itrPath: string) {
const goal =
Assess the creditworthiness of this loan applicant.
Bank statement is at ${bankStatementPath}.
ITR is at ${itrPath}.
Calculate:
1. Average monthly net credit (last 6 months)
2. Declared annual income from ITR
3. Income stability ratio (bank vs ITR)
4. Existing EMI obligations
5. Final verdict: Approve / Review / Reject with reasoning
;
const plan = await planner.createPlan(goal, kernel);
console.log("Execution plan:", plan.toString());
const result = await plan.invokeAsync(kernel);
return result.getOutput();
}
// Usage
const verdict = await assessApplicant(
"/uploads/statement_jan_jun.pdf",
"/uploads/itr_fy2025.pdf",
);
console.log(verdict);
Example output:
Average monthly net credit: ₹87,420
Declared annual income (ITR FY2025): ₹10,80,000
Bank-declared income ratio: 0.97 (healthy, within 5% variance)
Existing EMI obligations: ₹24,500/month (28% FOIR)
Verdict: APPROVE — Income well-documented, FOIR within 40% limit, no adverse transaction patterns.
The planner called extractBankStatement and extractITR in sequence, then reasoned over both outputs to produce the verdict. You wrote no orchestration logic.
Step 4: Add Semantic Memory for Multi-Turn Conversations
One of SK's most useful features for financial workflows is persistent memory. Once a document has been extracted, the kernel can answer follow-up questions without re-processing it.
// src/memory-agent.ts
import {
Kernel,
OpenAIChatCompletion,
OpenAITextEmbedding,
SemanticTextMemory,
VolatileMemoryStore,
TextMemoryPlugin,
} from "@microsoft/semantic-kernel";
import { LekhaPlugin } from "./plugins/lekha-plugin.js";
const kernel = new Kernel();
kernel.addService(
new OpenAIChatCompletion({ modelId: "gpt-4o", apiKey: process.env.OPENAI_API_KEY! })
);
kernel.addService(
new OpenAITextEmbedding({ modelId: "text-embedding-3-small", apiKey: process.env.OPENAI_API_KEY! })
);
const memory = new SemanticTextMemory(
new VolatileMemoryStore(),
kernel.getService(OpenAITextEmbedding)
);
kernel.addPlugin(new TextMemoryPlugin(memory));
kernel.addPlugin(new LekhaPlugin(process.env.LEKHA_API_KEY!), "LekhaPlugin");
// Store extracted statement in memory
async function ingestDocument(filePath: string, applicantId: string) {
const plugin = kernel.getPlugin("LekhaPlugin");
const extracted = await plugin.extractBankStatement({ filePath });
await memory.saveInformationAsync(
"financial_docs",
extracted,
${applicantId}_bank_statement,
Bank statement for applicant ${applicantId}
);
}
// Answer questions using memory
async function askAboutApplicant(applicantId: string, question: string) {
const context = await memory.searchAsync(
"financial_docs",
question,
limit: 3,
minRelevanceScore: 0.7
);
const facts = context.map((r) => r.metadata.text).join("\n\n");
return kernel.invokePromptAsync(
Given these financial facts:\n${facts}\n\nAnswer: ${question},
new KernelArguments()
);
}
Connecting to Real Document Sources
Production financial agents rarely read from local disk. Documents arrive via upload APIs, S3 buckets, or the RBI Account Aggregator network. Lekha accepts buffers directly:
@kernelFunction({
description: "Extract bank statement from a URL (S3, GCS, or public HTTPS)",
parameters: [
{ name: "url", description: "Document URL", type: "string", isRequired: true },
],
})
async extractBankStatementFromUrl({ url }: { url: string }): Promise {
const response = await fetch(${this.baseUrl}/extract-url, {
method: "POST",
headers: {
Authorization: Bearer ${this.apiKey},
"Content-Type": "application/json",
},
body: JSON.stringify({ url, document_type: "bank_statement" }),
});
const result = await response.json();
if (!result.success) throw new Error(result.error.message);
return JSON.stringify(result.data, null, 2);
}
Try the URL extraction approach in Lekha's playground before wiring it into your SK pipeline.
Why This Beats a Monolithic LLM Prompt
The alternative to this architecture is uploading all PDFs directly to an LLM and asking it to reason over them. That approach has real limits:
| Factor | Monolithic LLM | SK + Lekha | | ------------------- | ------------------------------ | ------------------------------------- | | Context window | Exhausted fast with large PDFs | Lekha extracts only the data you need | | Structured output | Inconsistent | Typed JSON every time | | Auditability | Black box | Each plugin call is logged | | Cost | Full PDF tokens on every call | Extract once, query cheaply | | Indian bank support | Hallucination-prone | 50+ banks validated |
Lekha handles the extraction complexity — multi-column tables, regional language headers, non-standard date formats — so your SK agent can focus on reasoning.
What to Build Next
Once your SK + Lekha pipeline is running, the most common extensions are:
assessApplicant in Promise.all to process a batch concurrentlyLekhaPlugin.classify() before choosing which extraction function to useBrowse Lekha's documentation for the full list of supported document types and response schemas.
FAQ
Does Semantic Kernel's TypeScript SDK support all the same features as the Python SDK?The TypeScript SDK supports plugins, planners, and semantic memory, which are the three features used in this guide. Some advanced features like process framework and step-wise planners are still Python-only as of late 2026. For pure financial document workflows the TypeScript SDK is feature-complete.
Can I use Azure OpenAI instead of OpenAI with this setup?Yes. Replace OpenAIChatCompletion with AzureChatCompletion and pass your endpoint, apiKey, and deploymentName. The rest of the code is identical.
Lekha extracts all pages of a multi-page PDF in a single API call. The response includes a summary object with pre-aggregated metrics (total credits, total debits, average balance) across the full statement period, so your SK plugin can pass compact summaries to the planner instead of raw transaction arrays.
Lekha processes documents entirely within India-hosted infrastructure and returns only structured JSON — no raw document content leaves the extraction pipeline. See lekhadev.com/docs/compliance for the full data handling policy.
Ready to try it? Get your free API key at lekhadev.com and test your first extraction in the playground — no code required.