PHP code example of lucianotonet / groq-php

1. Go to this page and download the library: Download lucianotonet/groq-php 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/ */

    

lucianotonet / groq-php example snippets


$models = $groq->models()->list();
print_r($models['data']);
// print_r output (formatted):
// Array (
//   [0] => Array ( [id] => openai/gpt-oss-20b [object] => model [owned_by] => OpenAI )
//   [1] => Array ( [id] => whisper-large-v3 [object] => model [owned_by] => Groq )
//   ...
// )

$model = $groq->models()->retrieve('openai/gpt-oss-20b');
echo $model['id'];
// Output: openai/gpt-oss-20b



use LucianoTonet\GroqPHP\Groq;

$groq = new Groq(getenv('GROQ_API_KEY'));

try {
    $response = $groq->chat()->completions()->create([
        'model' => 'openai/gpt-oss-20b', // Or another supported model
        'messages' => [
            ['role' => 'user', 'content' => 'Explain the importance of low latency in LLMs'],
        ],
    ]);

    echo $response['choices'][0]['message']['content'];
    // Expected response structure (formatted):
    // {
    //   "id": "chatcmpl-9a8b7c6d",
    //   "object": "chat.completion",
    //   "model": "openai/gpt-oss-20b",
    //   "choices": [
    //     {
    //       "index": 0,
    //       "message": { "role": "assistant", "content": "Low latency is critical because ..." },
    //       "finish_reason": "stop"
    //     }
    //   ],
    //   "usage": { "prompt_tokens": 15, "completion_tokens": 120, "total_tokens": 135 }
    // }
} catch (\LucianoTonet\GroqPHP\GroqException $e) {
    echo 'Error: ' . $e->getMessage();
}

$response = $groq->chat()->completions()->create([
    'model' => 'openai/gpt-oss-20b',
    'messages' => [
        ['role' => 'user', 'content' => 'Tell me a short story'],
    ],
    'stream' => true
]);

foreach ($response->chunks() as $chunk) {
    if (isset($chunk['choices'][0]['delta']['content'])) {
        echo $chunk['choices'][0]['delta']['content'];
        ob_flush(); // Important for real streaming
        flush();
    }
}

// Streamed chunk structure (formatted):
// {
//   "id": "chatcmpl-...",
//   "choices": [ { "delta": { "role": "assistant", "content": "Once" }, "finish_reason": null } ]
// }
// Chunks stream until finish_reason: "stop" (then a final [DONE] signal).

$response = $groq->chat()->completions()->create([
        'model' => 'openai/gpt-oss-120b',
    'messages' => [
        ['role' => 'system', 'content' => 'You are an API and must respond only with valid JSON.'],
        ['role' => 'user', 'content' => 'Give me information about the current weather in London'],
    ],
    'response_format' => ['type' => 'json_object']
]);

$content = $response['choices'][0]['message']['content'];
echo json_encode(json_decode($content), JSON_PRETTY_PRINT); // Display formatted JSON
// Output (formatted JSON):
// {
//   "location": "London",
//   "temperature": "15",
//   "unit": "Celsius"
// }

$response = $groq->chat()->completions()->create([
    'model' => 'openai/gpt-oss-20b',
    'messages' => [
        ['role' => 'system', 'content' => 'Extract product review information from the text.'],
        ['role' => 'user', 'content' => 'I bought the UltraSound Headphones and I am really impressed!'],
    ],
    'response_format' => [
        'type' => 'json_schema',
        'json_schema' => [
            'name' => 'product_review',
            'strict' => true,
            'schema' => [
                'type' => 'object',
                'properties' => [
                    'product_name' => ['type' => 'string'],
                    'rating' => ['type' => 'number'],
                ],
                '


// Example function (simulated)
function getNbaScore($teamName) {
    // ... (simulated logic to return score) ...
    return json_encode(['team' => $teamName, 'score' => 100]); // Example
}

$messages = [
    ['role' => 'system', 'content' => "You must call the 'getNbaScore' function to answer questions about NBA game scores."],
    ['role' => 'user', 'content' => 'What is the Lakers score?']
];

$tools = [
    [
        'type' => 'function',
        'function' => [
            'name' => 'getNbaScore',
            'description' => 'Get the score for an NBA game',
            'parameters' => [
                'type' => 'object',
                'properties' => [
                    'team_name' => ['type' => 'string', 'description' => 'NBA team name'],
                ],
                'tion_response,
    ];

    // Second call to the model with tool response:
    $response = $groq->chat()->completions()->create([
        'model' => 'openai/gpt-oss-120b',
        'messages' => $messages
    ]);
    echo $response['choices'][0]['message']['content'];
} else {
    // Direct response, no tool_calls
    echo $response['choices'][0]['message']['content'];
}

// When the model requests a tool, the first response 

use LucianoTonet\GroqPHP\Groq;

$groq = new Groq(getenv('GROQ_API_KEY'));

try {
    $transcription = $groq->audio()->transcriptions()->create([
        'file' => 'audio.mp3', /* Your audio file */
        'model' => 'whisper-large-v3',
        'response_format' => 'verbose_json', /* Or 'text', 'json' */
        'language' => 'en', /* ISO 639-1 code (optional but recommended) */
        'prompt' => 'Audio transcription...' /* (optional) */
    ]);

    echo json_encode($transcription, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    // Output (formatted JSON):
    // {
    //   "text": "Hello, how can I help you today",
    //   "language": "english",
    //   "duration": 3.2,
    //   "segments": [ { "start": 0.0, "end": 2.1, "text": "Hello, how can I help you today" } ]
    // }
} catch (\LucianoTonet\GroqPHP\GroqException $e) {
    echo "Error: " . $e->getMessage();
}

// (Similar to transcription, but uses ->translations()->create() and always translates to English)

// Target language for translation is always English
$translation = $groq->audio()->translations()->create([
    'file' => 'audio_in_spanish.mp3',
    'model' => 'whisper-large-v3'
]);

use LucianoTonet\GroqPHP\Groq;

$groq = new Groq(getenv('GROQ_API_KEY'));

try {
    // Method 1: Save to file
    $result = $groq->audio()->speech()
        ->model('canopylabs/orpheus-v1-english')  // 'canopylabs/orpheus-v1-english' for English, 'canopylabs/orpheus-arabic-saudi' for Arabic
        ->input('Hello, this text will be converted to speech')
        ->voice('troy')  // Voice identifier
        ->responseFormat('wav')  // Output format
        ->save('output.wav');
    
    if ($result) {
        echo "Audio file saved successfully!";
    }
    
    // Method 2: Get as stream
    $audioStream = $groq->audio()->speech()
        ->model('canopylabs/orpheus-v1-english')
        ->input('This is another example text')
        ->voice('troy')
        ->create();
    
    // Use the stream (e.g., send to browser)
    header('Content-Type: audio/wav');
    header('Content-Disposition: inline; filename="speech.wav"');
    echo $audioStream;
    
} catch (\LucianoTonet\GroqPHP\GroqException $e) {
    echo "Error: " . $e->getMessage();
}

// Method 1 prints: "Audio file saved successfully!"
// Method 2 streams raw WAV audio bytes (Content-Type: audio/wav).

use LucianoTonet\GroqPHP\Groq;

$groq = new Groq(getenv('GROQ_API_KEY'));

try {
    // Analyze a local image
    $response = $groq->vision()->analyze('path/to/image.jpg', 'What do you see in this image?');
    
    // Analyze an image from URL
    $response = $groq->vision()->analyze('https://example.com/image.jpg', 'Describe this image');
    
    // Custom options
    $response = $groq->vision()->analyze('path/to/image.jpg', 'What colors do you see?', [
        'temperature' => 0.7,
        'max_completion_tokens' => 100
    ]);

    echo $response['choices'][0]['message']['content'];
    // Expected response structure (formatted):
    // {
    //   "choices": [
    //     { "message": { "role": "assistant", "content": "I see a sunset over the mountains..." }, "finish_reason": "stop" }
    //   ],
    //   "usage": { "prompt_tokens": 120, "completion_tokens": 40, "total_tokens": 160 }
    // }
} catch (\LucianoTonet\GroqPHP\GroqException $e) {
    echo 'Error: ' . $e->getMessage();
}

use LucianoTonet\GroqPHP\Groq;

$groq = new Groq(getenv('GROQ_API_KEY'));

try {
    $response = $groq->reasoning()->analyze(
        'Explain the process of photosynthesis.',
        [
            'model' => 'qwen/qwen3.6-27b',
            'reasoning_format' => 'raw', // 'raw' (default), 'parsed', 'hidden'
            'temperature' => 0.6,
            'max_completion_tokens' => 10240
        ]
    );

    echo $response['choices'][0]['message']['content'];
    // Expected response structure (formatted):
    // {
    //   "choices": [
    //     { "message": { "role": "assistant", "content": "<think>Photosynthesis converts light...</think>\nPhotosynthesis is the process by which..." }, "finish_reason": "stop" }
    //   ],
    //   "usage": { "prompt_tokens": ..., "completion_tokens": ..., "total_tokens": ... }
    // }
} catch (\LucianoTonet\GroqPHP\GroqException $e) {
    echo "Error: " . $e->getMessage();
}

   $response = $groq->reasoning()->analyze(
       "Explain quantum entanglement.",
       [
            'model' => 'qwen/qwen3.6-27b',
           'reasoning_format' => 'raw'
       ]
   );
   // Response 

   $response = $groq->reasoning()->analyze(
       "Solve this math problem: 3x + 7 = 22",
       [
            'model' => 'qwen/qwen3.6-27b',
           'reasoning_format' => 'parsed'
       ]
   );
   // Response structure:
   // {
   //     "reasoning": "Step 1: Subtract 7 from both sides...",
   //     "content": "x = 5"
   // }
   

   $response = $groq->reasoning()->analyze(
       "What is the capital of France?",
       [
            'model' => 'qwen/qwen3.6-27b',
           'reasoning_format' => 'hidden'
       ]
   );
   // Response 

use LucianoTonet\GroqPHP\Groq;

$groq = new Groq(getenv('GROQ_API_KEY'));
$fileManager = $groq->files();

// Upload a file
$file = $fileManager->upload('path/to/your/file.jsonl', 'batch');

// List files
$files = $fileManager->list('batch', [
    'limit' => 10,
    'order' => 'desc'
]);

// Retrieve file info
$file = $fileManager->retrieve('file_id');

// Download file content
$content = $fileManager->download('file_id');

// Delete file
$fileManager->delete('file_id');

// Expected response structures (formatted):
// upload()    -> { "id": "file_abc123", "object": "file", "bytes": 1234, "filename": "file.jsonl", "purpose": "batch" }
// list()      -> { "object": "list", "data": [ { "id": "file_abc123", "filename": "file.jsonl" } ], "has_more": false }
// retrieve()  -> { "id": "file_abc123", "object": "file", "bytes": 1234, "filename": "file.jsonl", "purpose": "batch" }
// download()  -> raw file contents as a string

$batchManager = $groq->batches();

// Create a batch
$batch = $batchManager->create([
    'input_file_id' => 'file_id',
    'endpoint' => '/v1/chat/completions',
    'completion_window' => '24h',
    'metadata' => [
        'description' => 'Processing customer queries'
    ]
]);

// List batches
$batches = $batchManager->list([
    'limit' => 10,
    'order' => 'desc',
    'status' => 'completed'
]);

// Get batch status
$batch = $batchManager->retrieve('batch_id');
$summary = $batch->getSummary();

// Cancel batch
$batch = $batchManager->cancel('batch_id');

// Expected response structures (formatted):
// create()   -> { "id": "batch_abc123", "object": "batch", "status": "validating", "endpoint": "/v1/chat/completions", "completion_window": "24h" }
// list()     -> { "object": "list", "data": [ { "id": "batch_abc123", "status": "completed" } ], "has_more": false }
// retrieve() -> { "id": "batch_abc123", "status": "completed", "request_counts": { "total": 10, "completed": 10, "failed": 0 } }
// cancel()   -> { "id": "batch_abc123", "status": "cancelling" }
// getSummary() -> { "total": 10, "completed": 10, "failed": 0 }

try {
    // ... API call ...
} catch (\LucianoTonet\GroqPHP\GroqException $e) {
    echo "Groq Error: " . $e->getMessage() . "\n";
    echo "Type: " . $e->getType() . "\n";
    echo "Code: " . $e->getCode() . "\n";
    if ($e->getFailedGeneration()) {
        echo "Invalid JSON: " . $e->getFailedGeneration();
    }
}

// Output:
// Groq Error: Incorrect API key provided
// Type: authentication_error
// Code: 401

use LucianoTonet\GroqPHP\Groq;
use LucianoTonet\GroqPHP\BuiltInTools;

$groq = new Groq(getenv('GROQ_API_KEY'));

$response = $groq->chat()->completions()->create([
    'model' => 'compound-beta',
    'messages' => [
        ['role' => 'user', 'content' => 'What happened in AI last week?'],
    ],
    'compound_custom' => BuiltInTools::compound([
        BuiltInTools::WEB_SEARCH,
        BuiltInTools::CODE_INTERPRETER,
    ]),
    'search_settings' => ['exclude_domains' => ['wikipedia.org']],
]);

echo $response['choices'][0]['message']['content'];
// Expected response structure (formatted):
// {
//   "choices": [
//     { "message": { "role": "assistant", "content": "Last week's AI highlights 

use LucianoTonet\GroqPHP\BuiltInTools;

$response = $groq->chat()->completions()->create([
    'model' => 'llama-3.3-70b-versatile', // a model that supports documents
    'messages' => [
        ['role' => 'user', 'content' => 'Summarize the provided document'],
    ],
    'documents' => [
        BuiltInTools::document('Groq is a fast inference platform...', 'doc-1'),
    ],
    'citation_options' => 'enabled',
]);

echo $response['choices'][0]['message']['content'];
// Expected response structure (formatted):
// {
//   "choices": [
//     { "message": { "role": "assistant", "content": "Groq is a fast AI inference platform focused on low-latency LLM serving." }, "finish_reason": "stop" }
//   ],
//   "citations": [ { "document": "doc-1", "url": "...", "title": "..." } ]  // present when citation_options=enabled
// }

use LucianoTonet\GroqPHP\Groq;
use LucianoTonet\GroqPHP\Responses;

$groq = new Groq(getenv('GROQ_API_KEY'));

$response = $groq->responses()->create([
    'model' => 'openai/gpt-oss-120b',
    'input' => 'Tell me a fun fact about the moon in one sentence.',
]);

echo Responses::outputText($response);
// Hello from the Responses API.

$stream = $groq->responses()->create([
    'model' => 'openai/gpt-oss-120b',
    'input' => 'Tell me a short story.',
    'stream' => true,
]);

foreach ($stream->chunks() as $event) {
    if (($event['type'] ?? null) === 'response.output_text.delta') {
        echo $event['delta'];
    }
}

$response = $groq->responses()->create([
    'model' => 'openai/gpt-oss-120b',
    'input' => 'Extract product review information from the text.',
    'text' => [
        'format' => [
            'type' => 'json_schema',
            'name' => 'product_review',
            'schema' => [
                'type' => 'object',
                'properties' => ['product_name' => ['type' => 'string'], 'rating' => ['type' => 'number']],
                '

$response = $groq->chat()->completions()->create([
    'model' => 'openai/gpt-oss-120b',
    'messages' => [
        ['role' => 'system', 'content' => $longStaticSystemPrompt], // cached prefix
        ['role' => 'user', 'content' => $userQuestion],             // dynamic, at the end
    ],
]);

// Inspect cached tokens (populated when a cache hit occurs):
$cached = $response['usage']['prompt_tokens_details']['cached_tokens'] ?? 0;
echo "Cached input tokens: " . $cached;

use LucianoTonet\GroqPHP\Groq;

$groq = new Groq(getenv('GROQ_API_KEY'));

$screen = $groq->chat()->completions()->create([
    'model' => 'openai/gpt-oss-safeguard-20b',
    'messages' => [
        ['role' => 'user', 'content' => $userMessage],
    ],
]);

if (str_starts_with($screen['choices'][0]['message']['content'], 'unsafe')) {
    echo "Request blocked by content moderation.";
} else {
    // proceed with the real model
}
bash
composer 
bash
    export GROQ_API_KEY=your_key_here
    
bash
php -S 127.0.0.1:8000