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


  // Old configuration
  'stream' => true,
  'buffer_size' => 8192,
  
  // New configuration
  'streaming' => [
      'enabled' => true,
      'buffer_size' => 8192,
      'chunk_size' => 1024,
      'timeout' => 120,
  ],
  

  // 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();

'api_key' => env('OPENAI_API_KEY', null),
'organization' => env('OPENAI_ORGANIZATION', null),

'model' => env('OPENAI_CHAT_MODEL', 'gpt-3.5-turbo'),
'chat_model' => env('OPENAI_CHAT_MODEL', 'gpt-3.5-turbo'),
'edit_model' => 'gpt-4o',
'audio_model' => 'whisper-1',

// Streaming configuration
'streaming' => [
    'enabled' => true,
    'buffer_size' => 1024,
    'timeout' => 30,
    'memory_limit_mb' => 256,
],

// Background jobs configuration
'background_jobs' => [
    'enabled' => true,
    'queue' => 'ai-operations',
    'timeout' => 300,
    'max_tries' => 3,
],

// Security configuration
'security' => [
    'rate_limiting' => [
        'enabled' => true,
        'max_requests' => 100,
        'time_window' => 3600,
    ],
    'api_key_validation' => true,
    'request_signing' => false,
],

// Metrics collection
'metrics' => [
    'enabled' => true,
    'track_response_times' => true,
    'track_token_usage' => true,
    'track_error_rates' => true,
],

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

use CreativeCrafts\LaravelAiAssistant\Services\BackgroundJobService;

$jobService = app(BackgroundJobService::class);

// Queue a long-running operation
$jobId = $jobService->queueLongRunningOperation('large_text_processing', [
    'text' => $largeText,
    'model' => 'gpt-4',
    'temperature' => 0.7
], [
    'queue' => 'high-priority',
    'timeout' => 600,
    'max_tries' => 5
]);

echo "Job queued with ID: $jobId";

// Process multiple items in batches
$batchJobIds = $jobService->queueBatchOperation('translate_texts', [
    ['text' => 'Hello world', 'to' => 'es'],
    ['text' => 'How are you?', 'to' => 'fr'],
    ['text' => 'Good morning', 'to' => 'de']
], 10, ['queue' => 'translations']);

// Check job status
$status = $jobService->getJobStatus($jobId);
/*
Returns:
[
    'job_id' => 'job_123',
    'operation' => 'large_text_processing',
    'status' => 'processing', // queued, processing, completed, failed, cancelled
    'progress' => 75,
    'created_at' => '2024-01-01T10:00:00Z',
    'started_at' => '2024-01-01T10:00:05Z',
    'completed_at' => null,
    'duration_seconds' => 42.1,
    'result' => null,
    'error' => null,
    'retry_count' => 1
]
*/

// Get queue statistics
$stats = $jobService->getQueueStatistics();
/*
Returns:
[
    'total_jobs' => 150,
    'queued_jobs' => 5,
    'processing_jobs' => 3,
    'completed_jobs' => 140,
    'failed_jobs' => 2,
    'cancelled_jobs' => 1,
    'average_processing_time' => 45.2,
    'success_rate_percent' => 98.6
]
*/

use CreativeCrafts\LaravelAiAssistant\Services\LazyLoadingService;

$lazyService = app(LazyLoadingService::class);

// Register a lazy-loaded resource
$lazyService->registerLazyResource('heavy_model', function() {
    return new ExpensiveAiModel();
}, [
    'ttl' => 3600,  // Cache for 1 hour
    'preload' => false,
    'category' => 'ai_models'
]);

// Get resource (loads only when first accessed)
$model = $lazyService->getResource('heavy_model');

// Register multiple AI models for lazy loading
$lazyService->registerAiModels([
    'gpt-4' => ['type' => 'chat', 'context_size' => 8192],
    'gpt-3.5-turbo' => ['type' => 'chat', 'context_size' => 4096],
    'whisper-1' => ['type' => 'audio', 'languages' => ['en', 'es', 'fr']]
]);

// Register HTTP clients with different configurations
$lazyService->registerHttpClients([
    'standard' => ['timeout' => 30, 'pool_size' => 10],
    'streaming' => ['timeout' => 300, 'stream' => true],
    'batch' => ['timeout' => 600, 'concurrent' => 5]
]);

$metrics = $lazyService->getLazyLoadingMetrics();
/*
Returns:
[
    'total_resources' => 15,
    'loaded_resources' => 8,
    'cache_hits' => 45,
    'cache_misses' => 12,
    'average_load_time' => 2.3,
    'memory_saved_mb' => 124.5,
    'cache_hit_rate' => 78.9
]
*/

use CreativeCrafts\LaravelAiAssistant\Services\MetricsCollectionService;

$metricsService = app(MetricsCollectionService::class);

// Automatic recording (handled internally)
// Manual recording for custom operations
$metricsService->recordApiCall('/chat/completions', 1.5, 200, [
    'model' => 'gpt-4',
    'tokens' => 150
]);

$metricsService->recordTokenUsage('chat_completion', 100, 50, 'gpt-4');

// Get API performance summary
$performance = $metricsService->getApiPerformanceSummary('/chat/completions', 24);
/*
Returns:
[
    'total_calls' => 1250,
    'average_response_time' => 1.8,
    'success_rate' => 99.2,
    'error_rate' => 0.8,
    'p95_response_time' => 3.2,
    'total_errors' => 10
]
*/

// Get token usage summary
$tokenUsage = $metricsService->getTokenUsageSummary(24);
/*
Returns:
[
    'total_tokens' => 125000,
    'prompt_tokens' => 75000,
    'completion_tokens' => 50000,
    'estimated_cost_usd' => 2.50,
    'by_model' => [
        'gpt-4' => ['tokens' => 50000, 'cost' => 1.00],
        'gpt-3.5-turbo' => ['tokens' => 75000, 'cost' => 0.15]
    ]
]
*/

// 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");
}

// Generate request signature
$payload = ['message' => 'Hello AI', 'model' => 'gpt-4'];
$secret = config('app.key');
$timestamp = time();

$signature = $securityService->generateRequestSignature($payload, $secret, $timestamp);

// Verify request signature
$isValid = $securityService->verifyRequestSignature(
    $payload, 
    $signature, 
    $secret, 
    $timestamp, 
    300 // 5 minute tolerance
);

// Sanitize sensitive data before logging
$sensitiveData = [
    'api_key' => 'sk-secret123',
    'user_email' => '[email protected]',
    'message' => 'Hello world',
    'organization' => 'org-secret456'
];

$sanitized = $securityService->sanitizeSensitiveData($sensitiveData, [
    'api_key', 'organization', 'password', 'secret'
]);
/*
Returns:
[
    'api_key' => '***REDACTED***',
    'user_email' => '[email protected]',
    'message' => 'Hello world',
    'organization' => '***REDACTED***'
]
*/

use CreativeCrafts\LaravelAiAssistant\Services\MemoryMonitoringService;

$memoryService = app(MemoryMonitoringService::class);

// Monitor memory usage during operations
$memoryReport = $memoryService->getMemoryReport();
/*
Returns:
[
    'current_usage_mb' => 45.2,
    'peak_usage_mb' => 67.8,
    'limit_mb' => 256,
    'usage_percent' => 17.7,
    'available_mb' => 210.8
]
*/

// Set memory alerts
$memoryService->setMemoryAlert(200, function($usage) {
    Log::warning("High memory usage detected: {$usage}MB");
});

use CreativeCrafts\LaravelAiAssistant\Services\CacheService;

$cacheService = app(CacheService::class);

// Cache API responses
$cacheKey = 'ai_response_' . md5($prompt);
$response = $cacheService->remember($cacheKey, 3600, function() use ($prompt) {
    return AiAssistant::init()->setUserMessage($prompt)->sendChatMessage();
});

// Smart caching with tags
$cacheService->tags(['ai_responses', 'user_123'])->put($cacheKey, $response, 3600);

// Clear related caches
$cacheService->tags(['user_123'])->flush();

// Use appropriate TTL based on content type
$cacheService->cacheResponse('static_content', $response, 86400); // 24 hours
$cacheService->cacheResponse('dynamic_content', $response, 300);  // 5 minutes

// Implement cache warming for frequently accessed data
$cacheService->cacheConfig('popular_prompts', $popularPrompts, 7200);

// Use hierarchical cache keys for better organization
$cacheKey = "ai_response:{$userId}:{$modelName}:" . md5($prompt);

// Process large operations in background
use CreativeCrafts\LaravelAiAssistant\Jobs\ProcessAiRequestJob;

// Dispatch AI processing to queue
ProcessAiRequestJob::dispatch($requestData)
    ->onQueue(config('ai-assistant.background_jobs.queue'))
    ->delay(now()->addSeconds(5));

// Batch processing for multiple requests
$jobs = collect($requests)->map(function ($request) {
    return new ProcessAiRequestJob($request);
});

Bus::batch($jobs)
    ->then(function (Batch $batch) {
        // All jobs completed successfully
    })
    ->catch(function (Batch $batch, Throwable $e) {
        // First batch job failure
    })
    ->finally(function (Batch $batch) {
        // Batch has finished executing
    })
    ->dispatch();

// config/queue.php
'connections' => [
    'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
        'queue' => env('REDIS_QUEUE', 'default'),
        'retry_after' => 90,
        'block_for' => null,
        'after_commit' => false,
    ],
],

// Dedicated connection for AI Assistant
'ai-assistant-redis' => [
    'driver' => 'redis',
    'connection' => 'ai-assistant',
    'queue' => 'ai-assistant',
    'retry_after' => 300,
    'block_for' => null,
],

// tests/Performance/LoadTest.php
use CreativeCrafts\LaravelAiAssistant\AiAssistant;

public function test_concurrent_requests_performance()
{
    $concurrentRequests = 50;
    $promises = [];
    
    $startTime = microtime(true);
    
    for ($i = 0; $i < $concurrentRequests; $i++) {
        $promises[] = AiAssistant::init()
            ->setUserMessage("Test message {$i}")
            ->sendChatMessage();
    }
    
    // Wait for all requests to complete
    $results = collect($promises)->map(fn($promise) => $promise);
    
    $duration = microtime(true) - $startTime;
    $avgResponseTime = $duration / $concurrentRequests;
    
    $this->assertLessThan(5.0, $avgResponseTime, 'Average response time should be under 5 seconds');
}

// Monitor performance metrics
use CreativeCrafts\LaravelAiAssistant\Services\MetricsService;

$metrics = app(MetricsService::class);
$performanceData = $metrics->getPerformanceMetrics();

/*
Returns:
[
    'avg_response_time' => 1.2,
    'total_requests' => 1500,
    'error_rate' => 0.02,
    'token_usage' => [
        'total' => 45000,
        'avg_per_request' => 30
    ],
    'cache_hit_rate' => 0.85
]
*/

use CreativeCrafts\LaravelAiAssistant\Exceptions\{
    ApiResponseValidationException,
    ConfigurationValidationException,
    CreateNewAssistantException,
    FileOperationException,
    InvalidApiKeyException,
    MaxRetryAttemptsExceededException,
    MissingRequiredParameterException,
    ThreadExecutionTimeoutException
};

try {
    $assistant = AiAssistant::init()
        ->setModelName('gpt-4')
        ->sendChatMessage();
} catch (InvalidApiKeyException $e) {
    Log::error('Invalid API key provided', ['error' => $e->getMessage()]);
    return response()->json(['error' => 'Authentication failed'], 401);
    
} catch (MaxRetryAttemptsExceededException $e) {
    Log::error('Maximum retry attempts exceeded', ['error' => $e->getMessage()]);
    return response()->json(['error' => 'Service temporarily unavailable'], 503);
    
} catch (ThreadExecutionTimeoutException $e) {
    Log::error('Thread execution timeout', ['error' => $e->getMessage()]);
    return response()->json(['error' => 'Request timeout'], 408);
    
} catch (ApiResponseValidationException $e) {
    Log::error('API response validation failed', ['error' => $e->getMessage()]);
    return response()->json(['error' => 'Invalid response from AI service'], 502);
    
} catch (FileOperationException $e) {
    Log::error('File operation failed', ['error' => $e->getMessage()]);
    return response()->json(['error' => 'File processing error'], 422);
}

try {
    // Configuration is validated automatically during service provider boot
    $config = config('ai-assistant');
} catch (ConfigurationValidationException $e) {
    // Handle configuration errors
    Log::critical('AI Assistant configuration invalid', [
        'error' => $e->getMessage(),
        'config' => $e->getConfigurationErrors()
    ]);
}

   // 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);
   

   // Register expensive resources for lazy loading
   $lazyService = app(LazyLoadingService::class);
   $lazyService->registerLazyResource('expensive_model', $initializer, ['ttl' => 3600]);
   

   $securityService = app(SecurityService::class);
   if (!$securityService->validateApiKey($apiKey)) {
       throw new InvalidApiKeyException('Invalid API key format');
   }
   

   // Implement per-user rate limiting
   $canProceed = $securityService->checkRateLimit("user_{$userId}", 100, 3600);
   

   $sanitizedData = $securityService->sanitizeSensitiveData($data, [
       'api_key', 'organization', 'password'
   ]);
   Log::info('API call made', $sanitizedData);
   

   // Configure in config/ai-assistant.php
   'metrics' => [
       'enabled' => true,
       'track_response_times' => true,
       'track_token_usage' => true,
       'track_error_rates' => true,
   ]
   

   $metricsService = app(MetricsCollectionService::class);
   $health = $metricsService->getSystemHealthSummary(1);
   
   if ($health['status'] === 'critical') {
       // Alert administrators
       Mail::to('[email protected]')->send(new SystemHealthAlert($health));
   }
   

   $tokenUsage = $metricsService->getTokenUsageSummary(24);
   if ($tokenUsage['estimated_cost_usd'] > $dailyBudget) {
       // Implement cost controls
       Log::warning('Daily AI budget exceeded', $tokenUsage);
   }
   

use CreativeCrafts\LaravelAiAssistant\Facades\Ai;

$schema = [
    '$schema' => 'https://json-schema.org/draft/2020-12/schema',
    'type' => 'object',
    'properties' => [
        'title' => ['type' => 'string'],
        'bullets' => ['type' => 'array', 'items' => ['type' => 'string']],
    ],
    'data as an array
$raw = $response->toArray();

config([
    'ai-assistant.tool_calling.executor' => 'queue',  // 'sync' | 'queue'
    'ai-assistant.background_jobs.queue' => 'ai-tools',
    'queue.default' => env('AI_QUEUE_CONNECTION', 'sync'),
]);

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\Services\Metrics;

// Get performance metrics
$metrics = app(Metrics::class);
$stats = $metrics->getStats();

echo "Average Response Time: " . $stats['avg_response_time'] . "ms\n";
echo "Total Requests: " . $stats['total_requests'] . "\n";
echo "Error Rate: " . ($stats['error_rate'] * 100) . "%\n";

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,
                

use CreativeCrafts\LaravelAiAssistant\Services\MetricsCollectionService;

class AiDashboardController extends Controller
{
    public function getDashboardData()
    {
        $metricsService = app(MetricsCollectionService::class);
        $hours = 24; // Last 24 hours
        
        return [
            'api_performance' => [
                'chat_completions' => $metricsService->getApiPerformanceSummary('/chat/completions', $hours),
                'audio_transcriptions' => $metricsService->getApiPerformanceSummary('/audio/transcriptions', $hours),
                'assistants' => $metricsService->getApiPerformanceSummary('/assistants', $hours),
            ],
            
            'token_usage' => $metricsService->getTokenUsageSummary($hours),
            'system_health' => $metricsService->getSystemHealthSummary($hours),
            
            'streaming_metrics' => app(StreamingService::class)->getStreamingMetrics(),
            'lazy_loading_metrics' => app(LazyLoadingService::class)->getLazyLoadingMetrics(),
            'job_queue_stats' => app(BackgroundJobService::class)->getQueueStatistics(),
            
            'cost_analysis' => [
                'estimated_daily_cost' => $metricsService->calculateEstimatedCost($hours),
                'cost_by_model' => $metricsService->getTokenUsageByModel($hours),
                'cost_by_operation' => $metricsService->getTokenUsageByOperation($hours),
            ]
        ];
    }
}

// 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.');

$schema = [
    '$schema' => 'https://json-schema.org/draft/2020-12/schema',
    'type' => 'object',
    'properties' => [
        'title' => ['type' => 'string'],
        'bullets' => ['type' => 'array', 'items' => ['type' => 'string']],
    ],
    'er')
    ->setUserMessage('Summarize SOLID principles as JSON.');

$result = $assistant->sendChatMessage();

$assistant = AiAssistant::init()
    ->startConversation()
    ->uploaded
    ->setUserMessage('Answer using the attached policy file.');

$result = $assistant->sendChatMessage();

$assistant = AiAssistant::init()
    ->startConversation()
    ->useFileSearch(false)
    ->attachFilesToTurn(['file_abc123'])
    ->setUserMessage('Do not use RAG; answer generally.');

$result = $assistant->sendChatMessage();

// Local file
$assistant = AiAssistant::init()
    ->startConversation()
    ->addImageFromFile(storage_path('app/public/photo.jpg'))
    ->setUserMessage('Describe this image in one sentence.');

$res1 = $assistant->sendChatMessage();

// Remote URL
$res2 = AiAssistant::init()
    ->startConversation()
    ->addImageFromUrl('https://example.com/cat.jpg')
    ->setUserMessage('What breed is this cat?')
    ->sendChatMessage();

$assistant = AiAssistant::init()
    ->startConversation()
    ->setUserMessage('Stream a limerick about Laravel.');

$onEvent = function(array $evt) {
    // evt example: ['type' => 'response.output_text.delta', 'data' => [...], 'isFinal' => false]
    if (($evt['type'] ?? '') === 'response.output_text.delta') {
        echo $evt['data']['delta'] ?? '';
    }
};

$shouldStop = function() {
    // Return true to stop early (e.g., client disconnected)
    return false;
};

foreach ($assistant->streamChatMessage($onEvent, $shouldStop) as $event) {
    if (!empty($event['isFinal'])) {
        // completed/failed
    }
}

// If you captured a response ID to cancel later:
AiAssistant::init()->cancelResponse($responseId);

$first = AiAssistant::init()
    ->startConversation()
    ->includeFunctionCallTool(
        'getWeather',
        'Gets weather by city',
        [
            'type' => 'object',
            'properties' => ['city' => ['type' => 'string']],
            '     [
            'tool_call_id' => $call['id'],
            'output' => json_encode(['temp_c' => 21, 'condition' => 'Cloudy']),
        ],
    ];

    $followUp = AiAssistant::init()
        ->useConversation($first['conversationId'])
        ->continueWithToolResults($resultPayload);
}

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
}

// Files helper mirrors AiAssistant capabilities
Ai::chat('Explain these docs')
    ->files()->attachFileReference('file_123', useFileSearch: true)
    ->tools()->

// Old
$assistant = new \CreativeCrafts\LaravelAiAssistant\AiAssistant('Help me');
$result = $assistant->sendChatMessage(); // array

// New (preferred)
use CreativeCrafts\LaravelAiAssistant\Facades\Ai;
$dto = Ai::chat('Help me')->send();      // ChatResponseDto

// Or typed via AiAssistant (incremental migration)
$assistant = new \CreativeCrafts\LaravelAiAssistant\AiAssistant('Help me');
$dto = $assistant->sendChatMessageDto(); // ChatResponseDto
bash
   php artisan vendor:publish --tag="laravel-ai-assistant-config" --force
   
bash
   php artisan vendor:publish --tag="laravel-ai-assistant-migrations" --force
   php artisan migrate
   
bash
php artisan vendor:publish --tag="laravel-ai-assistant-config"
bash
php artisan vendor:publish --tag="ai-assistant-config"
bash
php artisan vendor:publish --tag="ai-assistant-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="ai-assistant-models"
bash
composer p-autoload
bash
   php artisan config:clear
   
bash
php artisan vendor:publish --tag="laravel-ai-assistant-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="ai-assistant-models"
bash
   php artisan queue:work --queue=ai-assistant
   
bash
# Check package installation
composer show creativecrafts/laravel-ai-assistant

# Verify configuration
php artisan config:show ai-assistant

# Test API connectivity
php artisan tinker
>>> app(\CreativeCrafts\LaravelAiAssistant\Services\AssistantService::class);

# Clear all caches
php artisan optimize:clear