Skip to content

API Reference

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

API Reference

Complete API documentation for all classes, methods, and interfaces.

Table of Contents

API Reference

Complete API documentation for all classes, methods, and interfaces.

Table of Contents

Core Classes

PhpChatbot

The main chatbot class that provides the primary interface for sending messages and managing conversations.

Constructor

public function __construct(array $config = [])

Parameters:

  • $config (array): Configuration array with the following options:
    • model (string): AI model provider ('openai', 'anthropic', 'google', etc.)
    • api_key (string): API key for the chosen provider
    • temperature (float): Controls randomness (0.0 - 1.0, default: 0.7)
    • max_tokens (int): Maximum tokens in response (default: 150)
    • timeout (int): Request timeout in seconds (default: 30)
    • model_name (string): Specific model name (optional)

Example:

use RumenX\PhpChatbot\PhpChatbot;

$chatbot = new PhpChatbot([
    'model' => 'openai',
    'api_key' => 'sk-your-openai-key',
    'temperature' => 0.7,
    'max_tokens' => 150,
    'timeout' => 30,
]);

sendMessage()

public function sendMessage(string $message, array $conversation = []): array

Sends a message to the AI model and returns the response.

Parameters:

  • $message (string): The user's message to send
  • $conversation (array): Previous conversation history (optional)

Returns: Array with the following structure:

[
    'reply' => 'The AI response text',
    'conversation_id' => 'unique-conversation-id',
    'model' => 'model-name-used',
    'tokens' => 42, // Token count (if available)
    'cached' => false, // Whether response was cached
]

Throws:

  • InvalidArgumentException: When message is empty or invalid
  • ApiException: When API request fails
  • RateLimitException: When rate limits are exceeded

Example:

$response = $chatbot->sendMessage('Hello, how are you?');
echo $response['reply']; // "Hello! I'm doing well, thank you for asking..."

// With conversation history
$conversation = [
    ['role' => 'user', 'content' => 'My name is John'],
    ['role' => 'assistant', 'content' => 'Nice to meet you, John!'],
];

$response = $chatbot->sendMessage('What is my name?', $conversation);
echo $response['reply']; // "Your name is John."

setModel()

public function setModel(string $model): self

Changes the AI model provider.

Parameters:

  • $model (string): Model provider name

Returns: Self for method chaining

Example:

$chatbot->setModel('anthropic')
    ->sendMessage('Hello');

getConfig()

public function getConfig(): array

Returns the current configuration.

Returns: Array containing all configuration options

getModel()

public function getModel(): AiModelInterface

Returns the current AI model instance.

Returns: Instance of the current AI model

ModelFactory

Factory class for creating AI model instances.

create()

public static function create(string $model, array $config = []): AiModelInterface

Creates an AI model instance.

Parameters:

  • $model (string): Model provider name
  • $config (array): Configuration options

Returns: AI model instance implementing AiModelInterface

Throws:

  • InvalidArgumentException: When model is not supported

Example:

use RumenX\PhpChatbot\Models\ModelFactory;

$openAiModel = ModelFactory::create('openai', [
    'api_key' => 'sk-your-key',
    'model_name' => 'gpt-4',
]);

$anthropicModel = ModelFactory::create('anthropic', [
    'api_key' => 'your-anthropic-key',
    'model_name' => 'claude-3-sonnet-20240229',
]);

getSupportedModels()

public static function getSupportedModels(): array

Returns list of supported AI model providers.

Returns: Array of supported model names

Example:

$models = ModelFactory::getSupportedModels();
// ['openai', 'anthropic', 'google', 'ollama', 'xai', 'deepseek', 'meta']

Model Interfaces

AiModelInterface

Interface that all AI model classes must implement.

sendMessage()

public function sendMessage(string $message, array $conversation = []): array

Sends a message to the AI provider.

Parameters:

  • $message (string): User message
  • $conversation (array): Conversation history

Returns: Array with response data

getConfig()

public function getConfig(): array

Returns model configuration.

validateConfig()

public function validateConfig(): bool

Validates the model configuration.

Returns: True if configuration is valid

Throws:

  • InvalidArgumentException: When configuration is invalid

Model Implementation Classes

OpenAiModel

OpenAI GPT model implementation.

use RumenX\PhpChatbot\Models\OpenAiModel;

$model = new OpenAiModel([
    'api_key' => 'sk-your-openai-key',
    'model_name' => 'gpt-4',          // or 'gpt-3.5-turbo', 'gpt-4-turbo'
    'temperature' => 0.7,
    'max_tokens' => 150,
    'top_p' => 1.0,
    'frequency_penalty' => 0.0,
    'presence_penalty' => 0.0,
]);

Specific Methods:

public function setSystemMessage(string $systemMessage): self

Sets the system message for OpenAI models.

AnthropicModel

Anthropic Claude model implementation.

use RumenX\PhpChatbot\Models\AnthropicModel;

$model = new AnthropicModel([
    'api_key' => 'your-anthropic-key',
    'model_name' => 'claude-3-sonnet-20240229', // or 'claude-3-opus-20240229', 'claude-3-haiku-20240307'
    'temperature' => 0.7,
    'max_tokens' => 150,
    'top_p' => 1.0,
]);

GeminiModel

Google Gemini model implementation.

use RumenX\PhpChatbot\Models\GeminiModel;

$model = new GeminiModel([
    'api_key' => 'your-google-api-key',
    'model_name' => 'gemini-pro',      // or 'gemini-pro-vision'
    'temperature' => 0.7,
    'max_tokens' => 150,
]);

OllamaModel

Ollama local model implementation.

use RumenX\PhpChatbot\Models\OllamaModel;

$model = new OllamaModel([
    'base_url' => 'http://localhost:11434',
    'model_name' => 'llama2',          // or any installed Ollama model
    'temperature' => 0.7,
    'timeout' => 60,
]);

XaiModel

xAI Grok model implementation.

use RumenX\PhpChatbot\Models\XaiModel;

$model = new XaiModel([
    'api_key' => 'your-xai-api-key',
    'model_name' => 'grok-beta',
    'temperature' => 0.7,
    'max_tokens' => 150,
]);

DeepSeekAiModel

DeepSeek AI model implementation.

use RumenX\PhpChatbot\Models\DeepSeekAiModel;

$model = new DeepSeekAiModel([
    'api_key' => 'your-deepseek-key',
    'model_name' => 'deepseek-chat',
    'temperature' => 0.7,
    'max_tokens' => 150,
]);

MetaModel

Meta LLaMA model implementation (via API).

use RumenX\PhpChatbot\Models\MetaModel;

$model = new MetaModel([
    'api_key' => 'your-meta-api-key',
    'model_name' => 'llama-2-70b-chat',
    'temperature' => 0.7,
    'max_tokens' => 150,
]);

Factory Classes

ModelFactory (Extended)

createMultiple()

public static function createMultiple(array $configs): array

Creates multiple model instances.

Parameters:

  • $configs (array): Array of model configurations keyed by model name

Returns: Array of model instances

Example:

$models = ModelFactory::createMultiple([
    'openai' => [
        'api_key' => 'sk-openai-key',
        'model_name' => 'gpt-4',
    ],
    'anthropic' => [
        'api_key' => 'anthropic-key',
        'model_name' => 'claude-3-sonnet-20240229',
    ],
]);

validateModel()

public static function validateModel(string $model): bool

Validates if a model provider is supported.

Parameters:

  • $model (string): Model name to validate

Returns: True if model is supported

Middleware

ChatMessageFilterMiddleware

Middleware for filtering and processing chat messages.

Constructor

public function __construct(array $options = [])

Parameters:

  • $options (array): Filter configuration options
    • max_length (int): Maximum message length (default: 2000)
    • blocked_words (array): List of blocked words
    • allow_html (bool): Whether to allow HTML (default: false)
    • profanity_filter (bool): Enable profanity filtering (default: true)

handle()

public function handle(string $message, \Closure $next): mixed

Processes a message through the filter.

Parameters:

  • $message (string): Message to filter
  • $next (Closure): Next middleware in chain

Returns: Filtered message or exception

Example:

use RumenX\PhpChatbot\Middleware\ChatMessageFilterMiddleware;

$filter = new ChatMessageFilterMiddleware([
    'max_length' => 1000,
    'blocked_words' => ['spam', 'inappropriate'],
    'allow_html' => false,
]);

$filteredMessage = $filter->handle($message, function($msg) {
    return $msg; // Continue processing
});

addBlockedWord()

public function addBlockedWord(string $word): self

Adds a word to the blocked words list.

removeBlockedWord()

public function removeBlockedWord(string $word): self

Removes a word from the blocked words list.

getBlockedWords()

public function getBlockedWords(): array

Returns the list of blocked words.

Adapters

Laravel Adapter

Laravel framework integration adapter.

ServiceProvider

use RumenX\PhpChatbot\Laravel\PhpChatbotServiceProvider;

Automatically registers the service provider.

Facade

use RumenX\PhpChatbot\Laravel\Facades\PhpChatbot;

// Usage
$response = PhpChatbot::sendMessage('Hello');

Configuration

Publish the configuration file:

php artisan vendor:publish --provider="RumenX\PhpChatbot\Laravel\PhpChatbotServiceProvider"

Configuration file: config/chatbot.php

return [
    'default' => env('CHATBOT_DEFAULT_MODEL', 'openai'),
    
    'models' => [
        'openai' => [
            'api_key' => env('OPENAI_API_KEY'),
            'model_name' => env('OPENAI_MODEL', 'gpt-4'),
            'temperature' => env('OPENAI_TEMPERATURE', 0.7),
            'max_tokens' => env('OPENAI_MAX_TOKENS', 150),
        ],
        
        'anthropic' => [
            'api_key' => env('ANTHROPIC_API_KEY'),
            'model_name' => env('ANTHROPIC_MODEL', 'claude-3-sonnet-20240229'),
            'temperature' => env('ANTHROPIC_TEMPERATURE', 0.7),
            'max_tokens' => env('ANTHROPIC_MAX_TOKENS', 150),
        ],
    ],
];

Artisan Commands

# Test chatbot configuration
php artisan chatbot:test

# Clear chatbot cache
php artisan chatbot:clear-cache

# List available models
php artisan chatbot:models

Symfony Adapter

Symfony framework integration adapter.

Service Registration

# config/services.yaml
services:
    RumenX\PhpChatbot\PhpChatbot:
        arguments:
            $config:
                model: '%env(CHATBOT_MODEL)%'
                api_key: '%env(CHATBOT_API_KEY)%'
                temperature: 0.7

Configuration

# config/packages/php_chatbot.yaml
php_chatbot:
    default_model: 'openai'
    models:
        openai:
            api_key: '%env(OPENAI_API_KEY)%'
            model_name: '%env(OPENAI_MODEL)%'
            temperature: 0.7
            max_tokens: 150

Symfony Bundle (if available)

use RumenX\PhpChatbot\Symfony\PhpChatbotBundle;

// In bundles.php
return [
    // ...
    RumenX\PhpChatbot\Symfony\PhpChatbotBundle::class => ['all' => true],
];

Configuration

Global Configuration Options

All configuration options available across all model providers:

$config = [
    // Provider settings
    'model' => 'openai',                    // Provider name
    'api_key' => 'your-api-key',           // API key
    'model_name' => 'gpt-4',               // Specific model
    
    // Generation parameters
    'temperature' => 0.7,                  // 0.0-1.0, controls randomness
    'max_tokens' => 150,                   // Maximum response tokens
    'top_p' => 1.0,                        // Nucleus sampling parameter
    'frequency_penalty' => 0.0,            // -2.0 to 2.0
    'presence_penalty' => 0.0,             // -2.0 to 2.0
    
    // Request settings
    'timeout' => 30,                       // Request timeout in seconds
    'retry_attempts' => 3,                 // Number of retry attempts
    'retry_delay' => 1,                    // Delay between retries
    
    // Caching
    'cache_enabled' => true,               // Enable response caching
    'cache_ttl' => 3600,                   // Cache TTL in seconds
    
    // Logging
    'log_requests' => false,               // Log API requests
    'log_responses' => false,              // Log API responses
    
    // Security
    'rate_limit' => [
        'enabled' => true,
        'requests_per_minute' => 20,
    ],
    'content_filter' => [
        'enabled' => true,
        'max_length' => 2000,
    ],
];

Environment Variables

Standard environment variables for configuration:

# Global settings
CHATBOT_DEFAULT_MODEL=openai
CHATBOT_CACHE_ENABLED=true
CHATBOT_LOG_REQUESTS=false

# OpenAI
OPENAI_API_KEY=sk-your-openai-key
OPENAI_MODEL=gpt-4
OPENAI_TEMPERATURE=0.7
OPENAI_MAX_TOKENS=150

# Anthropic
ANTHROPIC_API_KEY=your-anthropic-key
ANTHROPIC_MODEL=claude-3-sonnet-20240229
ANTHROPIC_TEMPERATURE=0.7

# Google
GOOGLE_API_KEY=your-google-key
GOOGLE_MODEL=gemini-pro

# Local models (Ollama)
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=llama2

# xAI
XAI_API_KEY=your-xai-key
XAI_MODEL=grok-beta

# DeepSeek
DEEPSEEK_API_KEY=your-deepseek-key
DEEPSEEK_MODEL=deepseek-chat

# Meta
META_API_KEY=your-meta-key
META_MODEL=llama-2-70b-chat

Exceptions

Base Exception Classes

ChatbotException

class ChatbotException extends \Exception

Base exception class for all chatbot-related errors.

ApiException

class ApiException extends ChatbotException

Thrown when API requests fail.

Properties:

  • $statusCode (int): HTTP status code
  • $responseBody (string): API response body

Methods:

public function getStatusCode(): int
public function getResponseBody(): string

RateLimitException

class RateLimitException extends ApiException

Thrown when rate limits are exceeded.

Properties:

  • $retryAfter (int): Seconds to wait before retry

Methods:

public function getRetryAfter(): int

ValidationException

class ValidationException extends ChatbotException

Thrown when input validation fails.

ConfigurationException

class ConfigurationException extends ChatbotException

Thrown when configuration is invalid.

ModelNotFoundException

class ModelNotFoundException extends ChatbotException

Thrown when requested model is not found.

Exception Handling Examples

use RumenX\PhpChatbot\PhpChatbot;
use RumenX\PhpChatbot\Exceptions\ApiException;
use RumenX\PhpChatbot\Exceptions\RateLimitException;
use RumenX\PhpChatbot\Exceptions\ValidationException;

try {
    $chatbot = new PhpChatbot([
        'model' => 'openai',
        'api_key' => 'your-key',
    ]);
    
    $response = $chatbot->sendMessage('Hello');
    
} catch (RateLimitException $e) {
    // Handle rate limiting
    $retryAfter = $e->getRetryAfter();
    echo "Rate limited. Retry after {$retryAfter} seconds.";
    
} catch (ValidationException $e) {
    // Handle validation errors
    echo "Validation error: " . $e->getMessage();
    
} catch (ApiException $e) {
    // Handle API errors
    $statusCode = $e->getStatusCode();
    $responseBody = $e->getResponseBody();
    echo "API Error {$statusCode}: {$e->getMessage()}";
    
} catch (ChatbotException $e) {
    // Handle other chatbot errors
    echo "Chatbot error: " . $e->getMessage();
    
} catch (\Exception $e) {
    // Handle unexpected errors
    echo "Unexpected error: " . $e->getMessage();
}

Custom Exception Handling

// Custom error handler
class CustomChatbotErrorHandler
{
    public function handleException(\Throwable $e)
    {
        if ($e instanceof RateLimitException) {
            return $this->handleRateLimit($e);
        }
        
        if ($e instanceof ApiException) {
            return $this->handleApiError($e);
        }
        
        return $this->handleGenericError($e);
    }
    
    private function handleRateLimit(RateLimitException $e): array
    {
        return [
            'error' => true,
            'type' => 'rate_limit',
            'message' => 'Please slow down your requests',
            'retry_after' => $e->getRetryAfter(),
        ];
    }
    
    private function handleApiError(ApiException $e): array
    {
        return [
            'error' => true,
            'type' => 'api_error',
            'message' => 'Service temporarily unavailable',
            'status_code' => $e->getStatusCode(),
        ];
    }
    
    private function handleGenericError(\Throwable $e): array
    {
        // Log the error
        error_log("Chatbot error: " . $e->getMessage());
        
        return [
            'error' => true,
            'type' => 'internal_error',
            'message' => 'Something went wrong. Please try again.',
        ];
    }
}

This completes the comprehensive API reference documentation. For more examples and implementation details, see the Examples and Best Practices guides.


Next: Examples

Clone this wiki locally