PHP code example of developer-unijaya / laravel-ai-chatbox

1. Go to this page and download the library: Download developer-unijaya/laravel-ai-chatbox 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/ */

    

developer-unijaya / laravel-ai-chatbox example snippets


// config/ai-chatbox.php
'providers' => [
    'ollama'   => [
        'api_url'             => env('OLLAMA_URL',               'http://localhost:11434/v1/chat/completions'),
        'api_token'           => env('OLLAMA_TOKEN',             'your-ollama-token'),
        'api_model'           => env('OLLAMA_MODEL',             'gpt-oss:120b'),
        'rag_embedding_url'   => env('OLLAMA_EMBEDDING_URL',     'http://localhost:11434/v1/embeddings'),
        'rag_embedding_model' => env('OLLAMA_EMBEDDING_MODEL',   'nomic-embed-text'),
    ],
    'openai'   => [
        'api_url'             => env('OPENAI_URL',               ''),
        'api_token'           => env('OPENAI_API_KEY',           ''),
        'api_model'           => env('OPENAI_MODEL',             ''),
        'rag_embedding_url'   => env('OPENAI_EMBEDDING_URL',     ''),
        'rag_embedding_model' => env('OPENAI_EMBEDDING_MODEL',   ''),
    ],
    'lmstudio' => [
        'api_url'             => env('LMSTUDIO_URL',             'http://127.0.0.1:1234/v1/chat/completions'),
        'api_token'           => env('LMSTUDIO_TOKEN',           'lmstudio'),
        'api_model'           => env('LMSTUDIO_MODEL',           'phi-3.5-mini-instruct'),
        'rag_embedding_url'   => env('LMSTUDIO_EMBEDDING_URL',   'http://127.0.0.1:1234/v1/embeddings'),
        'rag_embedding_model' => env('LMSTUDIO_EMBEDDING_MODEL', 'text-embedding-nomic-embed-text-v1.5'),
    ],
    'anthropic' => [
        'engine'              => 'anthropic',                    // explicit engine selection
        'api_url'             => env('ANTH_URL',                 'https://api.anthropic.com/v1/messages'),
        'api_token'           => env('ANTH_API_KEY',             ''),
        'api_model'           => env('ANTH_MODEL',               'claude-sonnet-4-6'),
        'anthropic_version'   => env('ANTH_VERSION',             '2023-06-01'),
        'rag_embedding_url'   => env('ANTH_EMBEDDING_URL',       ''),
        'rag_embedding_model' => env('ANTH_EMBEDDING_MODEL',     ''),
        'rag_embedding_token' => env('ANTH_EMBEDDING_TOKEN',     ''), // separate token for the embedding service
    ],
],

'providers' => [
    'groq' => [
        'api_url'   => env('GROQ_URL',     'https://api.groq.com/openai/v1/chat/completions'),
        'api_token' => env('GROQ_API_KEY', ''),
        'api_model' => env('GROQ_MODEL',   ''),
    ],
    // ... other providers
],

'providers' => [
    'openrouter' => [
        'api_url'   => env('OPENROUTER_URL',     'https://openrouter.ai/api/v1/chat/completions'),
        'api_token' => env('OPENROUTER_API_KEY',  ''),
        'api_model' => env('OPENROUTER_MODEL',    'mistralai/mistral-7b-instruct'),
    ],
    // ... other providers
],

// config/ai-chatbox.php
'frontend' => 'vue',      // Vue 3 widget (default)
'frontend' => 'blade',    // Vanilla JS, no framework
'frontend' => 'livewire', // Alpine.js via Livewire
'frontend' => 'none',     // API + config only

use DeveloperUnijaya\AiChatbox\AI;

// Use the active provider (resolves to AI_CHATBOX_ACTIVE_PROVIDER)
$reply = AI::chat('Summarise this document: ...');

// Use a specific named provider
$reply = AI::provider('openai')->chat('Translate to French: ...');
$reply = AI::provider('lmstudio')->chat('Write a test for this function...');
$reply = AI::provider('ollama')->chat('What is the capital of France?');

$reply = AI::provider('openai')
    ->withModel('gpt-4o-mini')
    ->withTemperature(0.2)
    ->withSystemPrompt('You are a JSON-only responder. Return only valid JSON.')
    ->withMaxTokens(512)
    ->withTimeout(60)
    ->chat($prompt);

// Pass a callback — tokens are emitted synchronously
AI::provider('openai')->stream($prompt, [], function (string $token) {
    echo $token;
    ob_flush(); flush();
});

// Or receive a Closure to invoke later
$reader = AI::provider('default')->stream($prompt);
$reader(fn(string $token) => print($token));

$history = [
    ['role' => 'user',      'content' => 'Previous question'],
    ['role' => 'assistant', 'content' => 'Previous answer'],
];

$reply = AI::provider('default')->chat('Follow-up question', $history);

use Illuminate\Support\Facades\Schedule;

Schedule::command('ai-chatbox:prune-conversations')->daily();

protected function schedule(Schedule $schedule): void
{
    $schedule->command('ai-chatbox:prune-conversations')->daily();
}

// config/ai-chatbox.php
'context_token_limit' => 4000,   // phi3:mini, llama3 8B (default)
'context_token_limit' => 8000,   // llama3 70B, Mixtral
'context_token_limit' => 32000,  // GPT-4o, Claude
'context_token_limit' => 0,      // disabled — rely on history_limit only

// config/ai-chatbox.php
'max_tokens' => 300,   // default — short replies
'max_tokens' => 512,   // medium replies
'max_tokens' => 2048,  // longer replies
'max_tokens' => null,  // let the model decide (not supported by Anthropic)

// config/ai-chatbox.php
'temperature' => 0.2,  // focused, deterministic
'temperature' => 0.5,  // balanced (default)
'temperature' => 1.0,  // creative, unpredictable

// config/ai-chatbox.php — default
'rag_no_context_prompt' => "No relevant knowledge-base entries were found for this question. "
    . "If the user is asking for information or a factual answer, do not answer from general knowledge — "
    . "reply exactly: \"I don't have that information in my knowledge base.\" "
    . "You may still respond naturally to greetings, thanks, and small talk.",

// config/ai-chatbox.php

// Restrict document management to admins only
'rag_admin_middleware' => ['web', 'auth', 'role:admin'],

// Allow all authenticated users to view the dashboard (read-only diagnostics)
'admin_middleware' => ['web', 'auth'],

'rag_admin_middleware' => ['web', 'auth', 'role:admin'],          // Spatie roles
'rag_admin_middleware' => ['web', 'auth', 'can:manage-chatbox'],  // Laravel Gates
'admin_middleware'     => ['web', 'auth:sanctum'],                // Sanctum

'allowed_origins' => [
    env('APP_URL', 'http://localhost'),
    'https://other-allowed-origin.example.com',
],

// config/ai-chatbox.php
'middleware' => ['web', 'throttle:20,1', 'ai-chatbox.cors', 'auth'],
// or with Sanctum:
'middleware' => ['web', 'throttle:20,1', 'ai-chatbox.cors', 'auth:sanctum'],

// config/ai-chatbox.php
'color_scheme' => 'auto',  // OS preference (default)
'color_scheme' => 'light',
'color_scheme' => 'dark',

use DeveloperUnijaya\AiChatbox\Engine\Contracts\AiEngineInterface;
use DeveloperUnijaya\AiChatbox\Engine\Exceptions\AiEngineException;

class AnthropicEngine implements AiEngineInterface
{
    public function validateConfig(array $options): void
    {
        if (empty($options['api_token'])) {
            throw new AiEngineException('E03', 'API token missing', 500);
        }
    }

    public function complete(array $messages, array $options = []): string
    {
        // Call Anthropic Messages API, return the reply as a plain string
    }

    public function stream(array $messages, array $options, callable $onToken): string
    {
        // Call $onToken('word') per token, return the full assembled reply
    }

    public function beginStream(array $messages, array $options): \Closure
    {
        // Open the HTTP connection before response()->stream() starts
        // Return a closure: fn(callable $onToken): string
        $this->validateConfig($options);
        return function (callable $onToken): string {
            // read stream, call $onToken per token, return full reply
        };
    }
}

use DeveloperUnijaya\AiChatbox\Engine\Contracts\AiEngineInterface;

$this->app->bind(AiEngineInterface::class, AnthropicEngine::class);

use DeveloperUnijaya\AiChatbox\Memory\Contracts\ConversationRepositoryInterface;

class RedisConversationRepository implements ConversationRepositoryInterface
{
    public function getHistory(string $threadId): array
    {
        return json_decode(Redis::get("chat:{$threadId}") ?? '[]', true);
    }

    public function saveHistory(string $threadId, array $history): void
    {
        Redis::set("chat:{$threadId}", json_encode($history));
    }

    public function trimToLimit(string $threadId, int $maxPairs): void
    {
        $history = $this->getHistory($threadId);
        $this->saveHistory($threadId, array_slice($history, -($maxPairs * 2)));
    }

    public function clear(string $threadId): void
    {
        Redis::del("chat:{$threadId}");
    }
}

use DeveloperUnijaya\AiChatbox\Memory\Contracts\ConversationRepositoryInterface;

$this->app->bind(ConversationRepositoryInterface::class, RedisConversationRepository::class);
bash
php artisan vendor:publish --tag=ai-chatbox-assets
bash
php artisan vendor:publish --tag=ai-chatbox-config
bash
php artisan vendor:publish --tag=ai-chatbox-migrations &&   
php artisan migrate
bash
php artisan vendor:publish --tag=ai-chatbox-config
bash
php artisan migrate

Nginx   proxy_buffering off;  (the package sets X-Accel-Buffering: no automatically)
PHP     output_buffering = Off  in php.ini
bash
php artisan migrate
bash
   php artisan ai-chatbox:graphify
   
bash
php artisan vendor:publish --tag=ai-chatbox-views