A comprehensive, AI-powered loan origination system built with LangChain and LangGraph that automates the entire loan application lifecycle from initial application to final decision.
- Complete Loan Application Management - Handle all loan types (personal, auto, home, business, student)
- AI-Powered Document Processing - Automated document verification and data extraction using LangChain
- Intelligent Workflow Orchestration - Complex decision workflows using LangGraph
- Real-time Credit Assessment - Integration with credit bureaus and risk modeling
- Automated Decision Engine - AI-driven approval/rejection with human review capabilities
- Comprehensive Audit Trail - Complete tracking of all application changes and decisions
- Document Analysis - OCR and intelligent document parsing
- Income Verification - Cross-reference income across multiple document sources
- Risk Assessment - Multi-factor risk evaluation using machine learning
- Decision Explanations - AI-generated explanations for loan decisions
- Fraud Detection - Automated detection of inconsistencies and red flags
- RESTful API - Complete FastAPI-based REST API
- Database Persistence - PostgreSQL with SQLAlchemy ORM
- Async Processing - Background workflow processing
- File Upload Management - Secure document storage and retrieval
- Health Monitoring - Comprehensive health checks and metrics
- Production Ready - Docker support, logging, error handling
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Frontend UI ββββββ FastAPI ββββββ LangGraph β
β (External) β β REST API β β Workflows β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β β
β β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β PostgreSQL ββββββ SQLAlchemy β β LangChain β
β Database β β ORM β β Chains β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β β
β β
βββββββββββββββββββ βββββββββββββββββββ
β File Storage β β External APIs β
β (Local/S3) β β (Credit/OCR) β
βββββββββββββββββββ βββββββββββββββββββ
- Python 3.13+
- PostgreSQL 12+
- OpenAI API Key (for AI features)
- Git
-
Clone the repository
git clone <repository-url> cd losa
-
Set up Python environment
# Using uv (recommended) uv venv source .venv/bin/activate # On Windows: .venv\Scripts\activate uv sync # Or using pip python -m venv .venv source .venv/bin/activate pip install -e .
-
Set up database
# Install PostgreSQL and create database createdb losa createuser losa_user -
Configure environment
cp .env.example .env # Edit .env with your configuration -
Initialize database
# Run database migrations alembic upgrade head -
Start the application
python -m losa.main # Or using uvicorn directly uvicorn losa.main:app --host 0.0.0.0 --port 8000 --reload -
Access the API
- API Documentation: http://localhost:8000/docs
- Health Check: http://localhost:8000/health
- API Base URL: http://localhost:8000/api/v1
Key configuration options in .env:
# Database
DB_HOST=localhost
DB_NAME=losa
DB_USER=losa_user
DB_PASSWORD=your_password
# OpenAI API
OPENAI_API_KEY=your_openai_api_key
OPENAI_MODEL=gpt-4
# Application
HOST=0.0.0.0
PORT=8000
DEBUG=falseSee .env.example for complete configuration options.
# Create new loan application
POST /api/v1/loans/
Content-Type: application/json
{
"personal_info": {
"first_name": "John",
"last_name": "Doe",
"email": "[email protected]",
"phone": "5551234567",
"ssn": "123-45-6789",
"date_of_birth": "1990-01-01T00:00:00Z",
"marital_status": "single",
"dependents": 0,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip_code": "12345"
}
},
"employment_info": {
"status": "employed",
"employer_name": "Tech Corp",
"job_title": "Software Engineer",
"annual_income": 80000,
"monthly_income": 6666.67
},
"financial_info": {
"monthly_rent_mortgage": 1500,
"monthly_debt_payments": 300,
"savings_balance": 10000,
"checking_balance": 5000
},
"loan_details": {
"loan_type": "personal",
"requested_amount": 25000,
"requested_term_months": 60,
"purpose": "Debt consolidation"
}
}# Get loan application
GET /api/v1/loans/{application_id}
# Update loan application
PUT /api/v1/loans/{application_id}
# Submit for processing
POST /api/v1/loans/{application_id}/submit
# Upload document
POST /api/v1/loans/{application_id}/documents
Content-Type: multipart/form-data
# Get applications by status
GET /api/v1/loans/status/under_review?limit=50&offset=0The system automatically processes applications through these stages:
- Validation - Check completeness and basic requirements
- Document Verification - AI-powered document analysis
- Credit Check - Credit bureau integration
- Risk Assessment - Multi-factor risk evaluation
- Decision Making - Automated approval/rejection
- Human Review - Manual review when needed
The loan origination workflow is implemented using LangGraph:
# Workflow nodes
validate_application β verify_documents β credit_check β risk_assessment β make_decision
β
human_review (conditional)Specialized chains handle specific AI tasks:
- DocumentAnalysisChain - Analyze uploaded documents
- IncomeVerificationChain - Verify income across sources
- CreditAnalysisChain - Comprehensive credit assessment
- LoanExplanationChain - Generate decision explanations
from losa.workflows.loan_workflow import process_loan_application
from losa.models.loan import LoanApplication
# Process application through complete workflow
processed_app = await process_loan_application(application)
# Check results
if processed_app.decision:
print(f"Decision: {processed_app.decision.decision}")
print(f"Approved Amount: ${processed_app.decision.approved_amount}")
print(f"Interest Rate: {processed_app.decision.interest_rate}%")- loan_applications - Main application data
- documents - Uploaded document metadata
- credit_scores - Credit bureau results
- risk_assessments - Risk evaluation results
- audit_logs - Complete audit trail
- underwriters - Human review assignments
loan_applications (1) -----> (many) documents
loan_applications (1) -----> (many) credit_scores
loan_applications (1) -----> (many) risk_assessments
loan_applications (1) -----> (many) audit_logsRun the test suite:
# Run all tests
pytest
# Run with coverage
pytest --cov=losa --cov-report=html
# Run specific test file
pytest tests/test_loan_service.py
# Run with verbose output
pytest -v- Unit Tests - Service and model testing
- Integration Tests - API endpoint testing
- Workflow Tests - LangGraph workflow testing
- Chain Tests - LangChain chain testing
# Build Docker image
docker build -t losa:latest .
# Run with docker-compose
docker-compose up -d- Set
DEBUG=falsein production - Use proper SSL certificates
- Configure rate limiting
- Set up monitoring and logging
- Use managed PostgreSQL service
- Configure backup strategies
GET /health # Comprehensive health check
GET /ready # Readiness probe
GET /live # Liveness probe
GET /metrics # Basic metricsStructured logging with configurable levels:
# Log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL
LOG_LEVEL=INFO
LOG_FILE=losa.log
STRUCTURED_LOGGING=true- SSN and sensitive data encryption at rest
- Secure file upload validation
- SQL injection prevention via ORM
- Input validation and sanitization
- CORS configuration
- Rate limiting
- Request/response logging
- Error handling without data leaks
- Configurable data retention policies
- Complete audit trail
- GDPR/CCPA compliance features
- PCI DSS considerations
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for new functionality
- Ensure all tests pass (
pytest) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Follow PEP 8 style guidelines
- Add type hints to all functions
- Write comprehensive docstrings
- Include tests for new features
- Update documentation as needed
This project is licensed under the MIT License - see the LICENSE file for details.
- API Documentation: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- Check existing GitHub issues
- Create a new issue for bugs or feature requests
- Review the troubleshooting guide below
Database Connection Failed
# Check PostgreSQL is running
pg_ctl status
# Verify connection settings in .env
DB_HOST=localhost
DB_PORT=5432OpenAI API Errors
# Verify API key is set
echo $OPENAI_API_KEY
# Check API quota and billingFile Upload Issues
# Check upload directory permissions
mkdir -p uploads
chmod 755 uploads- Advanced ML risk scoring models
- Integration with additional credit bureaus
- Mobile API optimizations
- Advanced fraud detection
- Alternative data sources integration
- Blockchain document verification
- Real-time decision streaming
- Advanced analytics dashboard
- Multi-tenant architecture
- Regulatory compliance automation
- AI-powered loan pricing
- Global market expansion features
- Application creation: ~100ms
- Document analysis: ~2-5s
- Complete workflow: ~10-30s
- API response time: <200ms (95th percentile)
- Supports 1000+ concurrent applications
- Horizontal scaling via load balancer
- Database read replicas supported
- Background job processing
Built with β€οΈ using LangChain and LangGraph
For more information, visit our documentation or reach out to the development team.