Groq has some interesting things going on.
Here's how to use their API with a PHP function
Call the function:
- It's API is free to use, and have the lowest cost if you're a high usage customer.
- It's the fastest AI API on the Market.
- Built on open-source models like Meta AI Llama.
Here's how to use their API with a PHP function
PHP:
$groqApiKey = "you_key";
// models https://console.groq.com/docs/models
// llama3-8b-8192 - llama3-70b-8192 - gemma-7b-it (8k)
// llama-3.3-70b-versatile - llama-3.3-70b-specdec
function queryGroqAPI($message, $systemMessage, $tokens, $model, $temp = 0) {
global $groqApiKey;
$payload = [
'messages' => [
['role' => 'system', 'content' => $systemMessage],
['role' => 'user', 'content' => $message]
],
'model' => $model,
'temperature' => $temp,
'top_p' => 1,
'stream' => false
// 'stop' => ["\n\n"] // Updated stopping condition
];
if (!empty($tokens)) {
$payload['max_tokens'] = $tokens;
}
$ch = curl_init('https://api.groq.com/openai/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $groqApiKey
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode != 200) {
echo "Groq HTTP Error: Received status code {$httpCode} <br> Prompt $message";
print_r($response);
exit();
}
$decodedResponse = json_decode($response, true);
if (isset($decodedResponse['error'])) {
echo 'Groq API Error: ' . $decodedResponse['error']['message'].'<br> Prompt: '.$message.'<br>';
print_r($decodedResponse);
exit();
}
// Extract the content from the response array
$content = $decodedResponse['choices'][0]['message']['content'];
return $content;
}
Call the function:
PHP:
// Example inputs
$message = "What is the capital of France?";
$systemMessage = "You are a helpful assistant.";
$tokens = 100; // Set the token limit
$model = "llama-3.3-70b-versatile"; // Specify the model
$temp = 0.7; // Set temperature for variability
// Call the function
$response = queryGroqAPI($message, $systemMessage, $tokens, $model, $temp);
// Output the response
echo "Response from Groq API: " . $response;