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:
- Natural Language Trigger: User can say things like:
- "Start a loan scoring for customer 123"
- "Check if customer qualifies for a loan"
-
"Run loan evaluation for borrower 456"
-
Multi-Turn Conversation: The AI can handle:
- Confirming customer existence
- Listing available products if user asks
- Validating loan amounts
-
Explaining scoring results
-
Error Recovery: If a step fails, the AI guides the user to retry or correct input
-
Context Preservation: Customer ID and product ID are passed through workflow steps
Technical Implementation¶
Key Components¶
- Workflow State Management
- Each step validates previous inputs
- Returns guidance for next step
-
Maintains data continuity across steps
-
Validation Layers
- Customer existence check
- Blacklist verification
- Loan amount range validation
-
Product availability check
-
Scoring Integration
- Uses existing
LoanScoringService - Respects configured scoring weights
- Returns risk level and recommendation
-
Logs score to
LoanScoreLogfor history -
Error Handling
- Try-catch blocks around each step
- Graceful error messages
- Suggestions for resolution
- Logging of failures
Files Modified¶
- ai_agent.py
- Added
start_loan_scoring_workflowtool definition - Implemented 4-step workflow handler in
execute_tool() -
Added proper imports and error handling
- Documented new workflow tool
- Added example prompts
Benefits¶
- Streamlined Process: Consolidates multi-step loan evaluation into one workflow
- Staff Efficiency: Reduces need to navigate multiple screens
- Consistent Evaluation: Ensures all required data is collected
- Clear Feedback: At each step, staff knows what's expected
- Error Prevention: Validates inputs before proceeding
- 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¶
- Document Collection: Integrate document upload in workflow
- Guarantor Assessment: Add guarantor evaluation step
- Collateral Valuation: Include collateral assessment
- Product Comparison: Compare scores across multiple products
- Batch Processing: Score multiple customers in one session
- Export Functionality: Generate loan evaluation PDF report
- Approval Workflow: Integrate with loan approval process
- External Scoring: Add bureau credit score integration
Testing Recommendations¶
Unit Testing¶
- Test each workflow step independently
- Test validation for each input parameter
- Test error scenarios (invalid customer, blacklisted, etc.)
- Test score calculation with various customer profiles
Integration Testing¶
- Test full workflow end-to-end
- Test workflow with existing AI agent conversation flow
- Test with multi-turn conversations
- Test error recovery and retries
User Acceptance Testing¶
- Test with staff on real customer scenarios
- Verify score accuracy matches manual calculations
- Verify workflow guidance is clear
- Test with edge cases (max/min amounts, new customers, etc.)
API Endpoint¶
The workflow is invoked through the existing AI agent chat endpoint:
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¶
- Permission Checks: Uses existing
ai_agentpermission - User Audit: Actions logged with current_user context
- Data Validation: All inputs validated before processing
- Error Messages: Non-sensitive error messages returned to user
- 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.