PHP code example of rumenx / php-chatbot

1. Go to this page and download the library: Download rumenx/php-chatbot library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rumenx / php-chatbot example snippets


use Rumenx\PhpChatbot\PhpChatbot;
use Rumenx\PhpChatbot\Models\ModelFactory;

$config = ly = $chatbot->ask('Hello!');
echo $reply;

use Rumenx\PhpChatbot\PhpChatbot;
use Rumenx\PhpChatbot\Models\OpenAiModel;

$model = new OpenAiModel('your-api-key', 'gpt-4o');
$chatbot = new PhpChatbot($model);

// Make a request
$response = $chatbot->ask('Explain quantum computing');
echo $response;

// Track token usage
$usage = $chatbot->getLastTokenUsage();
echo "Tokens used: {$usage->totalTokens}\n";

// Calculate cost
$cost = $chatbot->getLastCost();
echo "Cost: $" . number_format($cost, 4) . "\n";

// Estimate cost before making a request
$estimatedCost = $chatbot->estimateCost('This is my prompt');
echo "Estimated: $" . number_format($estimatedCost, 6) . "\n";

use Rumenx\PhpChatbot\PhpChatbot;
use Rumenx\PhpChatbot\Models\OpenAiModel;

$model = new OpenAiModel('your-api-key');
$chatbot = new PhpChatbot($model);

// Get streaming response
foreach ($chatbot->askStream('Hello!') as $chunk) {
    echo $chunk;
    flush(); // Send to browser immediately
}

// Set headers for SSE
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no'); // Disable nginx buffering

$model = ModelFactory::make($config);
$chatbot = new PhpChatbot($model, $config);

// Stream chunks to client
foreach ($chatbot->askStream($message, $context) as $chunk) {
    echo "data: " . json_encode(['chunk' => $chunk]) . "\n\n";
    flush();
}

echo "data: [DONE]\n\n";
flush();

use Rumenx\PhpChatbot\Contracts\StreamableModelInterface;

if ($model instanceof StreamableModelInterface && $model->supportsStreaming()) {
    // Use streaming
    foreach ($chatbot->askStream($message) as $chunk) {
        // Process chunk...
    }
} else {
    // Fallback to regular response
    $reply = $chatbot->ask($message);
}

use Rumenx\PhpChatbot\PhpChatbot;
use Rumenx\PhpChatbot\Models\OpenAiModel;

$config = edis'
    'limits' => [
        'requests' => 10,    // 10 requests
        'window' => 60,      // per 60 seconds
    ],
];

$model = new OpenAiModel('your-api-key');
$chatbot = new PhpChatbot($model, $config);

try {
    $reply = $chatbot->ask('Hello!');
} catch (\Rumenx\PhpChatbot\RateLimiting\RateLimitException $e) {
    // Rate limit exceeded
    echo "Too many requests. Try again in {$e->getRetryAfter()} seconds.";
}

$config['rate_limiting'] = [
    'enabled' => true,
    'driver' => 'redis',
    'limits' => [
        'requests' => 100,
        'window' => 3600,  // 100 requests per hour
    ],
    'redis' => [
        'host' => '127.0.0.1',
        'port' => 6379,
        'database' => 0,
    ],
];

$config['cache'] = [
    'enabled' => true,
    'driver' => 'file',  // 'memory', 'file', or 'redis'
    'ttl' => 3600,       // Cache for 1 hour
    'path' => '/tmp/chatbot-cache',  // for file driver
];

$chatbot = new PhpChatbot($model, $config);

// First call: hits API
$reply1 = $chatbot->ask('What is PHP?');

// Second call: returns cached response (no API call)
$reply2 = $chatbot->ask('What is PHP?');

$config['cache'] = [
    'enabled' => true,
    'driver' => 'redis',
    'ttl' => 7200,  // 2 hours
    'redis' => [
        'host' => '127.0.0.1',
        'port' => 6379,
        'database' => 1,
    ],
];

use Rumenx\PhpChatbot\Health\HealthMonitor;
use Rumenx\PhpChatbot\Health\ModelHealthChecker;
use Rumenx\PhpChatbot\Health\StorageHealthChecker;
use Rumenx\PhpChatbot\Health\CacheHealthChecker;

$model = new OpenAiModel('your-api-key');
$storage = new FileStorage('/tmp/chatbot-memory');
$cache = new MemoryCache();

$monitor = new HealthMonitor();
$monitor->registerChecker('model', new ModelHealthChecker($model));
$monitor->registerChecker('storage', new StorageHealthChecker($storage));
$monitor->registerChecker('cache', new CacheHealthChecker($cache));

// Check overall health
$results = $monitor->checkAll();
$overallHealth = $monitor->getOverallHealth($results);

echo "System Health: {$overallHealth->value}\n";

foreach ($results as $name => $result) {
    echo "{$name}: {$result->status->value} ";
    echo "({$result->metrics['response_time']}ms)\n";
    
    if ($result->message) {
        echo "  → {$result->message}\n";
    }
}

// HTTP endpoint for health checks
Route::get('/health/chatbot', function () {
    $results = $healthMonitor->checkAll();
    $status = $healthMonitor->getOverallHealth($results);
    
    return response()->json([
        'status' => $status->value,
        'checks' => array_map(fn($r) => [
            'status' => $r->status->value,
            'message' => $r->message,
            'metrics' => $r->metrics,
        ], $results),
    ], $status === HealthStatus::HEALTHY ? 200 : 503);
});

use Rumenx\PhpChatbot\Exceptions\PhpChatbotException;      // Base exception
use Rumenx\PhpChatbot\Exceptions\ApiException;            // API-related errors
use Rumenx\PhpChatbot\Exceptions\NetworkException;        // Network/connectivity errors
use Rumenx\PhpChatbot\Exceptions\ModelException;          // Model-specific errors
use Rumenx\PhpChatbot\Exceptions\InvalidConfigException;  // Configuration errors
use Rumenx\PhpChatbot\Exceptions\MemoryException;         // Memory storage errors
use Rumenx\PhpChatbot\RateLimiting\RateLimitException;    // Rate limit errors

use Rumenx\PhpChatbot\Exceptions\ApiException;
use Rumenx\PhpChatbot\Exceptions\NetworkException;
use Rumenx\PhpChatbot\Exceptions\RateLimitException;

try {
    $reply = $chatbot->ask($message);
    echo $reply;
} catch (RateLimitException $e) {
    // User exceeded rate limit
    http_response_code(429);
    echo json_encode([
        'error' => 'Too many requests',
        'retry_after' => $e->getRetryAfter(),
    ]);
} catch (ApiException $e) {
    // API error (invalid key, quota exceeded, etc.)
    http_response_code(502);
    echo json_encode([
        'error' => 'AI service error',
        'details' => $e->getMessage(),
        'status_code' => $e->getStatusCode(),
    ]);
} catch (NetworkException $e) {
    // Network/connectivity error
    http_response_code(503);
    echo json_encode([
        'error' => 'Service temporarily unavailable',
        'details' => $e->getMessage(),
    ]);
} catch (\Exception $e) {
    // Generic error
    http_response_code(500);
    echo json_encode(['error' => 'Internal server error']);
}

$config['throw_exceptions'] = false;

$chatbot = new PhpChatbot($model, $config);
$reply = $chatbot->ask($message);

// Errors will be returned as strings instead of throwing exceptions
if (str_starts_with($reply, 'Error:')) {
    // Handle error
}

// src/Controller/ChatbotController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Rumenx\PhpChatbot\PhpChatbot;
use Rumenx\PhpChatbot\Models\ModelFactory;

class ChatbotController extends AbstractController
{
    public function message(Request $request): JsonResponse
    {
        $config = 

// routes/web.php
Route::post('/php-chatbot/message', function (Request $request) {
    // ...existing code...
})->middleware('throttle:60,1'); // Framework-level: 60 requests per minute per IP

// Framework middleware: Protects against DDoS (IP-based)
Route::middleware('throttle:60,1')->group(function () {
    // Built-in rate limiter: Protects against API abuse (user/session-based)
    $config['rate_limiting'] = [
        'enabled' => true,
        'limits' => ['requests' => 10, 'window' => 60], // 10 AI calls per minute
    ];
});

// routes/web.php
use Illuminate\Http\Request;
use Rumenx\PhpChatbot\PhpChatbot;
use Rumenx\PhpChatbot\Models\ModelFactory;
use Illuminate\Support\Facades\Log;

Route::post('/php-chatbot/message', function (Request $request) {
    $config = config('phpchatbot');
    $model = ModelFactory::make($config);
    $chatbot = new PhpChatbot($model, $config);
    $context = [
        'prompt' => $config['prompt'],
        'logger' => Log::getFacadeRoot(), // Optional PSR-3 logger
    ];
    $reply = $chatbot->ask($request->input('message'), $context);
    return response()->json(['reply' => $reply]);
});

// public/php-chatbot-message.php

use Rumenx\PhpChatbot\Models\ModelFactory;
$config = t = json_decode(file_get_contents('php://input'), true)['message'] ?? '';
$reply = $chatbot->ask($input);
header('Content-Type: application/json');
echo json_encode(['reply' => $reply]);

     $configPath = getenv('PHPCHATBOT_CONFIG_PATH') ?: __DIR__ . '/../vendor/rumenx/php-chatbot/src/Config/phpchatbot.php';
     $config = 

$configPath = getenv('PHPCHATBOT_CONFIG_PATH') ?: __DIR__ . '/../vendor/rumenx/php-chatbot/src/Config/phpchatbot.php';
$config = 

'message_filtering' => [
    'instructions' => [
        'Avoid sharing external links.',
        'Refrain from quoting controversial sources.',
        'Use appropriate language.',
        'Reject harmful or dangerous requests.',
        'De-escalate potential conflicts and calm aggressive or rude users.',
    ],
    'profanities' => ['badword1', 'badword2'],
    'aggression_patterns' => ['hate', 'kill', 'stupid', 'idiot'],
    'link_pattern' => '/https?:\/\/[\w\.-]+/i',
],

use Rumenx\PhpChatbot\Middleware\ChatMessageFilterMiddleware;

$config = essageFilterMiddleware(
    $filterCfg['instructions'] ?? [],
    $filterCfg['profanities'] ?? [],
    $filterCfg['aggression_patterns'] ?? [],
    $filterCfg['link_pattern'] ?? ''
);

// Before sending to the AI model:
$filtered = $middleware->handle($userMessage, $context);
$reply = $chatbot->ask($filtered['message'], $filtered['context']);
bash
composer 
json
{ "reply": "Hi! How can I help you?" }
sh
    php artisan vendor:publish --provider="Rumenx\PhpChatbot\Adapters\Laravel\PhpChatbotServiceProvider" --tag=views
    
sh
  php artisan vendor:publish --provider="Rumenx\PhpChatbot\Adapters\Laravel\PhpChatbotServiceProvider"