# Groq PHP SDK ## Introduction Groq PHP is a comprehensive PHP client library for the GroqCloud API, providing seamless integration with the world's fastest LLM inference platform. This SDK enables PHP developers to leverage high-performance language models including DeepSeek r1, Llama 3.3, Mixtral, and Gemma for building AI-powered applications with minimal latency. The library offers a complete suite of features including chat completions, streaming responses, tool calling, audio transcription/translation, text-to-speech, vision analysis, reasoning capabilities, and asynchronous batch processing. Built on top of Guzzle HTTP client, it provides a fluent, object-oriented API with comprehensive error handling and validation, making it straightforward to integrate advanced LLM capabilities into any PHP application. ## APIs and Functions ### Installation and Configuration Initialize the Groq client with your API key. ```php 'https://api.groq.com/openai/v1', 'timeout' => 30000 ]); ``` ### Chat Completions Generate conversational responses using language models. ```php chat()->completions()->create([ 'model' => 'llama-3.1-8b-instant', 'messages' => [ [ 'role' => 'system', 'content' => 'You are a helpful assistant specializing in PHP development.' ], [ 'role' => 'user', 'content' => 'Explain the importance of low latency in LLMs' ] ], 'temperature' => 0.7, 'max_completion_tokens' => 1024, 'top_p' => 1.0, 'frequency_penalty' => 0, 'presence_penalty' => 0 ]); echo $response['choices'][0]['message']['content']; echo "\n\nTokens used: " . $response['usage']['total_tokens']; } catch (GroqException $e) { echo "Error: " . $e->getMessage(); echo "\nType: " . $e->getType(); echo "\nCode: " . $e->getCode(); } ``` ### Streaming Chat Completions Stream responses in real-time for better user experience. ```php chat()->completions()->create([ 'model' => 'llama-3.1-8b-instant', 'messages' => [ ['role' => 'user', 'content' => 'Tell me a short story about PHP'] ], 'stream' => true, 'temperature' => 0.8 ]); // Process streaming chunks foreach ($response->chunks() as $chunk) { if (isset($chunk['choices'][0]['delta']['content'])) { echo $chunk['choices'][0]['delta']['content']; ob_flush(); flush(); } // Check if stream is finished if (isset($chunk['choices'][0]['finish_reason'])) { echo "\n\nFinish reason: " . $chunk['choices'][0]['finish_reason']; } } } catch (GroqException $e) { echo "Error: " . $e->getMessage(); } ``` ### JSON Mode for Structured Output Force the model to respond with valid JSON objects. ```php chat()->completions()->create([ 'model' => 'llama3-70b-8192', 'messages' => [ [ 'role' => 'system', 'content' => 'You are an API that responds only with valid JSON.' ], [ 'role' => 'user', 'content' => 'Give me weather information for London with temperature, conditions, and humidity' ] ], 'response_format' => ['type' => 'json_object'], 'temperature' => 0.5 ]); $jsonContent = $response['choices'][0]['message']['content']; $weatherData = json_decode($jsonContent, true); echo "Weather Data:\n"; echo json_encode($weatherData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); // Validate JSON structure if (json_last_error() === JSON_ERROR_NONE) { echo "\n\nValid JSON received"; } } catch (GroqException $e) { echo "Error: " . $e->getMessage(); } ``` ### Tool Calling Enable models to call external functions and tools. ```php '401585601', 'status' => 'Final', 'home_team' => 'Los Angeles Lakers', 'home_team_score' => 121, 'away_team' => 'Golden State Warriors', 'away_team_score' => 128 ]); } return json_encode(['team_name' => $teamName, 'score' => 'unknown']); } $messages = [ [ 'role' => 'system', 'content' => "Call the 'getNbaScore' function to answer NBA game score questions." ], [ 'role' => 'user', 'content' => 'What was the Warriors score in their last game?' ] ]; $tools = [ [ 'type' => 'function', 'function' => [ 'name' => 'getNbaScore', 'description' => 'Get the score for a given NBA game', 'parameters' => [ 'type' => 'object', 'properties' => [ 'team_name' => [ 'type' => 'string', 'description' => "The NBA team name (e.g., 'Golden State Warriors')" ] ], 'required' => ['team_name'] ] ] ] ]; try { // First API call with tools $response = $groq->chat()->completions()->create([ 'model' => 'llama3-groq-70b-8192-tool-use-preview', 'messages' => $messages, 'tool_choice' => 'auto', 'tools' => $tools ]); // Check if model wants to call a tool if (isset($response['choices'][0]['message']['tool_calls'])) { $toolCall = $response['choices'][0]['message']['tool_calls'][0]; $functionArgs = json_decode($toolCall['function']['arguments'], true); // Execute the function $functionResponse = getNbaScore($functionArgs['team_name']); // Add function result to messages $messages[] = [ 'tool_call_id' => $toolCall['id'], 'role' => 'tool', 'name' => 'getNbaScore', 'content' => $functionResponse ]; // Second API call with function result $response = $groq->chat()->completions()->create([ 'model' => 'llama3-groq-70b-8192-tool-use-preview', 'messages' => $messages ]); } echo $response['choices'][0]['message']['content']; } catch (GroqException $e) { echo "Error: " . $e->getMessage(); } ``` ### Audio Transcription Convert audio files to text with high accuracy. ```php audio()->transcriptions()->create([ 'file' => '/path/to/audio.mp3', 'model' => 'whisper-large-v3', 'response_format' => 'verbose_json', 'language' => 'en', 'temperature' => 0.0, 'prompt' => 'This is a technical interview about software development.' ]); // For verbose_json format echo "Transcription:\n"; echo $transcription['text'] . "\n\n"; echo "Language: " . $transcription['language'] . "\n"; echo "Duration: " . $transcription['duration'] . " seconds\n\n"; // Process segments with timestamps if (isset($transcription['segments'])) { echo "Segments:\n"; foreach ($transcription['segments'] as $segment) { $start = gmdate('H:i:s', (int)$segment['start']); $end = gmdate('H:i:s', (int)$segment['end']); echo "[$start - $end] " . $segment['text'] . "\n"; } } } catch (GroqException $e) { echo "Error: " . $e->getMessage(); if ($e->getCode() === 400) { echo "\nPlease check if the audio file exists and is in a supported format."; } } ``` ### Audio Translation Translate audio from any supported language to English. ```php audio()->translations()->create([ 'file' => '/path/to/spanish_audio.mp3', 'model' => 'whisper-large-v3', 'response_format' => 'verbose_json', 'temperature' => 0.0, 'prompt' => 'This audio is in Spanish.' ]); echo "Translation to English:\n"; echo $translation['text'] . "\n\n"; echo "Original language detected: " . $translation['language'] . "\n"; echo "Duration: " . $translation['duration'] . " seconds\n"; } catch (GroqException $e) { echo "Error: " . $e->getMessage(); } ``` ### Text-to-Speech Convert text to natural-sounding speech audio. ```php audio()->speech() ->model('playai-tts') ->input('Hello! This is a sample text that will be converted to speech.') ->voice('Bryan-PlayAI') ->responseFormat('wav') ->save('/path/to/output.wav'); if ($success) { echo "Audio file saved successfully to output.wav\n"; } // Method 2: Get audio stream for direct use $audioStream = $groq->audio()->speech() ->model('playai-tts') ->input('This is another example of text-to-speech conversion.') ->voice('Bryan-PlayAI') ->responseFormat('wav') ->create(); // Send to browser header('Content-Type: audio/wav'); header('Content-Disposition: attachment; filename="speech.wav"'); echo $audioStream; // For Arabic language $arabicAudio = $groq->audio()->speech() ->model('playai-tts-arabic') ->input('مرحبا بك') ->voice('Hiba-PlayAI') ->save('/path/to/arabic_output.wav'); } catch (GroqException $e) { echo "Error: " . $e->getMessage(); } ``` ### Vision Analysis Analyze images using vision-capable language models. ```php vision()->analyze( '/path/to/image.jpg', 'What objects do you see in this image? Describe their colors and positions.', [ 'temperature' => 0.7, 'max_completion_tokens' => 300 ] ); echo "Local Image Analysis:\n"; echo $response['choices'][0]['message']['content'] . "\n\n"; // Analyze image from URL (up to 20MB) $response = $groq->vision()->analyze( 'https://example.com/sample-image.jpg', 'Describe this image in detail. What is the main subject?' ); echo "URL Image Analysis:\n"; echo $response['choices'][0]['message']['content'] . "\n\n"; // Multi-turn conversation with image context $response = $groq->vision()->analyze( '/path/to/chart.png', 'What data trends do you observe in this chart?', [ 'model' => 'meta-llama/llama-4-scout-17b-16e-instruct', 'temperature' => 0.5 ] ); echo "Chart Analysis:\n"; echo $response['choices'][0]['message']['content']; } catch (GroqException $e) { echo "Error: " . $e->getMessage(); if ($e->getType() === 'ImageSizeLimitExceededException') { echo "\nImage exceeds size limits (4MB for local, 20MB for URL)"; } } ``` ### Reasoning with DeepSeek Perform step-by-step reasoning for complex problem-solving. ```php tags $response = $groq->reasoning()->analyze( 'Explain the process of photosynthesis and its importance to the ecosystem.', [ 'model' => 'deepseek-r1-distill-llama-70b', 'reasoning_format' => 'raw', 'temperature' => 0.6, 'max_completion_tokens' => 10240 ] ); echo "Raw Format (with thinking process):\n"; echo $response['choices'][0]['message']['content'] . "\n\n"; // Parsed format - separates reasoning from answer $response = $groq->reasoning()->analyze( 'Solve this math problem: If 3x + 7 = 22, what is the value of x?', [ 'model' => 'deepseek-r1-distill-llama-70b', 'reasoning_format' => 'parsed', 'temperature' => 0.4 ] ); echo "Parsed Format:\n"; echo "Reasoning steps:\n" . $response['choices'][0]['message']['reasoning'] . "\n\n"; echo "Final answer:\n" . $response['choices'][0]['message']['content'] . "\n\n"; // Hidden format - only shows final answer $response = $groq->reasoning()->analyze( 'What are the three primary colors?', [ 'model' => 'deepseek-r1-distill-llama-70b', 'reasoning_format' => 'hidden', 'system_prompt' => 'Provide concise, accurate answers.' ] ); echo "Hidden Format (answer only):\n"; echo $response['choices'][0]['message']['content']; } catch (GroqException $e) { echo "Error: " . $e->getMessage(); } ``` ### File Management for Batch Processing Upload and manage files for asynchronous batch operations. ```php files(); try { // Upload a JSONL file for batch processing $file = $fileManager->upload('/path/to/batch_requests.jsonl', 'batch'); echo "File uploaded successfully!\n"; echo "File ID: " . $file->getId() . "\n"; echo "Filename: " . $file->getFilename() . "\n"; echo "Size: " . $file->getBytes() . " bytes\n\n"; // List all uploaded files $files = $fileManager->list('batch', [ 'limit' => 10, 'order' => 'desc' ]); echo "Total files: " . count($files['data']) . "\n"; foreach ($files['data'] as $file) { echo "- {$file->getFilename()} ({$file->getId()})\n"; } echo "\n"; // Retrieve file information $fileId = 'file_abc123'; $file = $fileManager->retrieve($fileId); echo "Retrieved file: " . $file->getFilename() . "\n"; echo "Status: " . $file->getStatus() . "\n"; echo "Purpose: " . $file->getPurpose() . "\n\n"; // Download file content $content = $fileManager->download($fileId, true); echo "File content:\n"; $lines = explode("\n", $content); foreach (array_slice($lines, 0, 3) as $line) { echo $line . "\n"; } echo "\n"; // Delete file $result = $fileManager->delete($fileId); if ($result['deleted'] === true) { echo "File deleted: " . $result['id']; } } catch (GroqException $e) { echo "Error: " . $e->getMessage(); if ($e->getType() === 'permissions_error') { echo "\nFiles API not available in your plan. Please upgrade."; } } ``` ### Batch Processing Process large volumes of requests asynchronously for cost efficiency. ```php batches(); try { // Create a batch job $batch = $batchManager->create([ 'input_file_id' => 'file_abc123', 'endpoint' => '/v1/chat/completions', 'completion_window' => '24h', 'metadata' => [ 'description' => 'Processing customer support queries', 'batch_type' => 'customer_support', 'priority' => 'high' ] ]); echo "Batch created successfully!\n"; echo "Batch ID: " . $batch->getId() . "\n"; echo "Status: " . $batch->getStatus() . "\n"; echo "Created at: " . date('Y-m-d H:i:s', $batch->getCreatedAt()) . "\n\n"; // List all batches with filters $batches = $batchManager->list([ 'limit' => 20, 'order' => 'desc', 'status' => 'completed' ]); echo "Completed batches: " . count($batches['data']) . "\n"; foreach ($batches['data'] as $batch) { echo "- Batch {$batch->getId()}: {$batch->getStatus()}\n"; } echo "\n"; // Retrieve batch status and progress $batchId = 'batch_xyz789'; $batch = $batchManager->retrieve($batchId); $summary = $batch->getSummary(); echo "Batch Status Report:\n"; echo "Status: " . $batch->getStatus() . "\n"; echo "Progress: {$summary['completed']}/{$summary['total']} requests\n"; echo "Success rate: " . round(($summary['completed'] / $summary['total']) * 100, 2) . "%\n"; if ($batch->getStatus() === 'completed') { echo "Output file: " . $batch->getOutputFileId() . "\n"; if ($batch->getErrorFileId()) { echo "Error file: " . $batch->getErrorFileId() . "\n"; } } echo "\n"; // Cancel a running batch $cancelledBatch = $batchManager->cancel($batchId); if ($cancelledBatch->getStatus() === 'cancelling') { echo "Batch cancellation initiated\n"; } } catch (GroqException $e) { echo "Error: " . $e->getMessage(); if ($e->getCode() === 403) { echo "\nBatch processing not available in your plan."; } elseif ($e->getCode() === 429) { echo "\nRate limit exceeded. Please try again later."; } } ``` ### List Available Models Query available models and their capabilities. ```php models()->list(); echo "Available Models:\n"; echo "Total: " . count($models['data']) . "\n\n"; foreach ($models['data'] as $model) { echo "Model ID: " . $model['id'] . "\n"; echo "Owner: " . $model['owned_by'] . "\n"; echo "Created: " . date('Y-m-d H:i:s', $model['created']) . "\n"; if (isset($model['context_window'])) { echo "Context window: " . number_format($model['context_window']) . " tokens\n"; } echo "\n"; } } catch (GroqException $e) { echo "Error: " . $e->getMessage(); } ``` ### Error Handling Comprehensive error handling with detailed exception information. ```php chat()->completions()->create([ 'model' => 'llama-3.1-8b-instant', 'messages' => [ ['role' => 'user', 'content' => 'Hello!'] ] ]); echo $response['choices'][0]['message']['content']; } catch (GroqException $e) { // Get error details echo "Error Message: " . $e->getMessage() . "\n"; echo "Error Type: " . $e->getType() . "\n"; echo "HTTP Code: " . $e->getCode() . "\n\n"; // Get full error array $errorDetails = $e->getError(); echo "Error Details:\n"; print_r($errorDetails); echo "\n"; // Get response headers $headers = $e->getHeaders(); if ($headers) { echo "Response Headers:\n"; print_r($headers); echo "\n"; } // Get response body $responseBody = $e->getResponseBody(); if ($responseBody) { echo "Response Body:\n"; print_r($responseBody); echo "\n"; } // Handle specific error types switch ($e->getType()) { case 'invalid_request': echo "Check your request parameters\n"; break; case 'authentication_error': echo "Invalid API key\n"; break; case 'rate_limit_error': echo "Rate limit exceeded, please retry later\n"; break; case 'failed_generation': $invalidJson = $e->getFailedGeneration(); echo "Invalid JSON generated: " . $invalidJson . "\n"; break; default: echo "An unexpected error occurred\n"; } } ``` ## Summary and Integration Patterns Groq PHP SDK serves as a production-ready solution for integrating advanced AI capabilities into PHP applications with minimal complexity. The library excels in scenarios requiring high-speed language model inference, such as real-time chatbots, content generation systems, automated transcription pipelines, and intelligent data processing workflows. Its streaming capabilities make it ideal for building responsive user interfaces, while the batch processing features enable efficient handling of large-scale operations like bulk content analysis, dataset generation, or automated customer support ticket processing. The SDK follows a consistent fluent interface pattern across all features, making it intuitive to chain method calls and configure complex operations. Integration typically involves initializing the Groq client with an API key, then accessing specific services through factory methods (chat, audio, vision, reasoning, files, batches). All operations are protected with comprehensive exception handling through the GroqException class, providing detailed error information including type, code, and context. The library supports both synchronous and asynchronous patterns, file-based caching for batch operations, and extensive validation to catch errors early. For Laravel applications, a dedicated wrapper package (GroqLaravel) provides native framework integration with service providers and facades.