PHP code example of lucianotonet / groq-laravel

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


use LucianoTonet\GroqLaravel\Facades\Groq;

$response = Groq::chat()->create([
    'messages' => [
        ['role' => 'user', 'content' => 'Hello, how are you?']
    ]
]);

echo $response['choices'][0]['message']['content'];

$models = Groq::models()->list();

foreach ($models['data'] as $model) {
    echo $model['id'] . "\n";
}

$response = Groq::vision()->analyze(
    'path/to/image.jpg',
    'Describe this image'
);

echo $response['choices'][0]['message']['content'];

$response = Groq::audio()->transcribe('path/to/audio.mp3');
echo $response['text'];

// Upload file
$file = Groq::files()->upload('data.jsonl', 'batch');

// Create batch
$batch = Groq::batches()->create([
    'input_file_id' => $file->id,
    'endpoint' => '/v1/chat/completions'
]);

return [
    'api_key' => env('GROQ_API_KEY'),
    'model' => env('GROQ_MODEL', 'llama3-8b-8192'),
    'timeout' => env('GROQ_TIMEOUT', 30),
    
    'options' => [
        'temperature' => 0.7,
        'max_tokens' => 150,
        'top_p' => 1.0,
        'frequency_penalty' => 0,
        'presence_penalty' => 0,
    ],
    
    'cache' => [
        'enabled' => true,
        'ttl' => 3600,
    ],
];

Groq::setConfig([
    'model' => 'mixtral-8x7b',
    'temperature' => 0.9,
    'max_tokens' => 500
]);

use LucianoTonet\GroqPHP\GroqException;

try {
    $response = Groq::chat()->create([
        'messages' => [
            ['role' => 'user', 'content' => 'Hello!']
        ]
    ]);
} catch (GroqException $e) {
    echo "Error: " . $e->getMessage();
}

use LucianoTonet\GroqLaravel\Facades\Groq;

// ...

$imageUrl = 'https://example.com/image.jpg'; // Replace with your image URL
$prompt = 'Describe the image';

$response = Groq::vision()->analyze($imageUrl, $prompt);

$imageDescription = $response['choices'][0]['message']['content'];

// ... do something with the image description

use LucianoTonet\GroqLaravel\Facades\Groq;

// ...

$imagePath = '/path/to/your/image.jpg'; // Replace with the actual path
$prompt = 'What do you see in this image?';

$response = Groq::vision()->analyze($imagePath, $prompt);

$imageAnalysis = $response['choices'][0]['message']['content'];

// ... do something with the image analysis

use LucianoTonet\GroqLaravel\Facades\Groq;

// Basic transcription
$result = Groq::transcriptions()->create([
    'file' => storage_path('app/audio/recording.mp3'),
    'model' => 'whisper-large-v3'
]);

echo $result['text']; // Transcribed text from the audio

// Transcription with advanced options
$result = Groq::transcriptions()->create([
    'file' => storage_path('app/audio/recording.mp3'),
    'model' => 'whisper-large-v3',
    'language' => 'en', // Audio language (optional)
    'prompt' => 'Transcription of a business meeting', // Context to improve accuracy
    'temperature' => 0.3, // Lower randomness for more accuracy
    'response_format' => 'verbose_json' // Detailed format with timestamps
]);

// Now you have access to timestamps and segments
echo $result['text']; // Complete text
foreach ($result['segments'] as $segment) {
    echo "From {$segment['start']} to {$segment['end']}: {$segment['text']}\n";
}

use LucianoTonet\GroqLaravel\Facades\Groq;

// Basic translation (always to English)
$result = Groq::translations()->create([
    'file' => storage_path('app/audio/portuguese.mp3'),
    'model' => 'whisper-large-v3'
]);

echo $result['text']; // English text translated from the audio

// Translation with advanced options
$result = Groq::translations()->create([
    'file' => storage_path('app/audio/french.mp3'),
    'model' => 'whisper-large-v3',
    'prompt' => 'This is a business meeting', // Context in English
    'temperature' => 0.3, // Lower randomness for more accuracy
    'response_format' => 'verbose_json' // Detailed format with timestamps
]);

// Now you have access to timestamps and segments in English
echo $result['text']; // Complete text in English
foreach ($result['segments'] as $segment) {
    echo "From {$segment['start']} to {$segment['end']}: {$segment['text']}\n";
}

use LucianoTonet\GroqLaravel\Facades\Groq;

// Raw format - displays the entire reasoning process
$response = Groq::reasoning()->analyze('How to solve x^2 - 9 = 0?', [
    'model' => 'llama-3.1-8b-instant',
    'reasoning_format' => 'raw'
]);

echo $response['choices'][0]['message']['content'];
// Displays both the reasoning process and the answer

// Parsed format - separates reasoning from the final answer
$response = Groq::reasoning()->analyze('What is the capital of France?', [
    'model' => 'llama-3.1-70b-instant',
    'reasoning_format' => 'parsed'
]);

echo "Answer: " . $response['choices'][0]['message']['content'] . "\n";
echo "Reasoning: " . $response['choices'][0]['message']['reasoning'];
// Displays the direct answer (Paris) and the reasoning separately

// Hidden format - only the final answer
$response = Groq::reasoning()->analyze('Calculate the area of a circle with radius 5cm', [
    'model' => 'llama-3.1-8b-instant',
    'reasoning_format' => 'hidden'
]);

echo $response['choices'][0]['message']['content'];
// Displays only the final answer, without the reasoning process

use LucianoTonet\GroqLaravel\Facades\Groq;

// Completions with image
$response = Groq::completions()->create([
    'model' => 'llava-v1.5-7b-4096-preview',
    'messages' => [
        [
            'role' => 'user',
            'content' => [
                ['type' => 'text', 'text' => 'What is in this image?'],
                [
                    'type' => 'image_url',
                    'image_url' => [
                        'url' => 'https://example.com/image.jpg'
                    ]
                ]
            ]
        ]
    ]
]);

echo $response['choices'][0]['message']['content'];

// Completions with streaming
$stream = Groq::completions()->create([
    'model' => 'llama-3.1-8b-instant',
    'messages' => [
        ['role' => 'user', 'content' => 'Tell a short story about a robot']
    ],
    'stream' => true
]);

// Process the response in stream (useful for real-time interfaces)
foreach ($stream->chunks() as $chunk) {
    if (isset($chunk['choices'][0]['delta']['content'])) {
        echo $chunk['choices'][0]['delta']['content'];
        // Send to client in real-time (in real applications)
        ob_flush();
        flush();
    }
}

use LucianoTonet\GroqLaravel\Facades\Groq;

// List files
$files = Groq::files()->list();

// Upload a file
$file = Groq::files()->upload(storage_path('app/data/document.txt'), 'assistants');

// Retrieve file information
$fileInfo = Groq::files()->retrieve($file['id']);

// Delete a file
Groq::files()->delete($file['id']);
bash
php artisan vendor:publish --provider="LucianoTonet\GroqLaravel\GroqServiceProvider"
bash
vendor/bin/phpunit tests/Feature/GroqTest.php
bash
vendor/bin/phpunit tests/Feature/GroqIntegrationTest.php
bash
   vendor/bin/phpunit ./tests/Feature/FacadeTest.php