PHP code example of softcreatr / php-mistral-ai-sdk

1. Go to this page and download the library: Download softcreatr/php-mistral-ai-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

softcreatr / php-mistral-ai-sdk example snippets





use SoftCreatR\MistralAI\MistralAI;

$apiKey = 'your_api_key';

// Replace these lines with your chosen PSR-17 and PSR-18 compatible HTTP client and factories
$httpClient = new YourChosenHttpClient();
$requestFactory = new YourChosenRequestFactory();
$streamFactory = new YourChosenStreamFactory();
$uriFactory = new YourChosenUriFactory();

$mistral = new MistralAI($requestFactory, $streamFactory, $uriFactory, $httpClient, $apiKey);

$response = $mistral->createChatCompletion([
    'model' => 'mistral-tiny',
    'messages' => [
        [
            'role' => 'user',
            'content' => 'Who is the most renowned French painter?'
        ],
    ],
]);

// Process the API response
if ($response->getStatusCode() === 200) {
    $responseObj = json_decode($response->getBody()->getContents(), true);
    
    print_r($responseObj);
} else {
    echo "Error: " . $response->getStatusCode();
}

$streamCallback = static function ($data) {
    if (isset($data['choices'][0]['delta']['content'])) {
        echo $data['choices'][0]['delta']['content'];
    }
};

$mistral->createChatCompletion([
    'model' => 'mistral-small-latest',
    'messages' => [
        [
            'role' => 'user',
            'content' => 'Tell me a story about a brave knight.',
        ],
    ],
    'stream' => true,
], $streamCallback);