How to use Grok API (X.ai) with PHP the easy way (function)

Perry

Administrator
Staff member
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

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:
A small review of Grok from x.ai.

- Grok is fast, which is particularly noticeable when handling complex tasks or generating extended responses. This speed alone makes it a nice to use for quick iterations or brainstorming sessions.
- One of the more intriguing aspects is its less strict moderation. While OpenAI's moderation has become much looser recently, Grok pushes the boundaries even further. This is particularly evident in image moderation, where Grok seems to apply significantly fewer restrictions compared to OpenAI.
- When it comes to coding, Grok shines. Its performance feels distinctively different from OpenAI, offering a fresh perspective or approach to solving problems. Whether it's debugging or writing code from scratch, it often delivers impressive results.
- Grok x.ai feels different f you’re looking for something that diverges slightly from the OpenAI experience.
 
Generated the post above with Grok (not the API but anyway), and yea, it's different. Not like ChatGPT:

Here's your review of Grok x.ai, now with an extra dash of flair:

A Whirlwind Waltz with Grok x.ai:
  • Speed of Light: Grok is like a rocket blasting off in the digital cosmos, delivering answers at breakneck speed. It's the kind of AI that makes you wonder if it's got a secret stash of caffeine or just pure, unadulterated computational magic.
  • Moderation with Moxie: In a world where moderation can feel like the tight grip of a Victorian corset, Grok opts for the relaxed fit of a Hawaiian shirt. OpenAI might have loosened the laces, but Grok has practically torn them off, especially in the realm of image moderation where it dances to a more liberal beat.
  • Coding with a Twist: When it comes to coding, Grok doesn't just follow the recipe; it improvises like a jazz musician. It's not just about getting the job done; it's about doing it with a style that feels uniquely its own, setting it apart from the more conventional tunes played by OpenAI.
Btw, did not pass https://quillbot.com/ai-content-detector despite it's a unique experience.
 
To Grok prompt: Explain this code with some flair.

Alright, buckle up, young padawan, as we dive into the magical world of PHP and APIs with a touch of flair! Here's your code, explained in a way that's easy to grok:

Step 1: Setting Up the Key
php
$grokApiKey = 'xai-example...';
global $grokApiKey;

  • What's this?: Here, we're setting up and declaring a global variable called $grokApiKey. This key is like your VIP pass to the Grok API party. It's secret, so don't share it with anyone!

Step 2: The Grok API Function

PHP:
function callGrokAPI($model = 'grok-beta', $messages = [], $temperature = 0, $stream = false) {
    global $grokApiKey;

    $url = '[URL='https://api.x.ai/v1/chat/completions%27;']https://api.x.ai/v1/chat/completions';[/URL]
 
    $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];
    }
}

  • What's happening?: We've created a function named callGrokAPI. It's like sending a magical owl with your request to the Grok API:
    • Parameters: You can tweak the model, messages, temperature, and whether to stream the response.
    • curl: This is the magic wand for making HTTP requests. We're setting up a POST request with our data, encoded in JSON, and sending it off with our authentication headers.
    • Return: If everything goes well (HTTP 200), it returns the content of the response. If not, it sends back an error message.

Step 3: Preparing the Message

PHP:
$messages = [
    [
        'role' => 'system',
        'content' => 'You are a test assistant.'
    ],
    [
        'role' => 'user',
        'content' => 'what do you think about elon musk'
    ]
];
  • What's this?: Here, we're crafting our message. It's like writing a letter:
    • One part tells the AI what role to play (system message).
    • The other part is your query (user message).
Step 4: Calling the API and Echoing the Result
php

$content = callGrokAPI('grok-2-latest', $messages, 0, false);
echo $content;
  • What's happening?: We're calling our function with specific parameters and then echoing whatever comes back. It's like opening the reply from the magical owl and reading it out loud!
And there you have it, a journey through PHP land with a sprinkle of fun! Remember, with great power (API keys) comes great responsibility. Use wisely!
 
Back
Top