Skip to content

iammerus/zeki

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Zeki

A flexible and extensible framework for building WhatsApp bots.

Features

  • Support for multiple WhatsApp providers (Facebook Cloud API, Twilio)
  • Intent-based message handling
  • Advanced AI-powered intent detection (OpenAI, Anthropic, Google)
  • Middleware architecture for flexible request processing
  • Support for interactive messages (buttons, lists, templates)
  • Media message support (images, audio, video, documents)
  • Location message support
  • Conversation state management
  • Extensible architecture
  • Simple configuration
  • Logging and monitoring

Installation

composer require zeki/bot-framework

Quick Start

1. Create a .env file

# WhatsApp Provider Configuration
WHATSAPP_PROVIDER=facebook  # or twilio
WHATSAPP_ACCESS_TOKEN=your_access_token  # For Facebook provider
WHATSAPP_PHONE_NUMBER_ID=your_phone_number_id  # For Facebook provider
# OR
TWILIO_ACCOUNT_SID=your_account_sid  # For Twilio provider
TWILIO_AUTH_TOKEN=your_auth_token  # For Twilio provider
TWILIO_FROM_NUMBER=your_from_number  # For Twilio provider

# AI Provider Configuration
AI_PROVIDER=openai  # or anthropic, google
OPENAI_API_KEY=your_openai_api_key
OPENAI_MODEL=gpt-3.5-turbo  # or gpt-4, etc.
# OR
ANTHROPIC_API_KEY=your_anthropic_api_key
ANTHROPIC_MODEL=claude-3-haiku-20240307  # or claude-3-opus-20240229, etc.
# OR
GOOGLE_API_KEY=your_google_api_key
GOOGLE_MODEL=gemini-pro  # or gemini-pro-vision, etc.

# Cache Configuration
CACHE_DSN=redis://localhost:6379

# Webhook Configuration
WEBHOOK_VERIFY_TOKEN=your_verify_token

# Logging Configuration
LOG_LEVEL=info  # debug, info, notice, warning, error, critical, alert, emergency
LOG_FILE=php://stderr  # or path to log file

2. Create a webhook handler

<?php

require_once __DIR__ . '/vendor/autoload.php';

use Zeki\Core\Application;

// Initialize the application
$app = new Application();

// Run the application
$app->run();

3. Create a custom intent

<?php

namespace YourApp\Intent;

use Zeki\Intent\IntentInterface;
use Zeki\Service\WhatsApp\WhatsAppService;

class GreetingIntent implements IntentInterface
{
    private $whatsapp;
    
    public function __construct(WhatsAppService $whatsapp)
    {
        $this->whatsapp = $whatsapp;
    }
    
    public function canHandle(string $intent): bool
    {
        return $intent === 'greeting';
    }
    
    public function getName(): string
    {
        return 'greeting';
    }
    
    public function handle(string $userPhone, string $message, array $context = []): void
    {
        $this->whatsapp->sendMessage($userPhone, "Hello! How can I help you today?");
        $this->markComplete($userPhone);
    }
    
    public function isInProgress(string $userPhone): bool
    {
        return false;
    }
    
    public function markComplete(string $userPhone): void
    {
        // No state to clean up
    }
}

4. Register your intent

<?php

require_once __DIR__ . '/vendor/autoload.php';

use Zeki\Core\Application;
use YourApp\Intent\GreetingIntent;

// Initialize the application
$app = new Application();

// Register your custom intent
$app->registerIntent(new GreetingIntent($app->getWhatsAppService()));

// Run the application
$app->run();

Architecture

The framework is built with a modular architecture:

  • Core: Contains the main application logic, request/response handling, and middleware
  • Intent: Handles different types of user intents
  • Service: Provides services like WhatsApp messaging, chat history, AI, etc.
  • Provider: Implements different WhatsApp API providers
  • Middleware: Processes requests in a pipeline

Middleware Architecture

The framework uses a middleware architecture for processing requests:

use Zeki\Core\Middleware\MiddlewareInterface;
use Zeki\Core\Request;
use Zeki\Core\Response;

class MyCustomMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        // Do something before the next middleware
        
        // Call the next middleware in the stack
        $response = $next($request);
        
        // Do something after the next middleware
        
        return $response;
    }
}

// Register your middleware
$app->registerMiddleware(new MyCustomMiddleware());

Interactive Messages

The framework supports various types of interactive messages:

Button Messages

$whatsapp->sendButtonMessage(
    $userPhone,
    "Please select an option:",
    [
        ['id' => 'option_1', 'text' => 'Option 1'],
        ['id' => 'option_2', 'text' => 'Option 2'],
        ['id' => 'option_3', 'text' => 'Option 3']
    ]
);

List Messages

$whatsapp->sendListMessage(
    $userPhone,
    "Please select a product:",
    "View Products",
    [
        [
            'title' => 'Popular Products',
            'rows' => [
                [
                    'id' => 'product_1',
                    'title' => 'Product 1',
                    'description' => 'Description of Product 1'
                ],
                [
                    'id' => 'product_2',
                    'title' => 'Product 2',
                    'description' => 'Description of Product 2'
                ]
            ]
        ]
    ]
);

Template Messages

$whatsapp->sendTemplateMessage(
    $userPhone,
    'order_confirmation',
    [
        [
            'type' => 'body',
            'parameters' => [
                ['type' => 'text', 'text' => 'ORDER123'],
                ['type' => 'text', 'text' => 'Product Name'],
                ['type' => 'text', 'text' => '$99.99']
            ]
        ]
    ],
    'en_US'
);

Media Messages

The framework supports various types of media messages:

Image Messages

$whatsapp->sendImageMessage(
    $userPhone,
    "Check out this image!",
    "https://example.com/image.jpg"
);

Audio Messages

$whatsapp->sendAudioMessage(
    $userPhone,
    "https://example.com/audio.mp3"
);

Video Messages

$whatsapp->sendVideoMessage(
    $userPhone,
    "Check out this video!",
    "https://example.com/video.mp4"
);

Document Messages

$whatsapp->sendDocumentMessage(
    $userPhone,
    "Here's the document you requested",
    "https://example.com/document.pdf",
    "document.pdf",
    "application/pdf"
);

Location Messages

$whatsapp->sendLocationMessage(
    $userPhone,
    37.7749,
    -122.4194,
    "San Francisco",
    "California, USA"
);

AI Intent Detection

The framework supports multiple AI providers for intent detection:

OpenAI

use Zeki\Service\AI\AIProviderFactory;
use Zeki\Service\AI\SimpleAIService;

$provider = AIProviderFactory::create('openai', [
    'api_key' => 'your_openai_api_key',
    'model' => 'gpt-3.5-turbo' // or gpt-4, etc.
]);
$aiService = new SimpleAIService($provider);
$app->registerAIService($aiService);

Anthropic

use Zeki\Service\AI\AIProviderFactory;
use Zeki\Service\AI\SimpleAIService;

$provider = AIProviderFactory::create('anthropic', [
    'api_key' => 'your_anthropic_api_key',
    'model' => 'claude-3-haiku-20240307' // or claude-3-opus-20240229, etc.
]);
$aiService = new SimpleAIService($provider);
$app->registerAIService($aiService);

Google

use Zeki\Service\AI\AIProviderFactory;
use Zeki\Service\AI\SimpleAIService;

$provider = AIProviderFactory::create('google', [
    'api_key' => 'your_google_api_key',
    'model' => 'gemini-pro' // or gemini-pro-vision, etc.
]);
$aiService = new SimpleAIService($provider);
$app->registerAIService($aiService);

Adding a New AI Provider

  1. Create a new class that extends AbstractAIProvider
  2. Implement the required methods
  3. Register your provider in the AIProviderFactory
use Zeki\Service\AI\Provider\AbstractAIProvider;

class MyCustomAIProvider extends AbstractAIProvider
{
    public function getName(): string
    {
        return 'MyCustomAI';
    }
    
    public function detectIntent(string $message, array $availableIntents = [], array $context = []): string
    {
        // Your custom intent detection logic here
    }
    
    public function generateResponse(string $message, string $systemPrompt, array $context = []): string
    {
        // Your custom response generation logic here
    }
}

// Register in AIProviderFactory
AIProviderFactory::registerProvider('mycustom', MyCustomAIProvider::class);

Extending the Framework

Adding a New WhatsApp Provider

  1. Create a new class that implements WhatsAppProviderInterface
  2. Register your provider in the WhatsAppServiceFactory

Adding a New Intent

  1. Create a new class that implements IntentInterface
  2. Register your intent with the application

Adding a New Middleware

  1. Create a new class that implements MiddlewareInterface
  2. Register your middleware with the application

Advanced Example

Check out the examples/advanced_webhook.php file for a more comprehensive example that demonstrates:

  • Interactive messages (buttons, lists, templates)
  • Custom middleware for analytics
  • Multi-step conversation flows
  • Media message handling

License

MIT

About

A smart, extensible WhatsApp bot framework with multi-provider support and AI-powered intent detection for building sophisticated conversational experiences.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages