AI Prompts & Providers
Overview
LoanPilot features a polymorphic AI provider system designed to extract structured data from financial documents and generate comprehensive credit assessments. By abstracting the AI logic into a unified provider interface, the system can seamlessly switch between different LLM engines (such as Anthropic's Claude or OpenAI's GPT models) while maintaining consistent data outputs.
AI Provider Factory
The createAIProvider function is the primary entry point for interacting with the AI layer. It initializes the appropriate client based on the requested provider type.
import { createAIProvider } from '@/lib/ai/provider';
import type { AIProviderType } from '@/lib/ai/types';
// Initialize the default provider or a specific one
const provider = createAIProvider('anthropic' as AIProviderType);
console.log(`Using provider: ${provider.name}`);
Supported Provider Types
anthropic: Utilizes Claude models for high-context financial analysis.openai: Utilizes GPT models for structured data extraction.undefined: The system falls back to a default provider configured in environment variables.
Core Extraction Methods
Each provider instance implements a standard interface for processing loan-related documents.
Bank Statement Extraction
Extracts transaction history, balances, and identifies fraud flags from bank statements.
const result = await provider.extractBankStatement(base64File, mimeType);
Input:
base64File: The document encoded as a base64 string.mimeType: String (e.g.,application/pdf).
Key Analysis Metrics:
- Summary: Average balance, net income, total credits/debits.
- Enhanced Analysis: Fraud risk scores, inflow regularity, and repayment capacity (EMI detection).
- Transaction Quality: Customer concentration and cashflow volatility.
Financial Statement Extraction
Parses Balance Sheets, Profit & Loss (P&L) statements, and Income Tax Returns (ITR).
const result = await provider.extractFinancialStatement(
base64File,
'profit_loss', // 'balance_sheet' | 'profit_loss' | 'itr'
mimeType
);
Output Includes:
- Ratios: Asset turnover, DSCR (Debt Service Coverage Ratio), Current Ratio, ROE, etc.
- Statement Data: Automated mapping of line items to standard financial categories.
GST Returns Analysis
Extracts data from GST filings to verify business turnover and tax compliance.
Credit Memo Generation
The Credit Memo is a complex analysis generated by aggregating all available data points for a specific application. It uses a specialized prompt template to synthesize borrower information, bank analyses, and financial statements into a final recommendation.
Usage
The generateCreditMemo (internal implementation) requires a structured CreditMemoInput object:
const input: CreditMemoInput = {
application: { /* loan details */ },
borrower: { /* profile and verification status */ },
bank_analysis: { /* aggregated metrics from bank statements */ },
financial_analysis: [ /* array of P&L and Balance Sheet metrics */ ]
};
const result = await provider.generateCreditMemo(input);
Response Structure
All AI operations return a standardized result object to ensure type safety across the application:
| Property | Type | Description |
| :--- | :--- | :--- |
| success | boolean | Indicates if the extraction/analysis succeeded. |
| data | object | The structured JSON output (varies by method). |
| confidence | number | A score (0-1) representing the AI's certainty. |
| raw_response | object | The raw JSON response from the LLM for debugging/logging. |
| error | string | Error message if success is false. |
Configuration & Customization
The system manages prompts internally through specialized templates. While the internal templates are optimized for Indian financial documents (mentioning terms like "CIBIL", "GSTIN", and "Udyam"), the interface is designed to be extensible for other markets.
To ensure high-quality extraction, the system uses Function Calling (OpenAI) or Tool Use (Anthropic) to force the LLM to return valid JSON that matches the database schema. This minimizes parsing errors and ensures the raw_ai_response can be safely stored in Supabase.