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:
Step 2 - code
Step 3:
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.
Step 1
To obtain a Mistral API key, follow these steps:
- Create an Account: Visit Mistral AI's website and sign up for an account.
- Set Up Billing Information: After logging in, navigate to the Billing section and provide the necessary payment details to activate your account.
- 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".
- 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.
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: