PHP code example of creativecrafts / laravel-ai-assistant
1. Go to this page and download the library: Download creativecrafts/laravel-ai-assistant 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/ */
creativecrafts / laravel-ai-assistant example snippets
// Add to your .env file
AI_BACKGROUND_JOBS_ENABLED=false // Set to true if you want to enable
AI_QUEUE_NAME=ai-assistant
use CreativeCrafts\LaravelAiAssistant\Facades\Ai;
// Simple chat interaction
$response = Ai::chat('Explain Laravel in one sentence')->send();
echo $response->getContent();
// Or use the fluent builder
$response = Ai::assistant()
->usingModel('gpt-4o')
->withTemperature(0.7)
->sendChatMessage('Write a haiku about coding');
use CreativeCrafts\LaravelAiAssistant\Facades\Ai;
$response = Ai::chat('Summarize SOLID in 2 lines')
->setResponseFormatText()
->send();
echo $response->content; // normalized text content when available
foreach (Ai::chat('Stream a limerick about Laravel')->streamText(fn($t) => print($t)) as $chunk) {
// $chunk is a string delta
}
use CreativeCrafts\LaravelAiAssistant\Assistant;
$assistant = app(Assistant::class)
->setUserMessage('Compare Laravel and Symfony briefly');
$result = $assistant->sendChatMessageDto();
use CreativeCrafts\LaravelAiAssistant\AiAssistant;
$assistant = AiAssistant::init();
$response = AiAssistant::init()
->setModelName('gpt-4')
->adjustTemperature(0.7)
->setDeveloperMessage('Please maintain a friendly tone.')
->setUserMessage('What is the weather like today?')
->sendChatMessage();
$transcription = AiAssistant::init()
->setFilePath('/path/to/audio.mp3')
->transcribeTo('en', 'Transcribe the following audio:');
$assistant = AiAssistant::init()
->setModelName('gpt-4')
->adjustTemperature(0.5)
->setAssistantName('My Assistant')
->setAssistantDescription('An assistant for handling tasks')
->setInstructions('Be as helpful as possible.')
->includeFunctionCallTool(
'calculateSum',
'Calculates the sum of two numbers',
['num1' => 'number', 'num2' => 'number'],
isStrict: true,
use CreativeCrafts\LaravelAiAssistant\Services\StreamingService;
$streamingService = app(StreamingService::class);
// Process a stream with automatic buffering
foreach ($streamingService->processStream($apiStream, 'chat_completion') as $chunk) {
echo $chunk['content'];
// Real-time processing of each chunk
}
// Configure streaming with custom buffer size and chunk processing
$streamingService = app(StreamingService::class);
$customProcessor = function($chunk) {
// Custom processing logic
return strtoupper($chunk['content']);
};
foreach ($streamingService->processStream($stream, 'text_completion', $customProcessor) as $chunk) {
// Process transformed chunks
broadcast(new StreamChunkEvent($chunk));
}
$metrics = $streamingService->getStreamingMetrics();
// Returns: active_streams, total_streams_processed, average_stream_size_mb, total_data_processed_mb, streaming_errors
$capabilities = $streamingService->validateStreamingCapabilities();
// Returns system capabilities and limits
// System health is recorded automatically
$health = $metricsService->getSystemHealthSummary(1);
/*
Returns:
[
'status' => 'healthy', // healthy, warning, critical
'uptime_seconds' => 86400,
'memory_usage_mb' => 512,
'cpu_usage_percent' => 15.3,
'disk_usage_percent' => 68.2,
'active_connections' => 25,
'error_rate_percent' => 0.5
]
*/
use CreativeCrafts\LaravelAiAssistant\Services\SecurityService;
$securityService = app(SecurityService::class);
// Validate API key format and structure
if ($securityService->validateApiKey($apiKey)) {
echo "API key is valid";
}
// Validate organization ID
if ($securityService->validateOrganizationId($orgId)) {
echo "Organization ID is valid";
}
// Check rate limit before making API call
$identifier = "user_" . auth()->id();
$canProceed = $securityService->checkRateLimit($identifier, 100, 3600); // 100 requests per hour
if ($canProceed) {
// Apply rate limiting to operation
$result = $securityService->applyRateLimit($identifier, function() {
return AiAssistant::init()->sendChatMessage();
}, 100, 3600);
} else {
throw new RateLimitExceededException("Rate limit exceeded");
}
// Enable streaming for real-time chat interfaces
$streamingService = app(StreamingService::class);
foreach ($streamingService->processStream($stream, 'chat_completion') as $chunk) {
broadcast(new MessageChunkEvent($chunk));
}
// Queue operations that take more than 30 seconds
$jobService = app(BackgroundJobService::class);
$jobId = $jobService->queueLongRunningOperation('bulk_processing', $data);
$securityService = app(SecurityService::class);
if (!$securityService->validateApiKey($apiKey)) {
throw new InvalidApiKeyException('Invalid API key format');
}
use CreativeCrafts\LaravelAiAssistant\AiAssistant;
$assistant = AiAssistant::init()
->startConversation()
->includeFunctionCallTool(
'getWeather',
'Gets current weather for a city',
[
'type' => 'object',
'properties' => [ 'city' => ['type' => 'string'] ],
''] ?? [];
if ($toolCalls !== []) {
$call = $toolCalls[0];
// Execute your domain logic (this can also be in a Job handler for full control)
$weather = [ 'temp_c' => 21, 'condition' => 'Cloudy' ];
$followUp = AiAssistant::init()
->useConversation($result['conversationId'])
->continueWithToolResults([
[
'tool_call_id' => $call['id'],
'output' => json_encode($weather),
],
]);
}
use CreativeCrafts\LaravelAiAssistant\AiAssistant;
$result = AiAssistant::init()
->startConversation()
->swer using the attached policy file and related knowledge base.')
->sendChatMessage();
$result = AiAssistant::init()
->startConversation()
->useFileSearch(false)
->attachFilesToTurn(['file_abc123'])
->setUserMessage('Do not use RAG; answer generally.')
->sendChatMessage();
use CreativeCrafts\LaravelAiAssistant\AiAssistant;
use CreativeCrafts\LaravelAiAssistant\Services\StreamingService;
class ChatController extends Controller
{
public function streamChat(Request $request)
{
$streamingService = app(StreamingService::class);
// Validate and rate limit
$securityService = app(SecurityService::class);
$userId = auth()->id();
if (!$securityService->checkRateLimit("chat_user_{$userId}", 50, 3600)) {
return response()->json(['error' => 'Rate limit exceeded'], 429);
}
// Create streaming response
return response()->stream(function() use ($request, $streamingService) {
$assistant = AiAssistant::init()
->setModelName('gpt-4')
->adjustTemperature(0.7)
->setUserMessage($request->input('message'));
$stream = $assistant->getStreamingResponse();
foreach ($streamingService->processStream($stream, 'chat_completion') as $chunk) {
echo "data: " . json_encode(['content' => $chunk['content']]) . "\n\n";
ob_flush();
flush();
}
}, 200, [
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'no-cache',
]);
}
}
use CreativeCrafts\LaravelAiAssistant\Services\BackgroundJobService;
class DocumentProcessor
{
public function processBulkDocuments(array $documents)
{
$jobService = app(BackgroundJobService::class);
// Queue batch processing
$jobIds = $jobService->queueBatchOperation('process_document',
array_map(fn($doc) => ['path' => $doc['path'], 'format' => $doc['format']], $documents),
5, // Process 5 at a time
[
'queue' => 'document-processing',
'timeout' => 600,
'max_tries' => 3
]
);
return [
'message' => 'Documents queued for processing',
'job_ids' => $jobIds,
'total_documents' => count($documents)
];
}
public function getProcessingStatus(array $jobIds)
{
$jobService = app(BackgroundJobService::class);
$statuses = [];
foreach ($jobIds as $jobId) {
$statuses[$jobId] = $jobService->getJobStatus($jobId);
}
$completed = collect($statuses)->where('status', 'completed')->count();
$total = count($statuses);
return [
'overall_progress' => ($completed / $total) * 100,
'job_statuses' => $statuses,
'queue_stats' => $jobService->getQueueStatistics()
];
}
}
use CreativeCrafts\LaravelAiAssistant\AiAssistant;
class AdvancedAiService
{
public function createSmartAssistant()
{
return AiAssistant::init()
->setModelName('gpt-4')
->adjustTemperature(0.3)
->setAssistantName('Smart Business Assistant')
->setAssistantDescription('An AI assistant specialized in business operations')
->setInstructions('You are a business expert. Provide clear, actionable advice.')
// Add code interpreter for data analysis
->includeCodeInterpreterTool(['file_12345'])
// Add file search for document retrieval
->includeFileSearchTool(['vector_store_789'])
// Add custom business calculation functions
->includeFunctionCallTool(
'calculate_roi',
'Calculate return on investment',
[
'initial_investment' => 'number',
'final_value' => 'number',
'time_period_years' => 'number'
],
isStrict: true,
// In your test
config(['ai-assistant.api_key' => 'test_key_123']);
config(['ai-assistant.mock_responses' => true]);
use CreativeCrafts\LaravelAiAssistant\AiAssistant;
$assistant = AiAssistant::init()
->startConversation(['tenant_id' => 'acme-1'])
->instructions('You are a helpful assistant. Keep answers concise.')
->setModelName('gpt-4o')
->setUserMessage('What are three benefits of unit testing?');
$result = $assistant->sendChatMessage();
// Result fields
$responseId = $result['responseId'];
$conversationId = $result['conversationId'];
$text = $result['messages'];
$assistant = AiAssistant::init()
->useConversation($conversationId)
->setUserMessage('Give me a short code example in PHP.');
$next = $assistant->sendChatMessage();
$assistant = AiAssistant::init()
->startConversation()
->instructions('You are a senior PHP engineer. Always explain the why.');
use CreativeCrafts\LaravelAiAssistant\Facades\Ai;
// Simple, typed chat turn
$response = Ai::chat('Help me compare X and Y')
->instructions('You are a product assistant')
->setResponseFormatJsonSchema([
'type' => 'object',
'properties' => [ 'verdict' => ['type' => 'string'] ],
])
->send(); // returns ChatResponseDto
$text = $response->content; // normalized content when available
$raw = $response->toArray(); // raw normalized envelope array if needed
// Streaming (typed events via ChatSession::stream or text chunks via streamText)
foreach (Ai::chat('stream me')->stream() as $event) {
// $event is StreamingEventDto
}