Repository navigation
API Reference
Complete API documentation for all classes, methods, and interfaces.
Complete API documentation for all classes, methods, and interfaces.
The main chatbot class that provides the primary interface for sending messages and managing conversations.
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,
]);public function sendMessage(string $message, array $conversation = []): arraySends 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."public function setModel(string $model): selfChanges the AI model provider.
Parameters:
-
$model(string): Model provider name
Returns: Self for method chaining
Example:
$chatbot->setModel('anthropic')
->sendMessage('Hello');public function getConfig(): arrayReturns the current configuration.
Returns: Array containing all configuration options
public function getModel(): AiModelInterfaceReturns the current AI model instance.
Returns: Instance of the current AI model
Factory class for creating AI model instances.
public static function create(string $model, array $config = []): AiModelInterfaceCreates 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',
]);public static function getSupportedModels(): arrayReturns list of supported AI model providers.
Returns: Array of supported model names
Example:
$models = ModelFactory::getSupportedModels();
// ['openai', 'anthropic', 'google', 'ollama', 'xai', 'deepseek', 'meta']Interface that all AI model classes must implement.
public function sendMessage(string $message, array $conversation = []): arraySends a message to the AI provider.
Parameters:
-
$message(string): User message -
$conversation(array): Conversation history
Returns: Array with response data
public function getConfig(): arrayReturns model configuration.
public function validateConfig(): boolValidates the model configuration.
Returns: True if configuration is valid
Throws:
-
InvalidArgumentException: When configuration is invalid
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): selfSets the system message for OpenAI models.
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,
]);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,
]);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,
]);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,
]);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,
]);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,
]);public static function createMultiple(array $configs): arrayCreates 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',
],
]);public static function validateModel(string $model): boolValidates if a model provider is supported.
Parameters:
-
$model(string): Model name to validate
Returns: True if model is supported
Middleware for filtering and processing chat messages.
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)
-
public function handle(string $message, \Closure $next): mixedProcesses 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
});public function addBlockedWord(string $word): selfAdds a word to the blocked words list.
public function removeBlockedWord(string $word): selfRemoves a word from the blocked words list.
public function getBlockedWords(): arrayReturns the list of blocked words.
Laravel framework integration adapter.
use RumenX\PhpChatbot\Laravel\PhpChatbotServiceProvider;Automatically registers the service provider.
use RumenX\PhpChatbot\Laravel\Facades\PhpChatbot;
// Usage
$response = PhpChatbot::sendMessage('Hello');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),
],
],
];# Test chatbot configuration
php artisan chatbot:test
# Clear chatbot cache
php artisan chatbot:clear-cache
# List available models
php artisan chatbot:modelsSymfony framework integration adapter.
# config/services.yaml
services:
RumenX\PhpChatbot\PhpChatbot:
arguments:
$config:
model: '%env(CHATBOT_MODEL)%'
api_key: '%env(CHATBOT_API_KEY)%'
temperature: 0.7# 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: 150use RumenX\PhpChatbot\Symfony\PhpChatbotBundle;
// In bundles.php
return [
// ...
RumenX\PhpChatbot\Symfony\PhpChatbotBundle::class => ['all' => true],
];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,
],
];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-chatclass ChatbotException extends \ExceptionBase exception class for all chatbot-related errors.
class ApiException extends ChatbotExceptionThrown when API requests fail.
Properties:
-
$statusCode(int): HTTP status code -
$responseBody(string): API response body
Methods:
public function getStatusCode(): int
public function getResponseBody(): stringclass RateLimitException extends ApiExceptionThrown when rate limits are exceeded.
Properties:
-
$retryAfter(int): Seconds to wait before retry
Methods:
public function getRetryAfter(): intclass ValidationException extends ChatbotExceptionThrown when input validation fails.
class ConfigurationException extends ChatbotExceptionThrown when configuration is invalid.
class ModelNotFoundException extends ChatbotExceptionThrown when requested model is not found.
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 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