Skip to content

A modern Next.js application leveraging MongoDB Atlas Vector Search and LangGraph AI agents for intelligent loan portfolio insights and risk analysis.

Notifications You must be signed in to change notification settings

coder-pikachu/loan-portfolio-insights

Repository files navigation

🏦 Loan Portfolio Insights with MongoDB Atlas

🚀 AI-Powered Loan Portfolio Analysis

A modern Next.js application leveraging MongoDB Atlas Vector Search and LangGraph AI agents for intelligent loan portfolio insights and risk analysis.

📋 Table of Contents


🏗️ Architecture Overview

This application combines the power of MongoDB Atlas with modern AI technologies to deliver intelligent loan portfolio analysis:

🔮 Technology Stack

Frontend     │ Next.js 15 + React 19 + TypeScript + Mantine UI
AI/ML        │ LangGraph + LangChain + OpenAI/Anthropic
Database     │ MongoDB Atlas + Vector Search
Visualization│ Recharts + Plotly.js
Styling      │ TailwindCSS

🎯 Key Features

  • 🤖 AI-Powered Analysis: LangGraph workflow engine with 7 domain-specific tools
  • 🔍 Hybrid Search: Vector similarity + metadata filtering
  • 📊 Interactive Dashboard: Real-time loan portfolio visualizations
  • ⚡ Vector Search: 1536-dimension embeddings with semantic search
  • 🛡️ Risk Assessment: Advanced ML-based risk scoring
  • 📈 Portfolio Analytics: Comprehensive performance metrics

🔧 Prerequisites

Before setting up the application, ensure you have:

  • Node.js 18.17+ and npm 8+
  • MongoDB Atlas account (free tier available)
  • OpenAI API key (for embeddings and chat)
  • Anthropic API key (for Claude models) [Optional]
  • Git for version control

🗄️ MongoDB Atlas Setup

Step 1: Create MongoDB Atlas Account

  1. Sign Up: Visit MongoDB Atlas and create a free account
  2. Verify Email: Check your email and verify your account

Step 2: Create a New Cluster

  1. Create Organization (if first time):

    • Click "Create Organization"
    • Name it (e.g., "Loan Portfolio Analytics")
    • Add members if needed
  2. Create Project:

    • Click "New Project"
    • Name: loan-portfolio-insights
    • Click "Create Project"
  3. Deploy Cluster:

    • Click "Create Deployment"
    • Choose M0 FREE tier
    • Cloud Provider: AWS (recommended)
    • Region: Choose closest to your location
    • Cluster Name: loan-portfolio-cluster
    • Click "Create Deployment"

Step 3: Configure Database Security

3.1 Create Database User

  1. Go to Database Access in left sidebar
  2. Click "Add New Database User"
  3. Authentication Method: Password
  4. Username: loan-admin
  5. Password: Generate secure password (save this!)
  6. Database User Privileges:
    • Select "Read and write to any database"
  7. Click "Add User"

3.2 Configure Network Access

  1. Go to Network Access in left sidebar
  2. Click "Add IP Address"
  3. For development:
    • Click "Allow Access from Anywhere" (0.0.0.0/0)
    • Description: "Development Access"
  4. For production:
    • Add your specific IP addresses
  5. Click "Confirm"

Step 4: Get Connection String

  1. Go to Database in left sidebar
  2. Click "Connect" on your cluster
  3. Choose "Connect your application"
  4. Driver: Node.js
  5. Version: 4.1 or later
  6. Copy Connection String:
    mongodb+srv://loan-admin:<password>@loan-portfolio-cluster.xxxxx.mongodb.net/?retryWrites=true&w=majority
    
  7. Replace <password> with your actual password

Step 5: Configure Vector Search Index

  1. Go to DatabaseSearchCreate Search Index
  2. Configuration Method: Visual Editor
  3. Database: loan_portfolio
  4. Collection: loan_applications_demo
  5. Index Name: vector_index
  6. Field Configuration:
    {
      "fields": [
        {
          "path": "embedding",
          "numDimensions": 1536,
          "similarity": "cosine",
          "type": "vector"
        }
      ]
    }
  7. Click "Create Search Index"

🔐 Environment Configuration

Step 1: Create Environment File

Create .env.local in your project root:

touch .env.local

Step 2: Configure Environment Variables

Add the following to .env.local:

# 🗄️ MongoDB Atlas Configuration
MONGODB_URI=mongodb+srv://loan-admin:<password>@loan-portfolio-cluster.xxxxx.mongodb.net/loan_portfolio?retryWrites=true&w=majority

# 🤖 AI Model API Keys
OPENAI_API_KEY=sk-your-openai-api-key-here
ANTHROPIC_API_KEY=sk-ant-your-anthropic-key-here

# 🛠️ Development Configuration
NODE_ENV=development
NEXT_PUBLIC_APP_ENV=development

# 📊 Analytics (Optional)
NEXT_PUBLIC_ANALYTICS_ID=your-analytics-id

Step 3: API Key Setup

3.1 OpenAI API Key

  1. Visit OpenAI Platform
  2. Sign in or create account
  3. Go to API Keys section
  4. Click "Create new secret key"
  5. Name: loan-portfolio-app
  6. Copy the key and add to .env.local

3.2 Anthropic API Key (Optional)

  1. Visit Anthropic Console
  2. Sign in or create account
  3. Go to API Keys
  4. Click "Create Key"
  5. Copy and add to .env.local

⚡ Quick Start

Step 1: Clone Repository

git clone <repository-url>
cd loan-portfolio-insights

Step 2: Install Dependencies

npm install

Step 3: Setup Environment

cp .env.example .env.local
# Edit .env.local with your MongoDB URI and API keys

Step 4: Initialize Database

# This will create sample loan data with embeddings
Run the seed-data.ts file from lib folder with customisations for same data and related embeddings.

Step 5: Start Development Server

npm run dev

🎉 Success! Open http://localhost:3000 to view the application.


🚀 Deployment

Production Build

# Build for production
npm run build

# Start production server
npm start

Environment Setup for Production

Update .env.local for production:

NODE_ENV=production
MONGODB_URI=your-production-mongodb-uri
# Add production API keys

Deployment Platforms

Vercel (Recommended)

  1. Push code to GitHub
  2. Connect repository to Vercel
  3. Add environment variables in Vercel dashboard
  4. Deploy automatically

Docker Deployment

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]

🛠️ Development

Project Structure

src/
├── app/
│   ├── components/          # React components
│   │   ├── LoanList.tsx    # Loan listings
│   │   ├── Dashboard.tsx   # Main dashboard
│   │   └── Charts/         # Visualization components
│   ├── lib/                # Business logic
│   │   ├── agent.ts        # LangGraph AI agent
│   │   ├── mongodb.ts      # Database connection
│   │   ├── types.ts        # TypeScript definitions
│   │   └── seed-data.ts    # Data generation
│   ├── api/                # API routes
│   │   ├── analyze/        # AI analysis endpoint
│   │   └── loans/          # Loan data endpoints
│   └── globals.css         # Global styles

Development Commands

# Development with hot reload
npm run dev

# Type checking
npm run type-check

# Linting
npm run lint

# Build production
npm run build

# Start production
npm start

Database Schema

The application uses a unified loan schema defined in src/app/lib/types.ts:

interface LoanApplication {
  _id: ObjectId;
  applicant_details: ApplicantDetails;
  loan_details: LoanDetails;
  risk_metrics: RiskMetrics;
  performance_data: PerformanceData;
  communication_logs: CommunicationLog[];
  embedding: number[]; // 1536-dimension vector
}

📊 Features

🤖 AI Agent Capabilities

  1. Portfolio Overview: Real-time metrics and KPIs
  2. Risk Analysis: Advanced risk scoring and assessment
  3. Applicant Search: Semantic search across loan applications
  4. Performance Tracking: Loan performance analytics
  5. Trend Analysis: Historical pattern recognition
  6. Compliance Monitoring: Regulatory compliance checks
  7. Predictive Analytics: ML-based forecasting

🔍 Search Capabilities

  • Semantic Search: Natural language queries
  • Hybrid Search: Vector + metadata filtering
  • Faceted Search: Multi-dimensional filtering
  • Real-time Results: Instant search responses

📈 Visualization Features

  • Interactive Dashboards: Real-time data visualization
  • Risk Heat Maps: Visual risk distribution
  • Performance Charts: Trend analysis charts
  • Portfolio Metrics: KPI dashboards

🔍 API Documentation

Analyze Endpoint

POST /api/analyze

Analyze loan portfolio using AI agent.

curl -X POST http://localhost:3000/api/analyze \
  -H "Content-Type: application/json" \
  -d '{"query": "Show me high-risk loans approved in the last month"}'

Response:

{
  "response": {
    "type": "analysis",
    "data": [...],
    "summary": "Found 15 high-risk loans approved recently..."
  }
}

Loans Endpoint

GET /api/loans

Retrieve loan applications.

curl http://localhost:3000/api/loans?limit=10&status=approved

🎯 Usage Examples

1. Risk Analysis Query

const response = await fetch('/api/analyze', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    query: "What are the top risk factors in our current portfolio?"
  })
});

2. Portfolio Performance

const analysis = await fetch('/api/analyze', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    query: "Show portfolio performance trends for the last 6 months"
  })
});

3. Applicant Search

const search = await fetch('/api/analyze', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    query: "Find software engineers with good credit history"
  })
});

🆘 Troubleshooting

Common Issues

MongoDB Connection Error

Error: Please add your MongoDB URI to .env.local

Solution:

  1. Verify .env.local exists
  2. Check MongoDB URI format
  3. Ensure IP address is whitelisted
  4. Verify database user credentials

API Key Issues

Error: OpenAI API key not found

Solution:

  1. Check .env.local for OPENAI_API_KEY
  2. Verify API key is valid
  3. Check API key permissions
  4. Restart development server

Vector Search Not Working

Solution:

  1. Verify Atlas Search index is created
  2. Check index configuration matches schema
  3. Ensure embeddings are generated
  4. Wait for index to be ready (can take a few minutes)

Performance Optimization

  • Connection Pooling: MongoDB connections are pooled automatically
  • Caching: Implement Redis caching for frequent queries
  • Indexing: Ensure proper database indexes
  • Batch Processing: Process large datasets in batches

🤝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

Development Guidelines

  • Follow TypeScript best practices
  • Write tests for new features
  • Update documentation
  • Follow MongoDB naming conventions
  • Use semantic commit messages

🌟 MongoDB Atlas Features Used

  • Document Model: Flexible schema for loan data
  • Vector Search: Semantic search capabilities
  • Aggregation Pipeline: Complex analytics queries
  • Atlas Search: Full-text search with faceting
  • Change Streams: Real-time data updates
  • Charts: Built-in data visualization

Built with ❤️ using MongoDB Atlas

MongoDB AtlasNext.jsLangChainMantine

About

A modern Next.js application leveraging MongoDB Atlas Vector Search and LangGraph AI agents for intelligent loan portfolio insights and risk analysis.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages