Skip to content

Loan Scoring Workflow Feature

Overview

A new interactive, multi-step loan scoring workflow has been added to the AI Agent. This workflow guides staff through a complete loan evaluation process by collecting customer information, selecting a loan product, entering the requested amount, and calculating the loan score.

Workflow Steps

Step 1: Search Customer

  • Purpose: Verify the customer exists and is not blacklisted
  • Input: customer_id (optional)
  • Validation:
  • Customer must exist in the system
  • Customer must not be blacklisted
  • Customer profile name is displayed for confirmation
  • Output: Customer found confirmation with next steps
  • Example: "I want to do a loan scoring for customer 123"

Step 2: Select Product

  • Purpose: Choose a loan product for the evaluation
  • Input:
  • customer_id (from previous step)
  • product_id (new)
  • Product Details Retrieved:
  • Product name and code
  • Interest rate
  • Min/max loan amounts
  • Tenure in days
  • Output: Product details confirmation and next steps
  • Example: "Now select product 5 for them"

Step 3: Enter Amount

  • Purpose: Specify the requested loan amount
  • Input:
  • customer_id (from previous step)
  • product_id (from previous step)
  • loan_amount (new)
  • Validation:
  • Amount must be between product minimum and maximum
  • Amount is converted to Decimal for precise calculations
  • Output: Amount confirmation and ready to calculate
  • Example: "The customer wants to borrow 50000"

Step 4: Calculate Score

  • Purpose: Run the loan scoring algorithm
  • Input:
  • customer_id (from previous step)
  • product_id (from previous step)
  • loan_amount (from previous step)
  • Processing:
  • Calls LoanScoringService.calculate_internal_score()
  • Calculates credit score based on:
    • Repayment history
    • Exposure/existing debt
    • Income stability
    • Behavioral patterns
  • Retrieves risk level classification
  • Generates lending recommendation
  • Output:
  • Final loan score (0-1000 range)
  • Risk level (LOW, MEDIUM, HIGH, etc.)
  • Lending recommendation (APPROVED, REVIEW, REJECT)
  • Score breakdown and creation timestamp
  • Example: "Score: 750, Risk Level: LOW. Recommendation: APPROVED"

Tool Definition

{
  "type": "function",
  "function": {
    "name": "start_loan_scoring_workflow",
    "description": "Start an interactive loan scoring workflow...",
    "parameters": {
      "type": "object",
      "properties": {
        "customer_id": {
          "type": "integer",
          "description": "Optional customer/borrower identity id"
        },
        "step": {
          "type": "string",
          "enum": ["search_customer", "select_product", "enter_amount", "calculate_score"],
          "description": "Current step in the workflow"
        },
        "product_id": {
          "type": "integer",
          "description": "Loan product ID (required for later steps)"
        },
        "loan_amount": {
          "type": "number",
          "description": "Requested loan amount in currency"
        }
      },
      "required": ["step"]
    }
  }
}

Usage Examples

Example 1: Step-by-Step Workflow

User: "I want to do a loan scoring for customer 123"
Agent: Searches customer and confirms identity
User: "Use product 5"
Agent: Shows product details and asks for amount
User: "They want 50000"
Agent: Validates amount and prepares for calculation
User: "Calculate the score"
Agent: Returns score of 750 with LOW risk and APPROVED recommendation

Example 2: All-in-One Request

User: "Start a loan scoring process for customer 789 with product 5 and amount 50000"
Agent: May guide through steps or execute complete workflow
Result: Returns final score and recommendation

Example 3: With Error Handling

User: "Check loan scoring for customer 999"
Agent: "Customer with ID 999 not found"
User: "Try customer 123"
Agent: Proceeds with valid customer

Response Format

Each step returns a structured JSON response:

Success Response (Step 1)

{
  "step": "search_customer",
  "success": true,
  "customer_id": 123,
  "customer_name": "John Doe",
  "message": "Customer found: John Doe. Now select a loan product.",
  "next_step": "select_product",
  "prompt": "Which loan product would they like?"
}

Success Response (Step 4 - Final)

{
  "step": "calculate_score",
  "success": true,
  "customer_id": 123,
  "customer_name": "John Doe",
  "product": "Personal Loan",
  "loan_amount": 50000,
  "score_result": {
    "score": 750,
    "risk_level": "LOW",
    "recommendation": "APPROVED",
    "breakdown": {
      "created_on": "2026-02-02T10:30:00",
      "risk_level": "LOW"
    }
  },
  "message": "Loan scoring completed. Score: 750, Risk Level: LOW. Recommendation: APPROVED.",
  "workflow_complete": true
}

Error Response

{
  "step": "search_customer",
  "error": "Customer with ID 999 not found",
  "prompt": "Enter a valid customer ID"
}

Integration with AI Agent

The workflow is fully integrated into the conversational AI:

  1. Natural Language Trigger: User can say things like:
  2. "Start a loan scoring for customer 123"
  3. "Check if customer qualifies for a loan"
  4. "Run loan evaluation for borrower 456"

  5. Multi-Turn Conversation: The AI can handle:

  6. Confirming customer existence
  7. Listing available products if user asks
  8. Validating loan amounts
  9. Explaining scoring results

  10. Error Recovery: If a step fails, the AI guides the user to retry or correct input

  11. Context Preservation: Customer ID and product ID are passed through workflow steps

Technical Implementation

Key Components

  1. Workflow State Management
  2. Each step validates previous inputs
  3. Returns guidance for next step
  4. Maintains data continuity across steps

  5. Validation Layers

  6. Customer existence check
  7. Blacklist verification
  8. Loan amount range validation
  9. Product availability check

  10. Scoring Integration

  11. Uses existing LoanScoringService
  12. Respects configured scoring weights
  13. Returns risk level and recommendation
  14. Logs score to LoanScoreLog for history

  15. Error Handling

  16. Try-catch blocks around each step
  17. Graceful error messages
  18. Suggestions for resolution
  19. Logging of failures

Files Modified

  • ai_agent.py
  • Added start_loan_scoring_workflow tool definition
  • Implemented 4-step workflow handler in execute_tool()
  • Added proper imports and error handling

  • ai_agent_module.md

  • Documented new workflow tool
  • Added example prompts

Benefits

  1. Streamlined Process: Consolidates multi-step loan evaluation into one workflow
  2. Staff Efficiency: Reduces need to navigate multiple screens
  3. Consistent Evaluation: Ensures all required data is collected
  4. Clear Feedback: At each step, staff knows what's expected
  5. Error Prevention: Validates inputs before proceeding
  6. Documentation: Scoring is automatically logged for audit trail

Limitations & Future Enhancements

Current Limitations

  • One customer per workflow instance (restart for new customer)
  • Uses internal scoring only (could add external bureau scores)
  • No document review integration
  • No guarantor/collateral assessment in workflow

Future Enhancements

  1. Document Collection: Integrate document upload in workflow
  2. Guarantor Assessment: Add guarantor evaluation step
  3. Collateral Valuation: Include collateral assessment
  4. Product Comparison: Compare scores across multiple products
  5. Batch Processing: Score multiple customers in one session
  6. Export Functionality: Generate loan evaluation PDF report
  7. Approval Workflow: Integrate with loan approval process
  8. External Scoring: Add bureau credit score integration

Testing Recommendations

Unit Testing

  1. Test each workflow step independently
  2. Test validation for each input parameter
  3. Test error scenarios (invalid customer, blacklisted, etc.)
  4. Test score calculation with various customer profiles

Integration Testing

  1. Test full workflow end-to-end
  2. Test workflow with existing AI agent conversation flow
  3. Test with multi-turn conversations
  4. Test error recovery and retries

User Acceptance Testing

  1. Test with staff on real customer scenarios
  2. Verify score accuracy matches manual calculations
  3. Verify workflow guidance is clear
  4. Test with edge cases (max/min amounts, new customers, etc.)

API Endpoint

The workflow is invoked through the existing AI agent chat endpoint:

POST /api/v1/ai-agent/chat

Request Example:

{
  "messages": [
    {
      "role": "user",
      "content": "Start a loan scoring for customer 123 with product 5 and amount 50000"
    }
  ]
}

Response Example:

{
  "message": "Loan scoring completed. Score: 750, Risk Level: LOW. Recommendation: APPROVED.",
  "tool_calls_used": ["start_loan_scoring_workflow"]
}

Configuration

The workflow uses existing configuration: - OPENAI_API_KEY: For LLM communication - OPENAI_MODEL: Model used for conversation - Loan scoring weights (from environment): - LOAN_REPAYMENT_HISTORY_SCORE - LOAN_EXPOSURE_SCORE - LOAN_INCOME_STABILITY_SCORE - LOAN_BEHAVIORAL_SCORE

Security Considerations

  1. Permission Checks: Uses existing ai_agent permission
  2. User Audit: Actions logged with current_user context
  3. Data Validation: All inputs validated before processing
  4. Error Messages: Non-sensitive error messages returned to user
  5. Logging: Detailed logging for debugging and audit

Conclusion

The Loan Scoring Workflow provides a seamless, conversational interface for staff to evaluate customer loan applications. It combines data collection, validation, and scoring in an intuitive, step-by-step process.