How Our Belfast Team Built an AI Chatbot: Complete Guide with OpenAI GPT-4o, Laravel & Integrations

Learn how to build a protected AI chatbot using OpenAI GPT-4o and Laravel. Complete implementation guide covering architecture, rate limiting, abuse protection, and cost control. Expert AI chatbot development services available.

AI-powered chatbots have revolutionized how businesses interact with potential customers. At WeeSite, our Belfast-based team has implemented a sophisticated chatbot system using OpenAI GPT-4o and Laravel that not only engages visitors but also qualifies leads through natural conversation. However, building a chatbot is only half the battle—protecting it from abuse is equally critical.

In this article, we'll explore how we built our chatbot, what's under the hood, and why implementing robust protection mechanisms is essential for cost control and security.

Why Build an AI Chatbot?

Modern chatbots powered by large language models (LLMs) like GPT-4o offer several advantages over traditional rule-based chatbots:

  • Natural Conversation: Understands context and responds naturally, not just keyword matching
  • Lead Qualification: Can intelligently collect information through conversation
  • 24/7 Availability: Always available to answer questions and engage visitors
  • Scalability: Handles multiple conversations simultaneously without additional staff
  • Consistency: Provides consistent, accurate information about your services

Our Chatbot Architecture

Our chatbot is built using a modular Laravel architecture, following best practices for maintainability and scalability:

Technology Stack

Component Technology Purpose
Backend Framework Laravel 11 API endpoints, business logic, protection
AI Model OpenAI GPT-4o Conversational intelligence, lead qualification
Frontend Alpine.js Interactive chat widget UI
API Client openai-php/laravel OpenAI API integration
Storage Laravel Cache + Database Rate limiting, blocked IPs, conversations

Module Structure

Following Laravel's best practices, we organized the chatbot into a dedicated module:

modules/Chatbot/
├── Controllers/
│   ├── ChatbotController.php          # Main API endpoint
│   └── AdminChatbotProtectionController.php  # Admin interface
├── Services/
│   ├── ChatbotService.php             # Core chatbot logic
│   ├── ChatbotProtectionService.php   # Rate limiting & abuse protection
│   └── ChatbotConversationStorageService.php  # Conversation storage
├── Models/
│   └── ChatbotBlockedIp.php           # Blocked IPs model
├── config/
│   ├── chatbot-knowledge.php          # Knowledge base & prompts
│   └── chatbot-protection.php         # Protection configuration
├── resources/views/
│   ├── components/chatbot/
│   │   └── chatbot-widget.blade.php  # Frontend widget
│   └── admin/
│       └── chatbot-protection.blade.php  # Admin interface
└── routes/
    └── chatbot.php                    # Route definitions

How the Chatbot Works

1. Frontend Widget (Alpine.js)

The chatbot widget is a floating button that expands into a chat window. Built with Alpine.js, it handles:

  • User interface and animations
  • Message display and conversation history
  • API communication with the backend
  • Session management (UUID-based)

2. API Endpoint (Laravel Controller)

The ChatbotController receives messages and:

  1. Validates the incoming request
  2. Checks protection mechanisms (rate limiting, suspicious patterns)
  3. Processes the message through the chatbot service
  4. Returns the AI response

3. Core Chatbot Service

The ChatbotService is the heart of the system:

public function processMessage(string $message, array $conversationHistory, ?string $sessionId): array
{
    // 1. Build system prompt with knowledge base
    $systemPrompt = $this->buildSystemPrompt();
    
    // 2. Build conversation messages
    $messages = $this->buildMessages($systemPrompt, $message, $conversationHistory);
    
    // 3. Call OpenAI API
    $response = OpenAI::chat()->create([
        'model' => 'gpt-4o',
        'messages' => $messages,
        'temperature' => 0.7,
        'max_tokens' => 500,
    ]);
    
    // 4. Extract lead data from conversation
    $collectedData = $this->extractCollectedDataWithAI($conversationHistory, $message);
    
    // 5. Save lead if all required data is collected
    if ($this->hasRequiredData($collectedData)) {
        $leadId = $this->saveLead($collectedData, $sessionId);
    }
    
    // 6. Store conversation for analysis
    $this->conversationStorage->storeConversation($sessionId, $conversationHistory);
    
    return $response;
}

4. Knowledge Base & System Prompt

The chatbot's knowledge is stored in config/chatbot-knowledge.php, containing:

  • Company information and services
  • Founder and team details
  • Service descriptions and pricing ranges
  • Lead qualification requirements
  • System prompt instructions for the AI

The system prompt guides the AI to:

  • Introduce itself as "Olivia"
  • Provide helpful information about services
  • Naturally collect lead qualification data
  • Submit leads when all required information is gathered
  • Maintain a professional, friendly tone

5. Lead Qualification & Extraction

The chatbot intelligently extracts lead information from conversations using:

  • AI Extraction: Uses GPT-4o to parse conversation and extract structured data
  • Regex Fallback: Pattern matching for common data formats (emails, phone numbers, budgets)
  • Validation: Ensures all required fields are collected before submission

6. CRM Integration & Lead Storage

Once the chatbot collects all required information, it automatically saves leads to our CRM system:

  • Structured Data Storage: Leads are stored in markdown format with all qualification data
  • Lead Tracking: Each lead gets a unique UUID for tracking through the entire sales funnel
  • Data Organization: Information is organized into phases (contact details, qualification, project requirements)
  • Source Attribution: Leads are tagged with "chatbot" source for analytics

Integration Ecosystem

Our chatbot doesn't operate in isolation—it's part of a comprehensive lead management ecosystem that includes booking, calendar, and communication integrations:

1. Booking System Integration

After collecting lead information, the chatbot can generate secure booking links for discovery calls:

  • Secure Token Generation: Creates encrypted tokens linking bookings to specific leads
  • Seamless Handoff: Users can schedule calls directly from the chat conversation
  • Data Pre-filling: Booking forms automatically populate with information collected during the chat
  • Lead Linking: Bookings are automatically linked to chatbot leads for complete tracking

2. Google Calendar Integration

When a user books a discovery call through the chatbot, the system automatically:

  • Creates Calendar Events: Automatically creates events in Google Calendar via API
  • Sends Invites: Calendar invites are sent to both the user and your team
  • Includes Details: Events contain all booking information (name, company, purpose, timezone)
  • Error Handling: Bookings succeed even if calendar creation fails

The system supports multiple calendar integration methods:

  • Google Calendar API: Direct integration using service account authentication
  • ICS File Generation: Creates downloadable calendar files for manual import
  • Webhook Integration: Can send booking data to automation tools like n8n

3. Zoom Integration

The booking system integrates with Zoom for virtual meetings:

  • Meeting Creation: Can automatically create Zoom meetings for scheduled calls
  • OAuth Authentication: Uses Zoom Server-to-Server OAuth for secure API access
  • Link Management: Zoom meeting links are stored with booking records
  • Webhook Support: Can integrate with automation tools for custom workflows

4. WhatsApp Notifications

When bookings are created, the system can send WhatsApp notifications:

  • Twilio Integration: Uses Twilio WhatsApp API for reliable message delivery
  • Template Messages: Uses Meta-approved WhatsApp message templates
  • Status Tracking: Monitors message delivery status via webhooks
  • Booking Details: Sends formatted booking information including date, time, and attendee details

5. Complete Lead Journey

The entire flow from chatbot conversation to booked call:

  1. Chatbot Conversation: User interacts with chatbot, providing information naturally
  2. Lead Extraction: AI extracts structured data from conversation
  3. CRM Storage: Lead is saved to CRM with unique ID
  4. Booking Link: Chatbot generates secure booking link
  5. Calendar Selection: User selects date and time
  6. Booking Creation: System creates booking, links to lead
  7. Calendar Event: Google Calendar event created automatically
  8. Zoom Meeting: Zoom meeting created
  9. Notifications: Email confirmations and WhatsApp notifications sent
  10. Reminders: Automated 24-hour reminder emails

This integrated approach ensures no lead falls through the cracks and provides a seamless experience from initial contact to scheduled call.

Why Protection is Critical

Without protection, a malicious script could:

  • Drain Your Budget: Send thousands of requests per minute, costing hundreds or thousands of pounds per day
  • Overwhelm Your System: Cause server overload and downtime
  • Generate Spam Leads: Fill your database with fake or malicious data
  • Impact Legitimate Users: Slow down or block real customers from using the chatbot

Cost Impact Example

Without Protection:

  • Script sends 1,000 requests/minute
  • ~500 tokens per request = 500,000 tokens/minute
  • Cost: ~£1.25-5/minute
  • Daily cost: £1,800-7,200 💸

With Protection:

  • Max 10 requests/minute per IP
  • Max 200 requests/day per IP
  • Cost: ~£0.25-1/day per IP
  • Daily cost: £0.25-1

Savings: 99.9%+

Our Protection Mechanisms

We implemented multiple layers of protection:

1. Laravel Throttle Middleware

First line of defense - limits requests at the route level:

Route::post('/api/chatbot', [ChatbotController::class, 'chat'])
    ->middleware('throttle:20,1'); // 20 requests per minute

2. IP-Based Rate Limiting

Tracks requests per IP address with multiple time windows:

Time Window Limit Action
Per Minute 10 requests Block with retry time
Per Hour 50 requests Block for 1 hour
Per Day 200 requests Block for 24 hours

3. Session-Based Limits

  • Maximum 50 messages per conversation
  • Minimum 1 second between messages (prevents rapid-fire)

4. Message Validation

  • Maximum 1,000 characters per message
  • Prevents extremely long messages that waste tokens

5. Suspicious Pattern Detection

Detects bot-like behavior:

  • Repeated Identical Messages: Same message sent multiple times
  • Rapid Short Messages: Many very short messages in quick succession
  • Suspicious Keywords: Logs messages containing keywords like "test", "bot", "script"

6. Automatic IP Blocking

After 5 abuse incidents, IPs are automatically blocked for 7 days. This prevents persistent attackers from repeatedly violating limits.

7. Database Storage

Blocked IPs are stored in a database table for:

  • Permanent reference (survives cache clears)
  • Historical tracking
  • Admin management interface
  • Audit trail

Admin Interface

We built an admin interface to manage blocked IPs:

  • View All Blocked IPs: See active and expired blocks
  • Manual Blocking: Block specific IPs with custom duration
  • Unblock IPs: Remove blocks with one click
  • Abuse Statistics: View request counts and abuse history per IP

Implementation Details

Protection Service Flow

public function checkRequest(string $ip, string $sessionId, string $message, array $conversationHistory): array
{
    // 1. Check if IP is blocked
    if ($this->isIpBlocked($ip)) {
        return ['allowed' => false, 'reason' => 'IP blocked'];
    }
    
    // 2. Check IP-based rate limits
    $ipCheck = $this->checkIpRateLimit($ip);
    if (!$ipCheck['allowed']) {
        return $ipCheck;
    }
    
    // 3. Check session-based rate limits
    $sessionCheck = $this->checkSessionRateLimit($sessionId, $conversationHistory);
    if (!$sessionCheck['allowed']) {
        return $sessionCheck;
    }
    
    // 4. Check message length
    if (strlen($message) > MAX_LENGTH) {
        return ['allowed' => false, 'reason' => 'Message too long'];
    }
    
    // 5. Check for suspicious patterns
    $suspiciousCheck = $this->checkSuspiciousPatterns($ip, $message, $conversationHistory);
    if (!$suspiciousCheck['allowed']) {
        return $suspiciousCheck;
    }
    
    // 6. Check minimum time between messages
    $timingCheck = $this->checkMessageTiming($ip, $sessionId);
    if (!$timingCheck['allowed']) {
        return $timingCheck;
    }
    
    return ['allowed' => true];
}

Configuration

All protection settings are configurable via config/chatbot-protection.php:

return [
    'rate_limits' => [
        'per_minute' => env('CHATBOT_RATE_LIMIT_MINUTE', 10),
        'per_hour' => env('CHATBOT_RATE_LIMIT_HOUR', 50),
        'per_day' => env('CHATBOT_RATE_LIMIT_DAY', 200),
    ],
    'session_limits' => [
        'max_messages' => env('CHATBOT_MAX_MESSAGES_PER_SESSION', 50),
        'min_time_between_messages' => env('CHATBOT_MIN_TIME_BETWEEN_MESSAGES', 1),
    ],
    'abuse_detection' => [
        'auto_block_threshold' => env('CHATBOT_AUTO_BLOCK_THRESHOLD', 5),
        'auto_block_duration' => env('CHATBOT_AUTO_BLOCK_DURATION', 7),
    ],
];

Best Practices

1. Monitor OpenAI Usage

  • Set up usage alerts in OpenAI dashboard
  • Monitor daily/weekly costs
  • Set spending limits

2. Log Everything

All protection events are logged for monitoring:

Log::warning('Chatbot: IP rate limit exceeded', ['ip' => $ip]);
Log::warning('Chatbot: Suspicious pattern detected', ['ip' => $ip]);
Log::critical('Chatbot: IP auto-blocked due to abuse', ['ip' => $ip]);

3. Regular Review

  • Review blocked IPs regularly
  • Check abuse statistics
  • Adjust limits based on legitimate usage patterns

Conclusion

Building an AI chatbot is exciting, but protecting it from abuse is essential. Our multi-layer protection system ensures:

  • Cost Control: Prevents budget drain from malicious scripts
  • Security: Protects against automated attacks
  • Performance: Maintains system stability
  • User Experience: Legitimate users aren't affected

By implementing comprehensive protection mechanisms, we've created a chatbot that's both powerful and secure—ready for production use while maintaining cost efficiency.

If you're considering implementing an AI chatbot for your business in Belfast or across the UK, remember: protection is not optional—it's essential. Our Belfast-based team offers custom AI chatbot development services, helping businesses build protected, cost-effective chatbot solutions tailored to their specific needs.

Need AI Chatbot Development in Belfast?

Our Belfast-based team specializes in AI chatbot development using OpenAI GPT-4o, Laravel, and modern web technologies. We can help you build a protected, cost-effective chatbot solution for your business. Contact us for expert AI chatbot development services in Belfast. Looking for Laravel development services in Belfast or Dublin? Contact us today.

Related Articles

Custom AI Chatbot Development Belfast
Date Icon 7 December 2025
Guides

Custom AI Chatbot Development Belfast: Why Businesses Are Investing in AI Automation

Discover why businesses in Belfast and across the UK are investing in custom AI chatbots. Learn about different chatbot types, real-world automation scenarios, and how protected AI chatbots can transform customer engagement and operational efficiency.

Laravel Security Best Practices
Date Icon 15 November 2023
Guides

Laravel Security Best Practices: Protecting Your Application

Learn essential Laravel security best practices to protect your application for businesses in Belfast, Dublin, and across the Island of Ireland. This guide covers authentication, SQL injection prevention, XSS protection, CSRF tokens, file upload security, and more.

Laravel API Development Best Practices
Date Icon 17 February 2023
Guides

Laravel API Development Best Practices: A Complete Guide for 2025

Master Laravel API development with this comprehensive guide for businesses in Belfast, Dublin, and across the Island of Ireland. Covering RESTful design, authentication, security, performance optimization, and testing strategies. Learn best practices from experienced Laravel developers.

STAY UPDATED WITH OUR LATEST ARTICLES

Don't miss out on our latest articles, product updates, and industry insights. Subscribe to get notified when we publish new content.