ChatGPT has a very annoying habit to use old code practices and, and skip the part where you get the actual AI-content back. So here's my modified and tested PHP code to access Grok API from https://x.ai.
I always come back to php functions like this for every project, so I will keep this thread my goto page for X API.
Get you API-key here: https://x.ai/api
I always come back to php functions like this for every project, so I will keep this thread my goto page for X API.
Get you API-key here: https://x.ai/api
PHP:
$grokApiKey = 'xai-example...';
global $grokApiKey;
function callGrokAPI($model = 'grok-beta', $messages = [], $temperature = 0, $stream = false) {
global $grokApiKey;
$url = 'https://api.x.ai/v1/chat/completions';
$data = [
'model' => $model,
'messages' => $messages,
'stream' => $stream,
'temperature' => $temperature
];
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $grokApiKey
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
$decodedResponse = json_decode($response, true);
return $decodedResponse['choices'][0]['message']['content'];
} else {
return ['error' => 'API call failed with HTTP code: ' . $httpCode, 'response' => $response];
}
}
// call the function
$messages = [
[
'role' => 'system',
'content' => 'You are a test assistant.'
],
[
'role' => 'user',
'content' => 'what do you think about elon musk'
]
];
$content = callGrokAPI('grok-2-latest', $messages, 0, false);
echo $content;
Last edited: