Skip to content

Quick Start Guide

Rumen Damyanov edited this page Jul 31, 2025 · 1 revision

Quick Start Guide

Get php-chatbot up and running in minutes with this step-by-step guide.

Table of Contents

5-Minute Setup

Step 1: Install the Package

composer require rumenx/php-chatbot

Step 2: Create Basic Configuration

Create a simple configuration file (config/phpchatbot.php):

<?php
return [
    'model' => 'default', // Start with default model (no API key needed)
    'prompt' => 'You are a helpful assistant. Keep responses concise and friendly.',
    'language' => 'en',
    'temperature' => 0.7,
    'max_tokens' => 1000,
];

Step 3: Create Your First Chatbot

Create chatbot-test.php:

<?php
require_once 'vendor/autoload.php';

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

// Load configuration
$config = require 'config/phpchatbot.php';

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

// Test conversation
$response = $chatbot->ask('Hello! How can you help me?');
echo "Bot: " . $response . "\n";

Step 4: Run Your First Chat

php chatbot-test.php

Expected Output:

Bot: Hello! I'm here to help you with any questions or tasks you might have. What would you like to know?

Basic Configuration

Add AI Provider (Optional)

To use a real AI provider like OpenAI, update your configuration:

  1. Get an API key from OpenAI

  2. Add to .env file:

    OPENAI_API_KEY=sk-your-key-here
  3. Update configuration:

    <?php
    return [
        'model' => 'openai',
        'api_key' => env('OPENAI_API_KEY'),
        'model_name' => 'gpt-3.5-turbo',
        'prompt' => 'You are a helpful assistant.',
        'temperature' => 0.7,
        'max_tokens' => 1000,
    ];

Framework Integration

Laravel (2 minutes)

# Publish configuration
php artisan vendor:publish --provider="Rumenx\PhpChatbot\Adapters\Laravel\PhpChatbotServiceProvider"

# Add to routes/web.php
Route::post('/chat', function (Request $request) {
    $chatbot = app('phpchatbot');
    $response = $chatbot->ask($request->input('message'));
    return response()->json(['reply' => $response]);
});

Symfony (2 minutes)

// src/Controller/ChatController.php
use Rumenx\PhpChatbot\PhpChatbot;
use Rumenx\PhpChatbot\Models\ModelFactory;

#[Route('/chat', methods: ['POST'])]
public function chat(Request $request): JsonResponse
{
    $config = require $this->getParameter('kernel.project_dir').'/config/phpchatbot.php';
    $model = ModelFactory::make($config);
    $chatbot = new PhpChatbot($model, $config);
    
    $message = $request->getPayload()->get('message');
    $response = $chatbot->ask($message);
    
    return $this->json(['reply' => $response]);
}

First Chat

Interactive Console Chat

Create interactive-chat.php for testing:

<?php
require_once 'vendor/autoload.php';

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

$config = require 'config/phpchatbot.php';
$model = ModelFactory::make($config);
$chatbot = new PhpChatbot($model, $config);

echo "🤖 PHP Chatbot Ready! Type 'exit' to quit.\n";
echo "=====================================\n\n";

while (true) {
    echo "You: ";
    $input = trim(fgets(STDIN));
    
    if (strtolower($input) === 'exit') {
        echo "Goodbye! 👋\n";
        break;
    }
    
    if (empty($input)) {
        continue;
    }
    
    echo "Bot: ";
    try {
        $response = $chatbot->ask($input);
        echo $response . "\n\n";
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "\n\n";
    }
}

Run it:

php interactive-chat.php

Web Interface Example

Create public/chat.html:

<!DOCTYPE html>
<html>
<head>
    <title>PHP Chatbot Test</title>
    <style>
        .chat-container { max-width: 600px; margin: 50px auto; }
        .chat-box { border: 1px solid #ddd; height: 400px; overflow-y: auto; padding: 10px; }
        .message { margin: 10px 0; }
        .user-message { text-align: right; color: blue; }
        .bot-message { text-align: left; color: green; }
        .input-container { margin-top: 10px; }
        input[type="text"] { width: 80%; padding: 10px; }
        button { width: 15%; padding: 10px; }
    </style>
</head>
<body>
    <div class="chat-container">
        <h1>PHP Chatbot Test</h1>
        <div id="chatBox" class="chat-box"></div>
        <div class="input-container">
            <input type="text" id="messageInput" placeholder="Type your message...">
            <button onclick="sendMessage()">Send</button>
        </div>
    </div>

    <script>
        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message) return;
            
            addMessage('You: ' + message, 'user-message');
            input.value = '';
            
            fetch('/chat', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ message: message })
            })
            .then(response => response.json())
            .then(data => {
                addMessage('Bot: ' + data.reply, 'bot-message');
            })
            .catch(error => {
                addMessage('Error: ' + error.message, 'bot-message');
            });
        }
        
        function addMessage(text, className) {
            const chatBox = document.getElementById('chatBox');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ' + className;
            messageDiv.textContent = text;
            chatBox.appendChild(messageDiv);
            chatBox.scrollTop = chatBox.scrollHeight;
        }
        
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') sendMessage();
        });
    </script>
</body>
</html>

Create public/chat.php backend:

<?php
require_once '../vendor/autoload.php';

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

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $config = require '../config/phpchatbot.php';
    $model = ModelFactory::make($config);
    $chatbot = new PhpChatbot($model, $config);
    
    $input = json_decode(file_get_contents('php://input'), true);
    $message = $input['message'] ?? '';
    
    if (empty($message)) {
        echo json_encode(['error' => 'Message is required']);
        exit;
    }
    
    $response = $chatbot->ask($message);
    echo json_encode(['reply' => $response]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>

Next Steps

🔧 Configure AI Models

🛡️ Add Security

  • Security & Filtering - Content filtering and rate limiting
  • Set up proper API key management
  • Configure input validation

🎨 Frontend Integration

  • Frontend Integration - React, Vue, Angular components
  • Customize the chat UI
  • Add real-time features

🚀 Framework Features

  • Framework Integration - Advanced Laravel/Symfony features
  • Service container integration
  • Middleware configuration

📚 Learn More

🔍 Troubleshooting

Having issues? Check the Troubleshooting Guide for common solutions.


Congratulations! 🎉 You now have a working chatbot. Explore the other guides to add advanced features.


Next: Configuration

Clone this wiki locally