PHP code example of helgesverre / mistral

1. Go to this page and download the library: Download helgesverre/mistral 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/ */

    

helgesverre / mistral example snippets


return [
    'api_key' => env('MISTRAL_API_KEY'),
    'base_url' => env('MISTRAL_BASE_URL'), // defaults to https://api.mistral.ai/v1 if null
    'timeout' => env('MISTRAL_TIMEOUT', 60),
];

use HelgeSverre\Mistral\Enums\Model;
use HelgeSverre\Mistral\Mistral;

// Instantiate the client
$mistral = new Mistral(apiKey: config('mistral.api_key'));

// Or use the Facade (Laravel)
Mistral::chat();
Mistral::simpleChat();
Mistral::embedding();
Mistral::models();

$completion = $mistral->chat()->createDto(
    messages: [['role' => 'user', 'content' => 'Hello!']],
    model: Model::small->value
);

$response = $mistral->simpleChat()->create(
    messages: [['role' => 'user', 'content' => 'Hello!']],
    model: Model::medium->value
);
echo $response->content; // Direct access to content

$embeddings = $mistral->embedding()->createDto([
    'Text to embed',
    'Another text'
]);

$models = $mistral->models()->listDto();
foreach ($models->data as $model) {
    echo $model->id;
}

$result = $mistral->ocr()->processUrlDto(
    url: 'https://example.com/document.pdf'
);

$completion = $mistral->fim()->createDto(
    model: 'codestral-latest',
    prompt: 'def fibonacci(',
    suffix: '    return result'
);

$transcription = $mistral->audio()->transcribeDto(
    filePath: '/path/to/audio.mp3',
    model: 'voxtral-small-latest'
);

use HelgeSverre\Mistral\Dto\Audio\SpeechRequest;
use HelgeSverre\Mistral\Enums\SpeechOutputFormat;

$dto = $mistral->audio()->speechDto(
    SpeechRequest::withVoice(
        input: 'Hello from PHP!',
        voiceId: 'alice',
        responseFormat: SpeechOutputFormat::MP3,
    )
);

$dto->saveTo('hello.mp3');

$moderation = $mistral->classifications()->moderateAsDto(
    model: 'mistral-moderation-latest',
    input: 'Text to moderate'
);

// Get Response object
$response = $mistral->models()->list();

// Or get typed DTO directly
/** @var \HelgeSverre\Mistral\Dto\Models\ModelList $models */
$models = $mistral->models()->listDto();

// Get Response object
$response = $mistral->embedding()->create([
    "A string here",
    "Another one here",
]);

// Or get typed DTO directly
/** @var EmbeddingResponse $embeddings */
$embeddings = $mistral->embedding()->createDto([
    "A string here",
    "Another one here",
]);

// Get Response object
$response = $mistral->chat()->create(
    messages: [
        [
            "role" => "user",
            "content" => "Write hello world in BASH",
        ]
    ],
    model: Model::medium->value,
    temperature: 0.4,
    maxTokens: 100,
    safeMode: false
);

// Or get typed DTO directly
/** @var ChatCompletionResponse $completion */
$completion = $mistral->chat()->createDto(
    messages: [
        [
            "role" => "user",
            "content" => "Write hello world in BASH",
        ]
    ],
    model: Model::medium->value,
    temperature: 0.4,
    maxTokens: 100,
    safeMode: false
);

$response = $this->mistral->chat()->create(
    messages: [
        [
            'role' => Role::user->value,
            'content' => 'What is the weather in Bergen, Norway?',
        ],
    ],
    model: Model::large->value,
    maxTokens: 1000,
    tools: [
        [
            'type' => 'function',
            'function' => [
                'name' => 'searchWeather',
                'description' => 'Get the weather for a location',
                'parameters' => [
                    'type' => 'object',
                    'ion about weather to a user',
                'parameters' => [
                    'type' => 'object',
                    'choices.0.message.tool_calls');
$response->json('choices.0.message.tool_calls.0.id');
$response->json('choices.0.message.tool_calls.0.type');
$response->json('choices.0.message.tool_calls.0.function');
$response->json('choices.0.message.tool_calls.0.function.name');
$response->json('choices.0.message.tool_calls.0.function.arguments');


// Or using the dto

/** @var ChatCompletionResponse $dto */
$dto = $response->dto();

$dto->choices; // array of ChatCompletionChoice

foreach ($dto->choices as $choice) {

    $choice->message; // ChatCompletionMessage

    foreach ($choice->message->toolCalls as $toolCall) {
        $toolCall->id; // null
        $toolCall->type; // function
        $toolCall->function; // FunctionCall
        $toolCall->function->name; // 'searchWeather'
        $toolCall->function->arguments; // '{"location":"Bergen, Norway"}'
        $toolCall->function->args(); // ['location' => 'Bergen, Norway']
    }
}

// Returns a generator, which you can iterate over to get the streamed chunks
$stream = $mistral->chat()->createStreamed(
    messages: [
        [
            'role' => 'user',
            'content' => 'Make a markdown list of 10 common fruits'
        ],
    ],
    model: Model::small->value,
);

foreach ($stream as $chunk) {

    /** @var StreamedChatCompletionResponse $chunk */

    echo $chunk->id; // 'cmpl-0339459d35cb441b9f111b94216cff97'
    echo $chunk->model; // 'mistral-small'
    echo $chunk->object; // 'chat.completion.chunk'
    echo $chunk->created; // DateTime

    foreach ($chunk->choices as $choice) {
        $choice->index; // 0
        $choice->delta->role; // 'assistant'
        $choice->delta->content; // 'Fruit list...'
        $choice->finishReason; // 'length'
    }
}

$response = $mistral->simpleChat()->create(
    messages: [
        [
            "role" => "user",
            "content" => "Hello world!",
        ],
    ],
    model: Model::medium->value,
    temperature: 0.4,
    maxTokens: 1500,
    safeMode: false
);

/** @var SimpleChatResponse $response */

// Returns a generator, which you can iterate over to get the streamed chunks
$response = $mistral->simpleChat()->stream(
    messages: [
        [
            'role' => "user",
            'content' => 'Say the word "banana"',
        ],
    ],
    maxTokens: 100,
);

foreach ($response as $chunk) {
    /** @var SimpleStreamChunk $chunk */

    $chunk->id;           // 'cmpl-716e95d336db4e51a04cbcf2b84d1a76'
    $chunk->model;        // 'mistral-medium'
    $chunk->object;       // 'chat.completion.chunk'
    $chunk->created;      // '2024-01-03 12:00:00'
    $chunk->role;         // 'assistant'
    $chunk->content;      // 'the text \n'
    $chunk->finishReason; // 'length'
}
bash
php artisan vendor:publish --tag="mistral-config"
bash
cd examples/01-getting-started
php getting-started.php