Parse Indian Financial Docs with Google ADK and Lekha
Build AI agents that extract structured data from Indian bank statements, salary slips, and ITRs using Google ADK and Lekha. Full TypeScript walkthrough.
Google's Agent Development Kit (ADK) is an open-source framework for building, deploying, and orchestrating AI agents using Gemini models. Released in 2025, it has quickly become a first-class choice for teams building production agents on Google Cloud — offering built-in support for tools, multi-agent orchestration, session memory, and streaming.
If you are building financial AI agents on ADK and need to handle Indian documents — bank statements, salary slips, ITRs, CAS reports — integrating Lekha gives you structured JSON from any Indian financial PDF in one API call. No prompt engineering, no format-specific logic, no fragile regex.
This guide walks through building a loan eligibility agent on Google ADK that accepts a bank statement upload, extracts income and transaction data with Lekha, and returns a structured credit assessment.
Why Google ADK + Lekha?
ADK handles the agent layer: routing between tools, managing conversation state, calling Gemini, and running multi-step workflows. Lekha handles the document intelligence layer: turning any Indian financial PDF into clean, typed JSON.
The separation of concerns is clean:
| Layer | Handled by |
| ---------------------------------------------- | ---------------------------- |
| LLM reasoning & orchestration | Google ADK + Gemini |
| Document parsing (bank statements, ITRs, etc.) | Lekha API |
| Tool definitions & routing | ADK FunctionTool |
| Session memory | ADK InMemorySessionService |
This means you don't burn Gemini tokens trying to OCR a 40-page PDF. Lekha extracts the numbers; Gemini reasons about them.
Prerequisites
# Node.js 20+ required
npm install @google/adk axios form-data
You need:
Step 1: Define the Lekha Tool
In ADK, tools are plain async functions wrapped with FunctionTool. Define one for each document type you need to parse.
// tools/lekha.ts
import axios from "axios";
import FormData from "form-data";
const LEKHA_BASE = "https://api.lekhadev.com/v1";
interface LekhaOptions {
apiKey: string;
}
export async function extractBankStatement(
pdfBuffer: Buffer,
filename: string,
opts: LekhaOptions,
): Promise> {
const form = new FormData();
form.append("file", pdfBuffer, { filename, contentType: "application/pdf" });
const response = await axios.post(${LEKHA_BASE}/extract, form, {
headers: {
...form.getHeaders(),
Authorization: Bearer ${opts.apiKey},
},
});
if (!response.data.success) {
throw new Error(response.data.error?.message ?? "Lekha extraction failed");
}
return response.data.data;
}
export async function extractSalarySlip(
pdfBuffer: Buffer,
filename: string,
opts: LekhaOptions,
): Promise> {
const form = new FormData();
form.append("file", pdfBuffer, { filename, contentType: "application/pdf" });
const response = await axios.post(${LEKHA_BASE}/extract, form, {
headers: {
...form.getHeaders(),
Authorization: Bearer ${opts.apiKey},
},
});
if (!response.data.success) {
throw new Error(response.data.error?.message ?? "Lekha extraction failed");
}
return response.data.data;
}
Lekha auto-classifies the document — the same /extract endpoint handles bank statements, salary slips, ITRs, and 20+ other Indian financial document types. You don't need separate endpoints per document type.
Step 2: Wrap Tools for ADK
ADK's FunctionTool takes a function and a JSON Schema describing its parameters. Since Lekha handles binary files, the agent will work with base64-encoded content.
// agent/tools.ts
import { FunctionTool } from "@google/adk";
import { extractBankStatement, extractSalarySlip } from "../tools/lekha";
const LEKHA_API_KEY = process.env.LEKHA_API_KEY!;
export const parseBankStatementTool = new FunctionTool({
name: "parse_bank_statement",
description:
"Extract structured transaction data from an Indian bank statement PDF. Returns account holder name, account number, transactions, monthly inflows/outflows, and average balance.",
parameters: {
type: "object",
properties: {
file_base64: {
type: "string",
description: "Base64-encoded PDF content of the bank statement",
},
filename: {
type: "string",
description: "Original filename, e.g. hdfc_statement.pdf",
},
},
required: ["file_base64", "filename"],
},
handler: async ({
file_base64,
filename,
}: {
file_base64: string;
filename: string;
}) => {
const buffer = Buffer.from(file_base64, "base64");
const data = await extractBankStatement(buffer, filename, {
apiKey: LEKHA_API_KEY,
});
return JSON.stringify(data, null, 2);
},
});
export const parseSalarySlipTool = new FunctionTool({
name: "parse_salary_slip",
description:
"Extract structured data from an Indian salary slip PDF. Returns employer, employee name, gross salary, deductions (PF, TDS, PT), and net take-home.",
parameters: {
type: "object",
properties: {
file_base64: {
type: "string",
description: "Base64-encoded PDF content of the salary slip",
},
filename: {
type: "string",
description: "Original filename, e.g. salary_jan_2026.pdf",
},
},
required: ["file_base64", "filename"],
},
handler: async ({
file_base64,
filename,
}: {
file_base64: string;
filename: string;
}) => {
const buffer = Buffer.from(file_base64, "base64");
const data = await extractSalarySlip(buffer, filename, {
apiKey: LEKHA_API_KEY,
});
return JSON.stringify(data, null, 2);
},
});
Step 3: Create the Loan Eligibility Agent
Now assemble the ADK agent. The system prompt instructs Gemini on what to do with the extracted data.
// agent/loan-agent.ts import { Agent, InMemorySessionService, Runner } from "@google/adk"; import { parseBankStatementTool, parseSalarySlipTool } from "./tools";, tools: [parseBankStatementTool, parseSalarySlipTool], });const loanEligibilityAgent = new Agent({ name: "loan_eligibility_agent", model: "gemini-2.0-flash", description: "Analyzes Indian financial documents to assess personal loan eligibility.", instruction:
You are a loan eligibility analyst for an Indian NBFC. When a user provides bank statement or salary slip documents:- Call the appropriate parse tool to extract structured financial data.
- Analyze: average monthly inflow, salary stability, EMI obligations (recurring debits), and credit score signals.
- Compute a debt-to-income ratio if both salary and EMIs are available.
- Return a JSON assessment with: { eligible: boolean, max_loan_amount: number, recommended_tenure_months: number, reasons: string[] }.
Always use ISO 8601 dates. Never return amounts as strings — use numbers only.
const sessionService = new InMemorySessionService();
export const runner = new Runner({ agent: loanEligibilityAgent, appName: "loan_eligibility_app", sessionService, });
Step 4: Run the Agent
Wire the runner into your API route or CLI:
// main.ts
import { runner } from "./agent/loan-agent";
import { Content } from "@google/adk";
import * as fs from "fs";
async function assessLoanEligibility(statementPath: string) {
const pdfBuffer = fs.readFileSync(statementPath);
const base64 = pdfBuffer.toString("base64");
const filename = statementPath.split("/").pop()!;
const sessionId = session_${Date.now()};
await runner.sessionService.createSession({
appName: "loan_eligibility_app",
userId: "user_001",
sessionId,
});
const userMessage: Content = {
role: "user",
parts: [
{
text: Please assess loan eligibility for this applicant. Here is their bank statement in base64:
file_base64: ${base64}
filename: ${filename},
},
],
};
let finalResponse = "";
for await (const event of runner.runAsync({
userId: "user_001",
sessionId,
newMessage: userMessage,
})) {
if (event.isFinalResponse() && event.content?.parts?.[0]?.text) {
finalResponse = event.content.parts[0].text;
}
}
return finalResponse;
}
// Run
assessLoanEligibility("./fixtures/applicant_statement.pdf")
.then(console.log)
.catch(console.error);
The agent calls parse_bank_statement, receives Lekha's structured JSON (account holder, transactions, monthly summaries), reasons over it with Gemini, and returns a structured eligibility decision.
Step 5: Multi-Document Assessment
For more thorough credit assessments, combine bank statement and salary slip in a single agent run. ADK's multi-turn session keeps context across tool calls automatically.
const userMessage: Content = {
role: "user",
parts: [
{
text: Assess loan eligibility using both documents.
Bank statement base64: ${bankBase64} (filename: bank_statement.pdf)
Salary slip base64: ${salaryBase64} (filename: salary_slip.pdf)
Provide a full DTI analysis.,
},
],
};
The agent will call both tools, cross-reference the net salary from the salary slip against inflows in the bank statement (a signal for income verification), and factor in recurring EMI debits before returning its assessment.
Handling Lekha's Response Structure
Lekha returns a consistently typed JSON for each document type. For bank statements:
{
"document_type": "bank_statement",
"bank_name": "HDFC Bank",
"account_holder": "Priya Sharma",
"account_number": "XXXX1234",
"period": { "from": "2026-04-01", "to": "2026-09-30" },
"summary": {
"opening_balance": 42500,
"closing_balance": 68200,
"total_credits": 385000,
"total_debits": 359300,
"average_monthly_balance": 55400
},
"transactions": [
{
"date": "2026-04-03",
"description": "SALARY CREDIT",
"amount": 85000,
"type": "credit",
"balance": 127500
}
// ...
]
}
Amounts are always numbers, dates are always ISO 8601 — no post-processing needed. Explore all response schemas at lekhadev.com/docs.
You can try parsing a sample document live at lekhadev.com/playground before writing any code.
Production Tips
Rate limiting: Lekha's free tier processes 100 documents/month. For production volumes, upgrade to a paid plan — API keys are provisioned instantly at lekhadev.com. Timeout handling: Large multi-page statements can take 8–12 seconds. Set ADK tool timeouts accordingly and implement retry logic with exponential backoff. Caching: If the same PDF is submitted multiple times (e.g. a re-assessment), cache Lekha's response by a hash of the file content. This avoids redundant API calls and speeds up the agent loop significantly. Vertex AI deployment: To deploy your ADK agent on Google Cloud, replaceInMemorySessionService with VertexAiSessionService and set GOOGLE_CLOUD_PROJECT. The Lekha integration requires no changes — it's just an external HTTP call your agent makes.
FAQ
What Indian document types does Lekha support? Lekha extracts structured data from bank statements (40+ Indian banks), salary slips, ITRs (AY 2020-21 onwards), Form 16, CAS reports, CIBIL credit reports, GST invoices, and balance sheets. The classifier auto-detects the document type, so you don't need separate endpoints. Does Lekha store uploaded documents? No. Lekha processes documents in memory and never persists them to disk. This is by design for DPDP Act compliance. Documents are discarded immediately after extraction. Can I use Google ADK with Vertex AI instead of AI Studio? Yes. Set yourGOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION environment variables and use VertexAI as the backend. The Lekha tool definitions and handler code are identical — only the ADK runner configuration changes.
What if the document is password-protected?
Lekha can handle password-protected PDFs. Pass the password as an optional password field in the FormData. Many Indian bank statements (SBI, HDFC) use the customer's date of birth as the PDF password.
Get Started
The full code for this integration is under 100 lines. You can have a working loan eligibility agent running against real Indian bank statements in under 30 minutes.
If you are building a fintech agent on Google ADK — loan origination, expense tracking, tax prep, or portfolio analysis — Lekha handles the hardest part: reliably turning messy Indian PDFs into structured data your agent can reason over.