### Install Laravel AI Assistant Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Install the package using Composer and run the installation artisan command. ```bash composer require creativecrafts/laravel-ai-assistant php artisan ai:install ``` -------------------------------- ### Install Laravel AI Assistant Package Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Install the package using Composer and run the AI installation command. Ensure your OpenAI API key is set in the .env file. ```bash composer require creativecrafts/laravel-ai-assistant php artisan ai:install ``` ```env OPENAI_API_KEY=your-openai-api-key-here ``` -------------------------------- ### Basic Pest Test Example Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/tests/README.md A simple Pest test demonstrating how to set configuration values and assert a basic condition. ```php it('generates a response using a fake repository', function () { config(['ai-assistant.mock_responses' => true]); // Arrange fakes or inputs // Act & Assert expect(true)->toBeTrue(); }); ``` -------------------------------- ### Install Dependencies Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/CONTRIBUTING.md Install project dependencies using Composer. Ensure your PHP version is compatible with the project's requirements. ```bash composer install ``` -------------------------------- ### Unified API Example Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Demonstrates the Single Source of Truth (SSOT) unified API approach, showing how a single interface routes requests to appropriate AI operations. ```php load(); $apiKey = $_ENV['OPENAI_API_KEY']; $organization = $_ENV['OPENAI_ORGANIZATION'] ?? null; // --- Initialization --- $ai = new AiAssistant($apiKey, $organization); // --- Unified API Demonstration --- echo "=== Unified API Example ===\n\n"; // 1. Text Conversation -> Routes to Response API echo "1. Text Conversation -> Routes to Response API\n"; // Example: $response = $ai->quick('What is the weather today?'); // 2. Audio Transcription -> Routes to Audio API echo "2. Audio Transcription -> Routes to Audio API\n"; // Example: $transcription = $ai->transcribe(['file' => 'audio.mp3']); // 3. Text-to-Speech -> Routes to Audio Speech API echo "3. Text-to-Speech -> Routes to Audio Speech API\n"; // Example: $speech = $ai->audio(['text' => 'Hello world', 'action' => 'speech']); // 4. Image Generation -> Routes to Image API echo "4. Image Generation -> Routes to Image API\n\n"; // Example: $image = $ai->image(['prompt' => 'A cat', 'action' => 'generate']); // --- Multi-Step Workflow Example --- echo "Multi-Step Workflow:\n"; // Step 1: Generate a tagline (Text Conversation) try { $taglineResponse = $ai->quick('Generate a catchy tagline for a coffee shop.'); echo " Step 1: Generated tagline\n"; // echo " Tagline: " . $taglineResponse->text . "\n"; // Uncomment to see tagline } catch ("Exception" $e) { echo " Step 1 Failed: " . $e->getMessage() . "\n"; } // Step 2: Convert tagline to speech (Audio Speech) try { $outputDir = __DIR__ . '/output'; if (!is_dir($outputDir)) { mkdir($outputDir, 0777, true); } $speechResponse = $ai->audio([ 'text' => $taglineResponse->text ?? 'Default tagline', 'voice' => 'nova', 'action' => 'speech' ]); $speechPath = "{$outputDir}/tagline_speech.mp3"; file_put_contents($speechPath, $speechResponse->content); echo " Step 2: Audio saved to {$speechPath}\n"; } catch ("Exception" $e) { echo " Step 2 Failed: " . $e->getMessage() . "\n"; } // Step 3: Generate an image related to the tagline (Image Generation) try { $imageResponse = $ai->image([ 'prompt' => 'A cozy coffee shop with a sign saying "' . ($taglineResponse->text ?? 'Your Daily Brew') . '"', 'action' => 'generate' ]); $imagePath = "{$outputDir}/tagline_image.png"; file_put_contents($imagePath, $imageResponse->content); echo " Step 3: Image saved to {$imagePath}\n"; } catch ("Exception" $e) { echo " Step 3 Failed: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Publish Full Configuration Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/config/presets/README.md Publish the complete AI Assistant configuration file. This is typically done when migrating from a preset to a more customized setup. ```bash php artisan vendor:publish --tag="laravel-ai-assistant-config" ``` -------------------------------- ### Run Individual Laravel AI Assistant Examples Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Execute individual PHP scripts to test specific features of the Laravel AI Assistant package, such as hello world, streaming, and more. ```bash php examples/01-hello-world.php ``` ```bash php examples/02-streaming.php ``` ```bash php examples/03-cancellation.php ``` ```bash php examples/04-complete-api.php ``` ```bash php examples/05-observability.php ``` ```bash php examples/05-audio-transcription.php ``` ```bash php examples/06-audio-speech.php ``` ```bash php examples/07-image-generation.php ``` ```bash php examples/08-unified-api.php ``` -------------------------------- ### Migrate Chat to SSOT API Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/MIGRATION.md Converts legacy `AiAssistant` chat prompts to the new SSOT API. This example shows how to set the model and temperature before sending the message. ```php use CreativeCrafts\LaravelAiAssistant\Facades\Ai; $response = Ai::responses() ->model('gpt-4') ->temperature(0.7) ->input() ->message('Hello') ->send(); ``` -------------------------------- ### Integrate AI Chat in Laravel Controller Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Shows how to use the Ai::quick() facade method within a Laravel controller to get a response for a given message. ```php namespace App\Http\Controllers; use CreativeCrafts\LaravelAiAssistant\Facades\Ai; use Illuminate\Http\Request; class AiController extends Controller { public function chat(Request $request) { $response = Ai::quick($request->input('message')); return response()->json([ 'response' => $response->text, ]); } public function stream(Request $request) { $generator = Ai::stream($request->input('message')); return StreamedAiResponse::fromGenerator($generator); } } ``` -------------------------------- ### Real-time Streaming with Laravel AI Assistant Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Implement real-time streaming for AI responses using `Ai::stream()`. This example shows basic streaming and streaming with callbacks for real-time processing. ```php // examples/02-streaming.php require __DIR__ . "/../vendor/autoload.php"; use CreativeCrafts\LaravelAiAssistant\Facades\Ai; // Basic streaming $story = Ai::stream("Tell me a short story."); echo "Streaming story: {$story}\n"; // Streaming with callbacks Ai::stream("Tell me another short story.", function (string $chunk, int $chunkCount) { echo "Chunk {$chunkCount}: {$chunk}\n"; }); ``` -------------------------------- ### Advanced SSOT API Endpoints Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/MIGRATION.md Provides examples of using advanced, low-level repository endpoints available through the `Ai` facade, such as moderations, batches, realtime sessions, assistants, and vector stores. ```php Ai::moderations()->create(['input' => 'Check this']); Ai::batches()->create([...]); Ai::realtimeSessions()->create(['model' => 'gpt-4o-realtime-preview']); Ai::assistants()->create(['model' => 'gpt-4o-mini']); Ai::vectorStores()->create(['name' => 'Docs']); ``` -------------------------------- ### Audio Speech Synthesis with Laravel AI Assistant Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Convert text into spoken audio using the `Ai::speech()` method. This example demonstrates basic text-to-speech conversion. ```php // examples/06-audio-speech.php require __DIR__ . "/../vendor/autoload.php"; use CreativeCrafts\LaravelAiAssistant\Facades\Ai; $text = "Hello, this is a test of the Laravel AI Assistant speech synthesis."; $audioContent = Ai::speech($text); // Save the audio content to a file file_put_contents('output.mp3', $audioContent); echo "Audio saved to output.mp3"; ``` -------------------------------- ### Image Generation with Laravel AI Assistant Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Generate images from text prompts using the `Ai::image()` method. This example shows how to create a simple image based on a description. ```php // examples/07-image-generation.php require __DIR__ . "/../vendor/autoload.php"; use CreativeCrafts\LaravelAiAssistant\Facades\Ai; $prompt = "A futuristic cityscape at sunset, digital art"; $imageUrl = Ai::image($prompt); echo "Generated image URL: {$imageUrl}\n"; ``` -------------------------------- ### Create Assistant (v2 beta) Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Set up a new assistant for conversational AI tasks. Requires 'model' and 'name'. ```php $assistant = Ai::assistants()->create([ 'model' => 'gpt-4o-mini', 'name' => 'Support Assistant', ]); ``` -------------------------------- ### Publish and Copy Configuration Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/config/presets/README.md Publish the AI Assistant configuration file and then copy the content of a chosen preset into your published configuration file. ```bash php artisan vendor:publish --tag="laravel-ai-assistant-config" # Then copy from your chosen preset to config/ai-assistant.php ``` -------------------------------- ### Run All Tests Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/CONTRIBUTING.md Execute the full test suite for the project. ```bash composer test ``` -------------------------------- ### Basic SSOT API Usage Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/MIGRATION.md Demonstrates the fundamental usage of the `Ai::responses()` facade for sending a simple message and retrieving a text response. Ensure the `Ai` facade is imported. ```php use CreativeCrafts\LaravelAiAssistant\Facades\Ai; $response = Ai::responses() ->input() ->message('Hello world') ->send(); echo $response->text; ``` -------------------------------- ### Create Vector Store (v2 beta) Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Create a vector store for managing and querying embeddings. Requires a 'name'. ```php $store = Ai::vectorStores()->create([ 'name' => 'Support Docs', ]); ``` -------------------------------- ### Basic Chat Completion with Laravel AI Assistant Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Demonstrates how to perform a quick one-off request and a simple chat session using `Ai::quick()` and `Ai::chat()`. ```php // examples/01-hello-world.php require __DIR__ . "/../vendor/autoload.php"; use CreativeCrafts\LaravelAiAssistant\Facades\Ai; // Quick test $quickResponse = Ai::quick("Laravel queues are"); echo "Quick response: {$quickResponse}\n"; // Chat test $chatResponse = Ai::chat( "Explain what service providers are in Laravel." ); echo "Chat response: {$chatResponse}\n"; ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/CONTRIBUTING.md Run tests and generate a code coverage report. The HTML report will be available in the `build/coverage/` directory. ```bash composer test-coverage ``` -------------------------------- ### Create Realtime Session Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Initiate a realtime session for interactive AI experiences. Specify the desired 'model'. ```php $session = Ai::realtimeSessions()->create([ 'model' => 'gpt-4o-realtime-preview', ]); ``` -------------------------------- ### File Upload and Content Retrieval (3.1+) Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/MIGRATION.md Demonstrates file upload and content retrieval using the `Ai::files()` service, introduced in version 3.1. This involves uploading a file and then fetching its content by ID. ```php $file = Ai::files()->upload(storage_path('docs/guide.pdf')); $content = Ai::files()->content($file['id']); ``` -------------------------------- ### Run Static Analysis Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/CONTRIBUTING.md Execute static analysis to check for code quality and potential issues using `composer analyse`. ```bash composer analyse ``` -------------------------------- ### Migrate Tool Usage to SSOT API Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/MIGRATION.md Shows how to migrate tool usage, including function calling, to the SSOT API. It involves building tools using `ToolsBuilder` and passing them to the `Ai::responses()` method. ```php use CreativeCrafts\LaravelAiAssistant\Support\ToolsBuilder; $tools = (new ToolsBuilder()) ->includeFunctionCallTool('getWeather', 'Fetch weather', [ 'properties' => ['city' => ['type' => 'string']], 'required' => ['city'], ]) ->toArray(); $response = Ai::responses() ->tools($tools) ->input() ->message('Weather in Paris?') ->send(); ``` -------------------------------- ### Generate, Edit, and Create Image Variations Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Demonstrates image generation from prompts, editing existing images, and creating variations using DALL-E models. Images are saved to the output directory. ```php load(); $apiKey = $_ENV['OPENAI_API_KEY']; $organization = $_ENV['OPENAI_ORGANIZATION'] ?? null; // --- Initialization --- $ai = new AiAssistant($apiKey, $organization); // --- Image Generation --- $outputDir = __DIR__ . '/output'; if (!is_dir($outputDir)) { mkdir($outputDir, 0777, true); } // 1. Generate image from prompt (DALL-E 3) $prompt = "A serene mountain landscape, digital art"; try { $response = $ai->image([ 'prompt' => $prompt, 'model' => 'dall-e-3', 'size' => '1024x1024', 'quality' => 'standard', 'style' => 'vivid', 'action' => 'generate' ]); $filename = 'image-basic.png'; $filePath = "{$outputDir}/{$filename}"; file_put_contents($filePath, $response->content); echo "=== Image Generation Example ===\n"; echo "Prompt: {$prompt}\n"; echo "Generated image saved to: {$filePath}\n\n"; } catch ("Exception" $e) { echo "Error generating image: " . $e->getMessage() . "\n"; } // 2. Generate image with specific size, quality, and style (DALL-E 3) $promptHd = "A futuristic cityscape at sunset, photorealistic"; try { $responseHd = $ai->image([ 'prompt' => $promptHd, 'model' => 'dall-e-3', 'size' => '1024x1024', 'quality' => 'hd', 'style' => 'vivid', 'action' => 'generate' ]); $filenameHd = 'image-hd-vivid.png'; $filePathHd = "{$outputDir}/{$filenameHd}"; file_put_contents($filePathHd, $responseHd->content); echo "Size: 1024x1024\n"; echo "Quality: hd\n"; echo "Style: vivid\n"; echo "Generated image saved to: {$filePathHd}\n"; } catch ("Exception" $e) { echo "Error generating HD image: " . $e->getMessage() . "\n"; } // Note: Image editing and variation examples would follow similar patterns // using 'edit' or 'variations' actions and providing 'image' parameter. ``` -------------------------------- ### Integrate AI Chat in Laravel Command Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Demonstrates how to use the Ai::quick() facade method within a Laravel console command to process a message argument. ```php namespace App\Console\Commands; use CreativeCrafts\LaravelAiAssistant\Facades\Ai; use Illuminate\Console\Command; class AiChatCommand extends Command { protected $signature = 'ai:chat {message}'; public function handle() { $response = Ai::quick($this->argument('message')); $this->info($response->text); } } ``` -------------------------------- ### Run CI Helper Script Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/CONTRIBUTING.md Execute the CI helper script to perform validation, auditing, analysis, and coverage checks. ```bash composer ci ``` -------------------------------- ### Observability with Laravel AI Assistant Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Integrate comprehensive observability features like correlation ID tracking, structured logging, performance metrics, and error reporting for production systems. ```php // examples/05-observability.php require __DIR__ . "/../vendor/autoload.php"; use CreativeCrafts\LaravelAiAssistant\Facades\Ai; // AI Request with Observability $response = Ai::quick("Laravel queues are", ['with_observability' => true]); $metrics = Ai::getObservabilityMetrics(); echo "AI Request with Observability:\n"; echo "Response: {$response}\n"; echo "Duration: {$metrics['duration']}s\n"; echo "Memory used: {$metrics['memory_usage']}MB\n"; echo "Metrics recorded: " . count($metrics['metrics']) . "\n\n"; // Stream with Observability $chunkCount = 0; Ai::stream("Tell me a story.", function (string $chunk) use (&$chunkCount) { $chunkCount++; }, ['with_observability' => true]); $streamMetrics = Ai::getObservabilityMetrics(); echo "Stream with Observability:\n"; echo "Chunks: {$chunkCount}\n"; echo "Duration: {$streamMetrics['duration']}s\n"; echo "All metrics logged successfully!\n"; ``` -------------------------------- ### Enabling Eloquent Persistence Driver Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/tests/README.md Configure the package to use the Eloquent persistence driver and run necessary migrations. This is required for validating Eloquent persistence flows. ```php config(['ai-assistant.persistence.driver' => 'eloquent']); // Ensure migrations are loaded. With Testbench, you can run: $this->artisan('migrate', ['--database' => 'testing'])->run(); ``` -------------------------------- ### Configure OpenAI API Key Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Set your OpenAI API key in the .env file for authentication. ```env OPENAI_API_KEY=your-openai-api-key-here ``` -------------------------------- ### Configure Webhooks Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Enable and configure webhook settings in your .env file. Essential parameters include 'AI_WEBHOOKS_ENABLED', 'AI_WEBHOOKS_SIGNING_SECRET', and optionally 'AI_WEBHOOKS_REQUIRE_TIMESTAMP'. ```env AI_WEBHOOKS_ENABLED=true AI_WEBHOOKS_SIGNING_SECRET=your-strong-secret AI_WEBHOOKS_REQUIRE_TIMESTAMP=true ``` -------------------------------- ### Implement content() in Custom Files Repositories Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/UPGRADE.md If you are implementing the `FilesRepositoryContract`, you must add the `content` method. This method is used to retrieve the content of a specific file. ```php public function content(string $fileId): array; ``` -------------------------------- ### Advanced SSOT Builder Usage Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Customize AI model parameters like temperature and specify the model for advanced requests. ```php $response = Ai::responses() ->model('gpt-4o-mini') ->temperature(0.3) ->input() ->message('Write a haiku about Laravel') ->send(); ``` -------------------------------- ### Unified API for Various AI Tasks Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Demonstrates the versatility of the unified API for different AI tasks beyond text completion, including audio and image processing. ```php // examples/08-unified-api.php require __DIR__ . "/../vendor/autoload.php"; use CreativeCrafts\LaravelAiAssistant\Facades\Ai; // Example: Audio Transcription using unified API $transcription = Ai::processAudio( 'test-audio.mp3', 'transcribe', ['language' => 'en'] ); echo "Transcription: {$transcription}\n\n"; // Example: Image Generation using unified API $prompt = "A cute cat wearing a hat"; $imageUrl = Ai::processImage($prompt); echo "Generated image URL: {$imageUrl}\n"; ``` -------------------------------- ### Migrate Audio Transcription to SSOT API Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/MIGRATION.md Demonstrates migrating audio transcription from the legacy repository to the SSOT API. The `audio()` method is used with the 'transcribe' action, specifying the file path. ```php $response = Ai::responses() ->input() ->audio([ 'file' => storage_path('audio/recording.mp3'), 'action' => 'transcribe', ]) ->send(); ``` -------------------------------- ### Create Batch Job Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md This snippet demonstrates how to create a batch job for processing large amounts of data. It requires 'input_file_id', 'endpoint', and 'completion_window'. ```php $batch = Ai::batches()->create([ 'input_file_id' => 'file_123', 'endpoint' => '/v1/responses', 'completion_window' => '24h', ]); ``` -------------------------------- ### Tool Calling with Chat Sessions Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Define and use tools for chat sessions, enabling the AI to call functions. Specify function names, descriptions, and parameters. ```php use CreativeCrafts\LaravelAiAssistant\Support\ToolsBuilder; $session = Ai::chat('You are a helpful assistant'); $session->tools() ->includeFunctionCallTool('getWeather', 'Fetch weather', [ 'properties' => ['city' => ['type' => 'string']], 'required' => ['city'], ]); $response = $session->send('What is the weather in Paris?'); ``` -------------------------------- ### Format Code with Laravel Pint Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/CONTRIBUTING.md Format your code according to the project's coding standards using the `composer format` command. ```bash composer format ``` -------------------------------- ### Configure Mock Responses for Testing Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/CONTRIBUTING.md In tests, disable real network calls by setting `ai-assistant.mock_responses` to true in the configuration. Use fakes provided in `tests/Fakes/*`. ```php config(['ai-assistant.mock_responses' => true]); ``` -------------------------------- ### Migrate Image Generation to SSOT API Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/MIGRATION.md Demonstrates migrating image generation to the SSOT API. The `image()` method is used with a 'prompt' parameter. The response object provides a method to save the generated images. ```php $response = Ai::responses() ->input() ->image([ 'prompt' => 'A futuristic Laravel logo', ]) ->send(); $response->saveImages(storage_path('images')); ``` -------------------------------- ### Unified Completion API with Laravel AI Assistant Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Utilize the modern, unified completion API with `AiManager::complete()`, supporting different modes (TEXT, CHAT) and transports (SYNC, STREAM). ```php // examples/04-complete-api.php require __DIR__ . "/../vendor/autoload.php"; use CreativeCrafts\LaravelAiAssistant\Facades\Ai; use CreativeCrafts\LaravelAiAssistant\Enums\Mode; use CreativeCrafts\LaravelAiAssistant\Enums\Transport; use CreativeCrafts\LaravelAiAssistant\DTO\CompletionRequest; // TEXT + SYNC echo "TEXT + SYNC:\n"; $textSyncRequest = new CompletionRequest(mode: Mode::TEXT, transport: Transport::SYNC); $textSyncResponse = Ai::complete($textSyncRequest->toArray()); echo "Result: {$textSyncResponse}\n\n"; // CHAT + SYNC echo "CHAT + SYNC:\n"; $chatSyncRequest = new CompletionRequest(mode: Mode::CHAT, transport: Transport::SYNC); $chatSyncResponse = Ai::complete($chatSyncRequest->toArray()); echo "Result: {" . json_encode($chatSyncResponse) . "}\n\n"; // TEXT + STREAM echo "TEXT + STREAM:\n"; $textStreamRequest = new CompletionRequest(mode: Mode::TEXT, transport: Transport::STREAM); $textStreamResponse = Ai::complete($textStreamRequest->toArray(), function (string $chunk) { echo $chunk; }); echo "\nFinal result: Once upon a time in Laravel...\n"; ``` -------------------------------- ### Basic Chat Interaction Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Send a message to the AI and retrieve the text response using the SSOT builder. ```php use CreativeCrafts\LaravelAiAssistant\Facades\Ai; $response = Ai::responses() ->input() ->message('Explain Laravel queues in simple terms') ->send(); echo $response->text; ``` -------------------------------- ### Run Smoke Test for Laravel AI Assistant Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Execute the smoke test script to verify that the Laravel AI Assistant package is correctly set up and functional. ```bash php examples/smoke-test.php ``` -------------------------------- ### Migrate Text-to-Speech to SSOT API Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/MIGRATION.md Shows the migration for text-to-speech functionality to the SSOT API. The `audio()` method is used with the 'speech' action, providing text and voice parameters. The response includes a method to save the generated audio. ```php $response = Ai::responses() ->input() ->audio([ 'text' => 'Welcome to Laravel AI Assistant', 'action' => 'speech', 'voice' => 'alloy', ]) ->send(); $response->saveAudio(storage_path('audio/welcome.mp3')); ``` -------------------------------- ### Migrate Audio Translation to SSOT API Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/MIGRATION.md Illustrates migrating audio translation to the SSOT API. Similar to transcription, the `audio()` method is used with the 'translate' action and the file path. ```php $response = Ai::responses() ->input() ->audio([ 'file' => storage_path('audio/french.mp3'), 'action' => 'translate', ]) ->send(); ``` -------------------------------- ### Check Optional Dependencies Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/CONTRIBUTING.md Perform checks for optional dependencies. This may require Composer version 2.7 or later. ```bash composer check-deps ``` ```bash composer audit ``` -------------------------------- ### File Upload Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Upload a file to the AI assistant. The response contains the file ID, which can be used for further operations. ```php $fileId = Ai::files()->upload(storage_path('docs/guide.pdf'))['id'] ?? null; ``` -------------------------------- ### Migrate Streaming Chat to SSOT API Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/MIGRATION.md Shows how to migrate from streaming chat responses using the legacy assistant to the SSOT API's streaming capability. The `stream()` method is used to iterate over Server-Sent Events. ```php foreach (Ai::responses()->input()->message('Tell me a story')->stream() as $event) { // handle SSE events } ``` -------------------------------- ### Controlling Streaming Operations with Cancellation Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Learn to control and stop streaming AI responses mid-flight using chunk count, time-based limits, or user-initiated patterns with the `shouldStop` callback. ```php // examples/03-cancellation.php require __DIR__ . "/../vendor/autoload.php"; use CreativeCrafts\LaravelAiAssistant\Facades\Ai; echo "Limiting to 5 chunks...\n"; Ai::stream("Tell me a very long story.", function (string $chunk, int $chunkCount) { echo "Chunk {$chunkCount}: {$chunk}\n"; // Stop after 5 chunks return $chunkCount >= 5; }); echo "Stopped after 5 chunks!\n"; ``` -------------------------------- ### Run Tests by Name Pattern Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/tests/README.md Filter and run tests that match a specific name pattern using the Pest command-line interface. ```bash vendor/bin/pest -d 'logging service' ``` -------------------------------- ### Create Moderation Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Use this snippet to check content against OpenAI's moderation policies. It requires the 'input' parameter. ```php $result = Ai::moderations()->create([ 'input' => 'Check this content', ]); ``` -------------------------------- ### Audio Transcription and Translation with Laravel AI Assistant Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Transcribe and translate audio files using the unified Response API. Supports various formats and provides options for language hints, context prompts, and response formats. ```php // examples/05-audio-transcription.php require __DIR__ . "/../vendor/autoload.php"; use CreativeCrafts\LaravelAiAssistant\Facades\Ai; // Transcription $transcription = Ai::audio([ 'file' => 'test-audio.mp3', 'action' => 'transcribe', 'language' => 'en', 'prompt' => 'This audio is about Laravel.', 'response_format' => 'text' ]); echo "Audio File: test-audio.mp3\n"; echo "Transcription: {$transcription}\n"; echo "Type: audio_transcription\n\n"; // Translation $translation = Ai::audio([ 'file' => 'test-audio.mp3', 'action' => 'translate', 'response_format' => 'text' ]); echo "Audio File: test-audio.mp3\n"; echo "Translation: {$translation}\n"; echo "Type: audio_translation\n"; ``` -------------------------------- ### Audio Transcription Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Transcribe an audio file using the AI assistant. Ensure the audio file path is correct. ```php $response = Ai::responses() ->input() ->audio([ 'file' => storage_path('audio/recording.mp3'), 'action' => 'transcribe', ]) ->send(); echo $response->text; ``` -------------------------------- ### Integrate AI Request in Laravel Job Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Illustrates how to process an AI request asynchronously within a Laravel queueable job, including setting a correlation ID for observability. ```php namespace App\Jobs; use CreativeCrafts\LaravelAiAssistant\Facades\{Ai, Observability}; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; class ProcessAiRequest implements ShouldQueue { use Queueable; public function __construct( private string $correlationId, private string $prompt ) {} public function handle() { Observability::setCorrelationId($this->correlationId); $response = Ai::quick($this->prompt); // Process response... } } ``` -------------------------------- ### Run Specific Test File or Folder Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/tests/README.md Execute tests located within a specific file or directory using the Pest command-line interface. ```bash vendor/bin/pest tests/Unit ``` -------------------------------- ### Migrate Image Editing to SSOT API Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/MIGRATION.md Illustrates migrating image editing functionality to the SSOT API. The `image()` method is used with 'image', 'mask', and 'prompt' parameters to modify an existing image. ```php $response = Ai::responses() ->input() ->image([ 'image' => storage_path('images/input.png'), 'mask' => storage_path('images/mask.png'), 'prompt' => 'Add neon glow', ]) ->send(); ``` -------------------------------- ### Implement getContent in Custom Transports Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/UPGRADE.md When providing a custom transport for OpenAI, ensure it implements the `getContent` method. This method should return an array containing 'content' (string) and 'content_type' (string). ```php public function getContent(string $path, array $headers = [], ?float $timeout = null): array; ``` -------------------------------- ### Environment Variable Overrides Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/config/presets/README.md Override default AI Assistant settings using environment variables in your .env file. This allows for flexible customization on top of any chosen preset. ```env # Required for all presets OPENAI_API_KEY=your-api-key-here # Override default model OPENAI_CHAT_MODEL=gpt-4o # Enable/disable features AI_STREAMING_ENABLED=true AI_METRICS_ENABLED=false ``` -------------------------------- ### Image Generation Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Generate an image based on a text prompt. The generated images can be saved to a specified directory. ```php $response = Ai::responses() ->input() ->image([ 'prompt' => 'A futuristic Laravel logo with neon lights', ]) ->send(); $response->saveImages(storage_path('images')); ``` -------------------------------- ### Binding Contract to Fake Implementation Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/tests/README.md Rebind a service contract to a fake implementation in the Laravel container for testing purposes. Ensure the fake class is imported. ```php use CreativeCrafts\LaravelAiAssistant\Contracts\FilesRepositoryContract; use CreativeCrafts\LaravelAiAssistant\Tests\Fakes\FakeFilesRepository; app()->bind(FilesRepositoryContract::class, fn () => new FakeFilesRepository()); ``` -------------------------------- ### Generate Speech from Text Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Converts text to speech using various voice options, speech speeds, and audio formats. Audio files are saved to the output directory. ```php load(); $apiKey = $_ENV['OPENAI_API_KEY']; $organization = $_ENV['OPENAI_ORGANIZATION'] ?? null; // --- Initialization --- $ai = new AiAssistant($apiKey, $organization); // --- Audio Speech Generation --- $textToConvert = "Hello, this is a test of the Laravel AI Assistant's text-to-speech functionality."; $voices = ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer']; $outputDir = __DIR__ . '/output'; // Ensure output directory exists if (!is_dir($outputDir)) { mkdir($outputDir, 0777, true); } echo "=== Audio Speech Generation Example ===\n"; foreach ($voices as $voice) { try { $response = $ai->audio([ 'text' => $textToConvert, 'voice' => $voice, 'model' => 'tts-1', 'speed' => 1.0, 'action' => 'speech' ]); $filename = "speech-{$voice}.mp3"; $filePath = "{$outputDir}/{$filename}"; // Save the audio content to a file file_put_contents($filePath, $response->content); echo "Voice: {$voice} -> {$filePath}\n"; } catch ("Exception" $e) { echo "Error generating speech for voice {$voice}: " . $e->getMessage() . "\n"; } } echo "\nAll audio files saved successfully!\n"; ``` -------------------------------- ### Image Editing Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Edit an existing image by providing an image, a mask, and a prompt. Save the edited image to a specified directory. ```php // Image editing $response = Ai::responses() ->input() ->image([ 'image' => storage_path('images/input.png'), 'mask' => storage_path('images/mask.png'), 'prompt' => 'Add a neon glow', ]) ->send(); $response->saveImages(storage_path('images/edited')); ``` -------------------------------- ### Increase Connection Timeout Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/examples/README.md Adjust the connection timeout in the configuration file to handle potential delays. ```php // config/ai-assistant.php 'timeout' => 60, // seconds ``` -------------------------------- ### File Content Download Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Download the content of a file using its ID. The content can then be saved or processed. ```php $content = Ai::files()->content('file_123'); file_put_contents(storage_path('downloads/file.jsonl'), $content['content']); ``` -------------------------------- ### Managing Conversations Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Create and interact within a conversation context to maintain chat history. Use the conversation ID to reference ongoing discussions. ```php $conversation = Ai::conversations()->create(); Ai::responses() ->inConversation($conversation['id']) ->input() ->message('Remember: I like short answers') ->send(); ``` -------------------------------- ### Validate Composer Metadata Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/CONTRIBUTING.md Validate the `composer.json` file for correctness and adherence to standards. ```bash composer validate-composer ``` -------------------------------- ### Speech Synthesis Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Convert text into speech using specified voice options. Save the generated audio to a file. ```php // Speech synthesis $response = Ai::responses() ->input() ->audio([ 'text' => 'Welcome to Laravel AI Assistant', 'action' => 'speech', 'voice' => 'alloy', ]) ->send(); $response->saveAudio(storage_path('audio/welcome.mp3')); ``` -------------------------------- ### Streaming AI Responses Source: https://github.com/creativecrafts/laravel-ai-assistant/blob/main/README.md Process AI responses as a stream of events. This is useful for real-time feedback in chat applications. ```php foreach (Ai::responses()->input()->message('Tell me about Laravel')->stream() as $event) { // $event is a normalized SSE event // You can also use Ai::stream(...) for a simpler chat stream } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.