Skip to content

AI Agent Module

Overview

The AI Agent module provides a conversational AI interface powered by OpenAI that allows users and staff to query banking data, execute transactions, and get insights through natural language. Users can ask questions about their accounts, loans, transactions, and more in plain English, and the AI agent will provide answers or execute actions.

API Prefix: /api/v1/ai-agent

Route Verification Status

  • Source Router: app/api/v1/endpoints/ai_agent.py
  • Live Route Count: 3
  • Verification State: Verified (2026-06-28)
  • Canonical Tracking: docs/API_ROUTE_DOCUMENTATION_TODO.md
  • Verification Method: Route decorators extracted from @r.<method>(...) in app/api/v1/endpoints/ai_agent.py.

Key Features

1. Natural Language Processing

  • Parse user queries in natural language
  • Intent recognition (query, action, help)
  • Entity extraction (loan ID, amount, date range)
  • Context awareness and conversation history
  • Multi-turn conversations

2. Query Capabilities

  • Account balance inquiries
  • Transaction history search
  • Loan portfolio analysis
  • Payment due date queries
  • Campaign and offer information
  • Agent performance data

3. Action Capabilities

  • Execute simple transactions
  • Submit bills for payment
  • Apply for loans
  • Update profile information
  • Request account statements
  • Initiate customer support

4. Analytics & Insights

  • Transaction trends and patterns
  • Spending analysis
  • Loan performance analysis
  • Fraud risk assessment
  • Recommendations (optimize fees, increase savings)

5. Conversation Management

  • Multi-turn conversation support
  • Context preservation across messages
  • Conversation history tracking
  • Session management
  • Clarification requests

API Endpoints (Verified Against Live Router)

For the complete AI agent endpoint inventory (all 3 routes with method, effective path, and source line), use: - docs/API_ROUTE_LIVE_REFERENCE.md -> section ai_agent.py (3 routes)

Database Models

Conversation Models

  • Conversation: Chat session record
  • Conversation ID, user ID
  • Start and end timestamps
  • Conversation metadata

  • ConversationMessage: Individual messages

  • Message ID, conversation ID
  • User message and AI response
  • Timestamp
  • Intent and entities extracted

AI Models

  • AIConfiguration: AI model settings and parameters
  • AIToolDefinition: Available tools and actions
  • AIKnowledgeBase: Training data and context

AI Agent Capabilities

Query Examples

Account & Wallet Queries

User: "What's my current balance?"
AI: "Your wallet balance is 25,500 ZMW across 2 wallets"

User: "Show me my transactions from last week"
AI: [List of 15 transactions with dates and amounts]

User: "How much did I spend on bill payments this month?"
AI: "You spent 8,500 ZMW on bill payments this month"

Loan Queries

User: "Tell me about my loans"
AI: "You have 2 active loans:
  1. Personal Loan - 50,000 ZMW (12% interest, 24 months)
     - Next payment: 2,500 ZMW on June 15
     - Paid: 5,000 ZMW of 60,000 ZMW total
  2. Business Loan - 100,000 ZMW (15% interest, 36 months)
     - Next payment: 3,500 ZMW on June 10"

User: "What's my loan repayment schedule?"
AI: [Detailed schedule for all loans]

User: "When is my next loan payment due?"
AI: "Your next payment of 2,500 ZMW is due on June 15"

Campaign & Offer Queries

User: "What promotions do I qualify for?"
AI: "You qualify for:
  - 20% discount on transfers (active until July 31)
  - Referral bonus: Invite 3 friends, earn 1,500 ZMW
  - Loyalty points: You have 2,500 points available"

User: "How do I redeem my loyalty points?"
AI: "You can redeem your 2,500 points for:
  - 500 ZMW cashback
  - Free bill payment (covers up to 2,500 ZMW)
  - 5,000 ZMW airtime"

Action Examples

User: "Send 1,000 ZMW to John"
AI: "I can help with that. Confirm:
  - Send 1,000 ZMW to John (0712345678)
  - Fee: 10 ZMW (1%)
  - Total: 1,010 ZMW
  Confirm? (yes/no)"

User: "Pay my electricity bill"
AI: "I found 1 electricity bill for 3,500 ZMW due on June 20.
  Pay this bill? (yes/no)"

User: "Apply for a 50,000 ZMW loan"
AI: "I can help you apply for a loan. Let me gather some info:
  - What's the loan purpose? (personal/business/education)"

AI Tools Available

Data Query Tools

Available Tools:
1. get_account_balance(wallet_id)
   - Returns: balance, currency, wallet_type

2. get_transaction_history(date_from, date_to, limit)
   - Returns: transactions, amount, date, merchant

3. get_loan_details(loan_id?)
   - Returns: loan_amount, term, rate, next_payment, balance

4. get_campaign_offers()
   - Returns: active campaigns, discounts, eligibility

5. get_payment_schedule(loan_id)
   - Returns: installment schedule, amounts, dates

6. search_customer(query)
   - Returns: matching customers for transfer

7. get_agent_performance(agent_id?, date_range)
   - Returns: transactions, revenue, metrics

Action Tools

Available Tools:
1. send_money(recipient, amount, description)
   - Pre-confirm before executing

2. pay_bill(biller_id, amount)
   - Pre-confirm before executing

3. request_loan(amount, purpose, term)
   - Create loan application, send to underwriting

4. redeem_points(points_amount, reward_type)
   - Redeem loyalty points for reward

5. update_profile(field, value)
   - Update customer profile information

6. generate_statement(date_from, date_to)
   - Generate and email statement

Conversation Flow

Multi-Turn Conversation Example

User: "What was my biggest transaction this month?"
AI: "Your biggest transaction was 45,000 ZMW paid to ZESCO Ltd 
     on June 5th. Would you like more details?"

User: "Yes, and can you show me all my utility bills?"
AI: "You have 3 utility bills this month:
     - ZESCO: 45,000 ZMW (paid June 5)
     - Water Co: 8,500 ZMW (due June 20)
     - ISP: 2,500 ZMW (due June 25)
     Total: 56,000 ZMW"

User: "Pay the water bill"
AI: "I'll pay 8,500 ZMW to Water Co due June 20.
     Processing fee: 130 ZMW (1.5%)
     Total: 8,630 ZMW
     Confirm? (yes/no)"

User: "yes"
AI: "Payment successful! Reference: TXN-2024-001234
     Water Company will receive payment by tomorrow.
     Receipt sent to your email."

Controllers & Business Logic

AI Agent Controllers

  • controller/ai_agent.py: Main AI logic
  • process_message(): Parse and process user query
  • extract_intent(): Determine user intent
  • extract_entities(): Extract relevant data
  • generate_response(): Generate AI response
  • execute_action(): Execute confirmed actions

  • controller/ai_tools.py: Tool implementations

  • execute_tool(): Execute specific tool
  • validate_tool_params(): Validate tool parameters
  • format_tool_result(): Format result for display

  • controller/ai_conversation.py: Conversation management

  • create_conversation(): Start new chat session
  • save_message(): Store message in history
  • get_conversation_context(): Retrieve conversation history
  • manage_session(): Handle session lifecycle

Configuration

AI Model Configuration

{
  "provider": "openai",
  "model": "gpt-4-turbo",
  "api_key": "***",
  "max_tokens": 2048,
  "temperature": 0.7,
  "system_prompt": "You are a helpful banking assistant...",
  "available_tools": [
    "get_account_balance",
    "get_transaction_history",
    "get_loan_details",
    "send_money",
    "pay_bill"
  ]
}

Tool Definitions

{
  "tools": [
    {
      "name": "get_account_balance",
      "description": "Get wallet balance",
      "parameters": {
        "type": "object",
        "properties": {
          "wallet_id": {"type": "string", "description": "Wallet ID"}
        },
        "required": ["wallet_id"]
      }
    },
    {
      "name": "send_money",
      "description": "Send money to recipient",
      "parameters": {
        "type": "object",
        "properties": {
          "recipient": {"type": "string"},
          "amount": {"type": "number"},
          "description": {"type": "string"}
        },
        "required": ["recipient", "amount"]
      },
      "requires_confirmation": true
    }
  ]
}

Security & Compliance

Safety Measures

  1. Permission Checks: Verify user can access data
  2. Action Confirmation: Require explicit confirmation for actions
  3. Rate Limiting: Limit queries per user per hour
  4. Input Validation: Sanitize all user inputs
  5. Output Filtering: Never expose sensitive data in responses
  6. Audit Logging: Log all AI interactions
  7. Transaction Limits: Enforce policy limits on AI actions

Data Privacy

Sensitive Data Handling:
- Never expose full account/card numbers
- Mask sensitive information in responses
- Encrypt stored conversations
- Auto-delete conversations after 90 days
- Don't log sensitive queries

Common Use Cases

1. Account Information Query

User: "How much money do I have?"
→ AI identifies intent: account_balance
→ Extracts entity: user_id
→ Queries wallet_balance
→ Returns: "You have 25,500 ZMW"
User: "Find all payments to MTN"
→ AI identifies intent: search_transactions
→ Extracts entities: merchant=MTN, transaction_type=payment
→ Queries transaction history
→ Returns: "Found 5 MTN payments totaling 15,000 ZMW"

3. Loan Status Check

User: "When is my loan due?"
→ AI identifies intent: check_loan_status
→ Queries active loans
→ Finds due dates
→ Returns: "Payment of 2,500 ZMW due June 15"

4. Execute Transaction

User: "Send 500 to John"
→ AI identifies intent: send_money
→ Extracts: recipient=John, amount=500
→ Searches for John in contacts
→ Asks for confirmation
→ User confirms
→ Executes transaction
→ Returns: "Sent 500 ZMW to John"

Error Handling

AI Errors

  • INTENT_NOT_UNDERSTOOD: Can't determine user intent
  • INSUFFICIENT_DATA: Missing required information
  • PERMISSION_DENIED: User not authorized for action
  • TOOL_NOT_AVAILABLE: Requested tool not accessible
  • INVALID_PARAMETERS: Invalid parameters for tool
  • EXECUTION_FAILED: Tool execution failed

Testing

Test Categories

  • Intent recognition accuracy
  • Entity extraction accuracy
  • Tool execution correctness
  • Conversation flow management
  • Permission enforcement
  • Action confirmation
  • Error handling

Test Files

  • tests/test_ai_agent.py: AI agent tests
  • conftest.py: AI agent test fixtures

Performance Considerations

  1. Response Time: Cache common queries
  2. Token Optimization: Minimize API tokens used
  3. Conversation History: Truncate old messages
  4. Tool Caching: Cache tool results briefly
  5. Rate Limiting: Prevent abuse

Integration Points

External Services

  • OpenAI API: LLM for processing

Internal Modules

  • Authentication: Verify user identity
  • Customer Management: Access customer data
  • Wallet: Balance and transaction queries
  • Loan: Loan information
  • Transaction: Execute transactions
  • Campaign: Offer information
  • Agent: Agent performance data

Conversation Examples

Example 1: Budget Analysis

User: "Am I over budget this month?"
AI: "Your monthly budget is 50,000 ZMW. 
     You've spent 42,300 ZMW so far (85%).
     Remaining budget: 7,700 ZMW
     Biggest category: Bills (18,000 ZMW)"

User: "Show me my spending by category"
AI: "Your spending breakdown:
     - Bills: 18,000 ZMW (43%)
     - Groceries: 12,500 ZMW (30%)
     - Transport: 8,000 ZMW (19%)
     - Entertainment: 3,800 ZMW (9%)"

Example 2: Loan Analysis

User: "Analyze my loans"
AI: "You have 2 loans totaling 150,000 ZMW:
     - Personal (50K): 4 years remaining
     - Business (100K): 2 years remaining
     Total interest to pay: 42,500 ZMW
     Monthly payments: 6,000 ZMW"

User: "What if I paid extra on the personal loan?"
AI: "If you paid an extra 500 ZMW/month on your personal loan:
     - Loan would be paid off 6 months faster
     - You'd save 2,100 ZMW in interest"