PHP code example of aitoolkit / laravel-ai-toolkit
1. Go to this page and download the library: Download aitoolkit/laravel-ai-toolkit 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/ */
aitoolkit / laravel-ai-toolkit example snippets
use AIToolkit\AIToolkit\Contracts\AIProviderContract;
// Dependency injection
public function chat(AIProviderContract $provider)
{
$response = $provider->chat('Tell me a joke about programming');
return [
'content' => $response['content'],
'usage' => $response['usage'], // Token usage stats
'model' => $response['model'],
];
}
use AIToolkit\AIToolkit\Facades\AiCache;
// Cache AI responses
$result = AiCache::remember('chat', 'openai', 'Your prompt', function () {
return app(AIProviderContract::class)->chat('Your prompt');
});
use AIToolkit\AIToolkit\Jobs\AiChatJob;
// Dispatch async job
AiChatJob::dispatch('Generate a report about AI trends', [
'max_tokens' => 2000,
'temperature' => 0.7
], 'unique-result-id');
// Listen for completion
event(new AiChatCompleted($response, 'unique-result-id'));
// Direct streaming
$stream = $provider->stream('Tell me a story about...');
return $stream; // Returns StreamedResponse
// Broadcasting via Reverb
$stream = $provider->streamBroadcast('Your prompt', [], 'my-channel');
// Frontend JavaScript
window.Echo.channel('ai-stream')
.listen('AiResponseChunk', (e) => {
if (e.chunk === '__START__') {
// Stream started
} else {if (e.chunk === '__END__') {
// Stream ended
} else {
// Append chunk to UI
document.getElementById('response').innerHTML += e.chunk;
}}
});
interface AIProviderContract
{
public function chat(string $prompt, array $options = []): array;
public function stream(string $prompt, array $options = []): \Symfony\Component\HttpFoundation\StreamedResponse;
public function embed(string $text): array;
}
// Circuit breaker automatically opens after 5 failures
// Resets after 60 seconds
namespace App\AI;
use AIToolkit\AIToolkit\Contracts\AIProviderContract;
class CustomProvider implements AIProviderContract
{
public function chat(string $prompt, array $options = []): array
{
// Your custom implementation
}
// ... implement other methods
}
$this->app->singleton(AIProviderContract::class, function () {
return new CustomProvider();
});
// Listen for AI chat completion
Event::listen(AiChatCompleted::class, function (AiChatCompleted $event) {
if ($event->failed) {
Log::error('AI chat failed', $event->broadcastWith());
} else {
Log::info('AI chat completed', $event->broadcastWith());
}
});