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.";
}
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";
}
}
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
$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]);
});