Skip to content

SnowKingSandy/loanlinkai

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

LoanLinkAI - Agentic AI System for Personal Loan Processing

🎯 Overview

LoanLinkAI is a sophisticated agentic AI system that automates personal loan processing through a conversational interface. The system uses a Master Agent orchestrating multiple Worker Agents to guide users seamlessly through the loan application journeyβ€”from initial sales conversation to sanction letter generation.

Key Features

  • πŸ€– Master Agent with State Machine orchestration
  • πŸ’¬ Conversational AI using OpenAI GPT models
  • πŸ“„ Mock OCR for document processing
  • 🏦 Credit Assessment with mock credit bureau
  • πŸ“‹ PDF Sanction Letter generation using ReportLab
  • πŸ’Ύ In-Memory State Management for simplicity
  • 🎨 Professional UI with Tailwind CSS
  • ⚑ Real-time Status Tracking with live agent status panel

πŸ“Š Application Workflow

The system implements a finite state machine with the following states:

Sales β†’ Verification_Pending β†’ Underwriting β†’ Approved β†’ Completed

State Transitions:

  1. Sales: Initial conversation, capture loan requirements
  2. Verification_Pending: Wait for document upload and verification
  3. Underwriting: Fetch credit score, validate eligibility
  4. Approved: Present approval and offer sanction letter
  5. Completed: Transaction complete

πŸ—οΈ Architecture

Tech Stack

Backend:

  • Python 3.13
  • FastAPI (REST API)
  • Uvicorn (Server)
  • OpenAI API (GPT-3.5-turbo / GPT-4o)
  • ReportLab (PDF Generation)
  • Pydantic (Data validation)
  • Python-Multipart (File uploads)

Frontend:

  • React 18 (UI Framework)
  • Vite (Build tool)
  • Tailwind CSS (Styling)
  • Axios (HTTP Client)
  • Lucide React (Icons)

πŸ“ Project Structure

loanlinkai/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ __init__.py          # Package initializer
β”‚   β”‚   β”œβ”€β”€ main.py              # FastAPI application
β”‚   β”‚   β”œβ”€β”€ agents.py            # Master Agent logic
β”‚   β”‚   β”œβ”€β”€ models.py            # Pydantic models
β”‚   β”‚   └── utils.py             # Utility functions
β”‚   β”œβ”€β”€ static/                  # Generated PDFs folder
β”‚   β”œβ”€β”€ .env                     # Environment configuration
β”‚   β”œβ”€β”€ requirements.txt         # Python dependencies
β”‚   └── README.md                # Backend documentation
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”œβ”€β”€ ChatBox.jsx      # Chat interface
β”‚   β”‚   β”‚   └── StatusPanel.jsx  # Status sidebar
β”‚   β”‚   β”œβ”€β”€ assets/              # Static assets
β”‚   β”‚   β”œβ”€β”€ App.jsx              # Main layout
β”‚   β”‚   β”œβ”€β”€ App.css              # Component styles
β”‚   β”‚   β”œβ”€β”€ index.css            # Global styles
β”‚   β”‚   └── main.jsx             # React entry point
β”‚   β”œβ”€β”€ public/                  # Public static files
β”‚   β”œβ”€β”€ node_modules/            # Dependencies (npm)
β”‚   β”œβ”€β”€ eslint.config.js         # ESLint configuration
β”‚   β”œβ”€β”€ tailwind.config.js       # Tailwind configuration
β”‚   β”œβ”€β”€ vite.config.js           # Vite build configuration
β”‚   β”œβ”€β”€ package.json             # npm dependencies
β”‚   β”œβ”€β”€ package-lock.json        # npm lock file
β”‚   β”œβ”€β”€ index.html               # HTML entry point
β”‚   └── README.md                # Frontend documentation
β”œβ”€β”€ .git/                        # Git repository
β”œβ”€β”€ .gitignore                   # Git ignore file
β”œβ”€β”€ LICENSE                      # MIT License
└── README.md                    # Project documentation

β”œβ”€β”€ LICENSE └── README.md # This file


---

## πŸš€ Quick Start

### Prerequisites
- Python 3.13 or higher
- Node.js 18+ and npm
- OpenAI API key

### Backend Setup

1. **Navigate to backend directory:**
   ```bash
   cd backend
  1. Create virtual environment:

    python -m venv venv
    
    # Windows
    venv\Scripts\activate
    
    # macOS/Linux
    source venv/bin/activate
  2. Install dependencies:

    pip install -r requirements.txt
  3. Configure environment:

    # Edit .env and add your OpenAI API key
    OPENAI_API_KEY=sk-your-key-here
  4. Run server:

    python -m uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

    Backend will be available at: http://localhost:8000

Frontend Setup

  1. Navigate to frontend directory:

    cd frontend
  2. Install dependencies:

    npm install
  3. Create environment file:

    echo "VITE_API_URL=http://localhost:8000" > .env.local
  4. Run development server:

    npm run dev

    Frontend will be available at: http://localhost:5173

Access the Application

  • Open browser to http://localhost:5173
  • Start chatting with the AI assistant!

πŸ“‘ API Endpoints

Chat

  • POST /chat - Send message and get bot response
    {
      "message": "I need a personal loan",
      "user_id": "user123",
      "session_id": "optional_session_id"
    }

Document Upload

  • POST /upload - Upload and process documents
    • Accepts: PDF, JPG, PNG, DOC, DOCX
    • Performs mock OCR extraction
    • Updates user profile

State Management

  • GET /state - Get current session state
  • GET /session/{session_id} - Get session details
  • GET /sessions - List all active sessions (monitoring)

Sanction Letter

  • POST /sanction-letter - Generate PDF sanction letter
  • GET /static/{filename} - Download PDF

Health

  • GET /health - Server health check
  • GET / - API information

πŸ’‘ How It Works

Master Agent Flow

class MasterAgent:
    def process_message(user_message, session):
        current_state = session.state
        
        if state == SALES:
            # Extract loan amount, collect requirements
            # Transition to VERIFICATION_PENDING if amount mentioned
        
        elif state == VERIFICATION_PENDING:
            # Check if document uploaded
            # Run mock OCR if document present
            # Transition to UNDERWRITING
        
        elif state == UNDERWRITING:
            # Fetch mock credit score
            # Validate eligibility (score > 700)
            # Transition to APPROVED or COMPLETED
        
        elif state == APPROVED:
            # Offer sanction letter generation
            # Generate PDF if requested
            # Transition to COMPLETED
        
        return agent_response

Worker Agents (Mock Implementations)

  1. OCR Agent (mock_ocr_scan)

    • Extracts: Name, PAN, Email, Phone, Employment Type
    • Returns: Structured user data
  2. Credit Bureau Agent (fetch_mock_credit_score)

    • Returns: Random credit score (600-850)
    • In production: Call real credit bureau API
  3. PDF Generator Agent (generate_sanction_pdf)

    • Creates professional sanction letter PDF
    • Includes: Applicant details, loan terms, conditions
    • Saves to static/ folder

🎨 Frontend Components

ChatBox Component

  • Real-time message display
  • User/Bot message distinction
  • File upload capability
  • Auto-scroll to latest message
  • Loading states

StatusPanel Component

  • Application state visualization
  • Progress timeline
  • User profile information
  • Credit score display
  • Sanction letter download button
  • Live status updates

πŸ”’ Security Considerations

For Production:

  1. Implement proper authentication (JWT/OAuth)
  2. Use environment variables for sensitive data
  3. Add rate limiting to prevent abuse
  4. Implement input validation and sanitization
  5. Use HTTPS for all communications
  6. Secure CORS policy
  7. Add request logging and monitoring
  8. Implement data encryption
  9. Use persistent database instead of in-memory
  10. Add API key management

πŸ“ Example Usage

1. User Starts Conversation

User: "Hello, I'm interested in a personal loan"
Bot: "Welcome to LoanLinkAI! I'm your personal loan assistant. 
      What loan amount are you looking for?"

2. User Mentions Amount

User: "I need 5 lakhs"
Bot: "Great! Let's verify your details. 
      Please upload your identity proof (Aadhar/PAN) and recent salary slip."

3. User Uploads Document

  • Frontend sends file to /upload endpoint
  • OCR extracts information
  • User profile updated
  • Transition to Underwriting

4. Credit Check

Bot: "Your documents have been verified. 
      Credit score: 750. Processing your application..."

5. Approval

Bot: "Congratulations! Your loan application is approved.
      Would you like to generate your sanction letter?"

6. Sanction Letter

User: "Yes, please"
Bot: "Your sanction letter has been generated! 
      Download: /static/sanction_letter_xxx.pdf"

πŸ”§ Configuration

Environment Variables

Backend (.env):

OPENAI_API_KEY=sk-your-key-here
BACKEND_HOST=0.0.0.0
BACKEND_PORT=8000
DEBUG=True
FRONTEND_URL=http://localhost:5173
LOG_LEVEL=INFO

Frontend (.env.local):

VITE_API_URL=http://localhost:8000

πŸ“Š Mock Data

The system uses mock data for demonstration:

  • Credit Scores: Random 600-850
  • User Names: Predefined list of Indian names
  • PAN Format: ABCDE1234F pattern
  • Employment Types: Salaried, Self-Employed, Businessperson

πŸ§ͺ Testing

Manual Testing

  1. Start backend: python -m uvicorn app.main:app --reload
  2. Start frontend: npm run dev
  3. Open http://localhost:5173
  4. Test conversation flow
  5. Upload sample documents
  6. Verify state transitions

API Testing with cURL

# Send message
curl -X POST http://localhost:8000/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "I need a loan", "user_id": "test"}'

# Get state
curl http://localhost:8000/state?user_id=test

# Health check
curl http://localhost:8000/health

πŸ“± Browser Support

  • Chrome/Edge (Latest)
  • Firefox (Latest)
  • Safari (Latest)
  • Mobile browsers (Responsive design)

πŸ› Troubleshooting

Backend Issues

Port already in use:

# Change port in main.py or use
uvicorn app.main:app --port 8001

Import errors:

# Ensure virtual environment is activated
pip install -r requirements.txt

OpenAI API errors:

- Check API key in .env
- Verify internet connection
- Check OpenAI account status

Frontend Issues

Dependencies not installing:

rm -rf node_modules package-lock.json
npm install

Port 5173 in use:

npm run dev -- --port 5174

CORS errors:

- Ensure backend CORS is configured
- Check FRONTEND_URL in backend .env

πŸš€ Deployment

Backend (Docker)

FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY app app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

Frontend (Vercel/Netlify)

npm run build
# Upload dist/ folder

πŸ“ˆ Future Enhancements

  • Persistent database (PostgreSQL/MongoDB)
  • User authentication system
  • Multi-language support
  • Advanced NLP for better intent detection
  • Real credit bureau integration
  • Email/SMS notifications
  • Video integration for VideoBot
  • Dashboard for loan officers
  • Advanced analytics and reporting
  • Mobile app (React Native)

πŸ“„ License

This project is licensed under the MIT License - see LICENSE file for details.


🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch
  3. Commit your changes
  4. Push to the branch
  5. Create a Pull Request

πŸ“ž Support

For issues, questions, or suggestions:

  • Create an Issue on GitHub

πŸ‘¨β€πŸ’» Development Team

Built with ❀️ by the LoanLinkAI Team

Technologies: Python β€’ FastAPI β€’ React β€’ Tailwind β€’ OpenAI


About

An autonomous Agentic AI system for end-to-end personal loan sales. Features a Master Agent orchestrator, conversational sales interface, and real-time underwriting. Built for Techathon 6.0 (Tata Capital Challenge).

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors