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


use LucianoTonet\GroqPHP\Groq;

$groq = new Groq();

$groq = new Groq('your_key_here');

$groq = new Groq([
    'apiKey' => 'your_key_here',
    'temperature' => 0.5,
    // ...
]);

$groq = new Groq();

$groq->setConfig([
    'apiKey' => 'another_key_here',
    'max_tokens' => 1024,
    // ...
]);

$models = $groq->models()->list();

foreach ($models['data'] as $model) {
    echo 'Model ID: ' . $model['id'] . PHP_EOL;
    echo 'Developer: ' . $model['owned_by'] . PHP_EOL;
    echo 'Context Window: ' . $model['context_window'] . PHP_EOL;
}

$response = $groq->chat()->completions()->create([
    'model' => 'llama3-8b-8192',
    'messages' => [
        [
            'role' => 'user',
            'content' => 'Explain the importance of low latency LLMs'
        ]
    ],
]);

echo $response['choices'][0]['message']['content']; // "Low latency LLMs are important because ..."

$response = $groq->chat()->completions()->create([
    'model' => 'mixtral-8x7b-32768',
    'messages' => [
        [
            'role' => 'user',
            'content' => $message
        ]
    ],
    'stream' => true
]);

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

$tools = [
    [
        "type" => "function",
        "function" => [
            "name" => "calendar_tool",
            "description" => "Gets the current time in a specific format.",
            "parameters" => [
                "type" => "object",
                "properties" => [
                    "format" => [
                        "type" => "string",
                        "description" => "The format of the time to return."
                    ],
                ],
                "et weather information."
                    ],
                ],
                "exists($function_name)) {
        $function_response = $function_name($function_args);
    } else {
        $function_response = "Function $function_name not defined.";
    }

    $messages[] = [
        'tool_call_id' => $tool_call['id'],
        'role' => 'tool',
        'name' => $function_name,
        'content' => $function_response,
    ];
}

// Build final response...
$response = $groq->chat()->completions()->create([
    'model' => 'mixtral-8x7b-32768',
    'messages' => $messages
]);


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

use LucianoTonet\GroqPHP\GroqException;

try {
    $response = $groq->chat()->completions()->create([
        'model' => 'mixtral-8x7b-32768',
        'messages' => [
            [
                'role' => 'system',
                'content' => "You are an API and shall respond only with valid JSON.",
            ],
            [
                'role' => 'user',
                'content' => 'Explain the importance of low latency LLMs',
            ],
        ],
        'response_format' => ['type' => 'json_object']
    ]);

    $jsonResponse = json_decode($response['choices'][0]['message']['content'], true);

    // Accessing the JSON response
    print_r($jsonResponse); 

} catch (GroqException $err) {
    echo $err->getCode() . "<br>"; 
    echo $err->getMessage() . "<br>";    
    echo $err->getType() . "<br>";           

    if($err->getFailedGeneration()) {
        print_r($err->getFailedGeneration());
    }
}

$transcription = $groq->audio()->transcriptions()->create([
    'file' => '/path/to/audio/file.mp3',
    'model' => 'whisper-large-v3',
    'response_format' => 'json',
    'language' => 'en',
    'prompt' => 'Optional transcription prompt'
]);

echo json_encode($transcription, JSON_PRETTY_PRINT);

$translation = $groq->audio()->translations()->create([
    'file' => '/path/to/audio/file.mp3',
    'model' => 'whisper-large-v3',
    'response_format' => 'json',
    'prompt' => 'Optional translation prompt'
]);

echo json_encode($translation, JSON_PRETTY_PRINT);

$analysis = $groq->vision()->analyze('/path/to/your/image.jpg', 'Describe this image');

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

use LucianoTonet\GroqPHP\GroqException;

try {
    $response = $groq->chat()->completions()->create([
        'model' => 'mixtral-8x7b-32768',
        'messages' => [
            [
                'role' => 'user',
                'content' => 'Hello, world!'
            ]
        ]
    ]);
} catch (GroqException $err) {
    echo "<strong>Error code:</strong> " . $err->getCode() . "<br>"; // e.g., 400
    echo "<strong>Message:</strong> " . $err->getMessage() . "<br>";    // Detailed error description
    echo "<strong>Type:</strong> " . $err->getType() . "<br>";           // e.g., invalid_request_error
    echo "<strong>Headers:</strong><br>"; 
    print_r($err->getHeaders()); // ['server' => 'nginx', ...]
}

$groq = new Groq([
    'timeout' => 20 * 1000, // 20 seconds
]);

$groq->chat()->completions()->create([
    'model' => 'mixtral-8x7b-32768',
    'messages' => [
        [
            'role' => 'user',
            'content' => 'Hello, world!'
        ]
    ],
], ['timeout' => 5 * 1000]); // 5 seconds
bash
composer