How to use Mistral API with PHP

Perry

Administrator
Staff member
ChatGPT, Le chat and other AI chats have a very annoying habit of using old coding practices and skipping the part where you get the actually AI-generated content back. Instead, it often returns the whole JSON array with 10+ quite meaningless details.

Step 1

To obtain a Mistral API key, follow these steps:
  1. Create an Account: Visit Mistral AI's website and sign up for an account.
  2. Set Up Billing Information: After logging in, navigate to the Billing section and provide the necessary payment details to activate your account.
  3. Generate API Key:
    • Go to the API Keys page.
    • Click on "Create new key".
    • Optionally, assign a name and set an expiration date for the key.
    • Click "Create key".
  4. Secure Your API Key: Once generated, copy the API key immediately, as it will not be displayed again for security reasons. Store it securely and avoid sharing it with others.
So here's my modified and tested PHP code to access the Mistral API and extract just the AI-generated content you need:

Step 2 - code
PHP:
$mistralKey = "you api key get one from https://console.mistral.ai/";

// API endpoint ex  mistral-small-latest - mistral-large-latest
function mistralApiRequest($model, $temperature, $systemPrompt, $message) {

    global $mistralKey;

    // Define the API endpoint
    $apiUrl = 'https://api.mistral.ai/v1/chat/completions'; // Replace with the actual Mistral API endpoint

    // Prepare the request data
    $data = [
        'model' => $model,
        'temperature' => $temperature,
        'messages' => [
            [
                'role' => 'system',
                'content' => $systemPrompt
            ],
            [
                'role' => 'user',
                'content' => $message
            ]
        ],
        'safe_prompt' => false,
        'stream' => false,
        'presence_penalty' => 0,
        'frequency_penalty' => 0,
        'top_p' => 1
    ];

    // Initialize cURL session
    $ch = curl_init($apiUrl);

    // Set cURL options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $mistralKey
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

    // Execute the request
    $response = curl_exec($ch);

    // Check for cURL errors
    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        curl_close($ch);
        throw new Exception('cURL error: ' . $error_msg);
    }

    // Close the cURL session
    curl_close($ch);

    // Decode the JSON response
    $responseData = json_decode($response, true);

    // Check for API errors
    if (isset($responseData['error'])) {
      //  mail("you email", "Mistral API Error", "EXIT. \n\nSystem promt: $systemPrompt. \n\n Mistral API Error: " . $responseData['error']);
 
        throw new Exception('API error: ' . $responseData['error']);
    }

  // Extract and return AI text
  if (isset($responseData['choices']) && !empty($responseData['choices'])) {
        $firstChoice = $responseData['choices'][0];
        if (isset($firstChoice['message']['content'])) {
            return $firstChoice['message']['content'];
        } else {
            throw new Exception('No content found in the first choice.');
        }
    } else {
         print_r($responseData);
         // mail("you email", "Mistral response Error, "EXIT. \n\nSystem promt: $systemPrompt. \n\n Mistral response Error: " . $response);
 
        throw new Exception('No responses found in the API response.');
    }
} // end mistralApiRequest

Step 3:

PHP:
<?php

// Define the parameters for the API request
$model = "mistral-large-latest"; // Replace with the desired model
$temperature = 0.7; // Adjust the temperature as needed
$systemPrompt = "You are a helpful assistant.";
$userMessage = "What is the capital of France?";

try {
    // Call the function
    $response = mistralApiRequest($model, $temperature, $systemPrompt, $userMessage);

    // Output the response
    echo "AI Response: " . $response;
} catch (Exception $e) {
    // Handle any exceptions
    echo "Error: " . $e->getMessage();
}
?>


What is the Mistral API?​

Mistral AI provides a cutting-edge platform for language model APIs, similar to OpenAI's GPT models. Their API allows developers to integrate advanced natural language processing capabilities into their applications, such as generating text, answering questions, or assisting with creative writing tasks.

The Mistral API focuses on performance and accessibility, offering lightweight and efficient models designed to deliver high-quality results in a wide range of use cases.
 
Last edited:
Explanation of the Mistral API Request Function (generated with Mistrals Le chat btw, it's like ChatGPT)

This code defines a function to make a request to the Mistral API, which is likely an AI service that generates text based on given inputs. Below is a step-by-step explanation of what the code does:

API Key
Code:
$mistralKey = "you api key get one from https://console.mistral.ai/";
This line sets the API key needed to authenticate requests to the Mistral API. You should replace "you api key get one from https://console.mistral.ai/" with your actual API key.

Function Definition
Code:
function mistralApiRequest($model, $temperature, $systemPrompt, $message) {
This defines a function named mistralApiRequest that takes four parameters:
- $model: The model to use for the API request.
- $temperature: A parameter that controls the randomness of the output.
- $systemPrompt: A system message that sets the context for the AI.
- $message: The user's message that the AI will respond to.

Global Variable
Code:
global $mistralKey;
This line makes the $mistralKey variable available inside the function. This variable contains the API key needed to authenticate the request.

API Endpoint
Code:
$apiUrl = 'https://api.mistral.ai/v1/chat/completions';
This sets the URL for the Mistral API endpoint.

Prepare Request Data
Code:
$data = [
    'model' => $model,
    'temperature' => $temperature,
    'messages' => [
        [
            'role' => 'system',
            'content' => $systemPrompt
        ],
        [
            'role' => 'user',
            'content' => $message
        ]
    ],
    'safe_prompt' => false,
    'stream' => false,
    'presence_penalty' => 0,
    'frequency_penalty' => 0,
    'top_p' => 1
];
This creates an array $data that contains all the necessary information for the API request, including the model, temperature, messages, and other parameters.

Initialize cURL Session
Code:
$ch = curl_init($apiUrl);
This initializes a cURL session to make the HTTP request to the API endpoint.

Set cURL Options
Code:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $mistralKey
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
These lines set various options for the cURL session:
- CURLOPT_RETURNTRANSFER: Makes cURL return the response as a string.
- CURLOPT_HTTPHEADER: Sets the HTTP headers, including the content type and authorization.
- CURLOPT_POST: Specifies that the request is a POST request.
- CURLOPT_POSTFIELDS: Sets the data to be sent with the POST request, encoded as JSON.

Execute the Request
Code:
$response = curl_exec($ch);
This executes the cURL request and stores the response in the $response variable.

Check for cURL Errors
Code:
if (curl_errno($ch)) {
    $error_msg = curl_error($ch);
    curl_close($ch);
    throw new Exception('cURL error: ' . $error_msg);
}
This checks if there were any errors during the cURL execution and throws an exception if there were.

Close the cURL Session
Code:
curl_close($ch);
This closes the cURL session.

Decode the JSON Response
Code:
$responseData = json_decode($response, true);
This decodes the JSON response into a PHP array.

Check for API Errors
Code:
if (isset($responseData['error'])) {
    // mail("you email", "Mistral API Error", "EXIT. \n\nSystem promt: $systemPrompt. \n\n Mistral API Error: " . $responseData['error']);
    throw new Exception('API error: ' . $responseData['error']);
}
This checks if the API response contains an error and throws an exception if it does. The email notification part is commented out.

Extract and Return the Content
Code:
if (isset($responseData['choices']) && !empty($responseData['choices'])) {
    $firstChoice = $responseData['choices'][0];
    if (isset($firstChoice['message']['content'])) {
        return $firstChoice['message']['content'];
    } else {
        throw new Exception('No content found in the first choice.');
    }
} else {
    print_r($responseData);
    // mail("you email", "Mistral response Error, "EXIT. \n\nSystem promt: $systemPrompt. \n\n Mistral response Error: " . $response);
    throw new Exception('No responses found in the API response.');
}
This checks if the API response contains any choices (responses) and returns the content of the first choice. If no content is found, it throws an exception. If no choices are found, it throws an exception. The email notification part is commented out.

End of Function
Code:
}
This marks the end of the function.

Summary
This function sends a request to the Mistral API with the given parameters, handles the response, and returns the content of the first choice if available. It also handles errors by throwing exceptions. The email notification parts are commented out, so you can uncomment and customize them if needed.
 
Exploring the use of Mistral API with PHP can open up a world of possibilities for developers! If you're interested in streamlining your code even further, you might want to look into using PHP libraries like Guzzle for handling HTTP requests. It could simplify the cURL setup we have here and make your code more readable and maintainable.

Also, if you're worried about those pesky API limits and want to optimize your calls, consider implementing some form of caching. Storing responses temporarily can save you from hitting the API every time for the same queries.

What do you think about adding these tweaks? Any other ideas on how we could improve our Mistral API interactions?
 
Back
Top