The Mistral.ai Laravel Client enables laravel applications to interact with the Mistral.ai API, providing straightforward access to features like chat completions and text embeddings.
Get your API key at console.mistral.ai.
You can install the package via composer:
composer require helgesverre/mistralYou can publish the config file with:
php artisan vendor:publish --tag="mistral-config"This is the contents of the published config file:
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),
];Create an instance of the Mistral client to start interacting with the API. This instance will be your primary interface for sending requests to Mistral.AI.
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();The package includes 12 hands-on examples in the examples/ directory, each with detailed documentation, working code, and explanations. These examples are the fastest way to learn the SDK and see it in action.
Quick Start: Begin with 01-getting-started to set up your first working integration.
| Example | Description |
|---|---|
| 01-getting-started | Install the SDK, configure authentication, and make your first API call |
| 02-basic-chat | Learn chat completions, system messages, and multi-turn conversations |
| 03-chat-parameters | Master temperature, top_p, max_tokens, and other generation parameters |
| 04-streaming-chat | Implement real-time streaming responses with Server-Sent Events |
| 05-function-calling | Enable AI to call PHP functions and interact with your application |
| 06-embeddings | Generate vector embeddings for semantic search and similarity matching |
| 07-ocr | Extract and process text from images and documents using OCR |
| 08-audio | Transcribe audio files with support for multiple languages and formats |
| 09-moderation | Identify and filter inappropriate content with content moderation |
| 10-error-handling | Implement robust error handling, retry logic, and rate limit management |
| 11-speech | Generate spoken audio from text with preset or custom voices |
| 12-voices | Manage custom voices — create from a sample, list, update, delete |
Each example includes:
- Step-by-step implementation guide
- Complete working code
- Real-world use cases
- Troubleshooting tips
- Links to related examples
To run an example:
cd examples/01-getting-started
php getting-started.phpThe Mistral PHP client provides 14 resource classes. Most resources offer both Response-returning methods and typed DTO convenience methods; where omitted, you can still call ->dto() on the Response.
Access via $mistral->chat()
Methods:
create(...): Response - Create a chat completioncreateDto(...): ChatCompletionResponse - Create a chat completion and return typed DTOcreateStreamed(...): Generator - Stream chat completions
Example:
$completion = $mistral->chat()->createDto(
messages: [['role' => 'user', 'content' => 'Hello!']],
model: Model::small->value
);Access via $mistral->simpleChat()
Methods:
create(...): SimpleChatResponse - Simplified chat completion (returns flattened DTO directly)stream(...): Generator - Stream simplified chat completions
Example:
$response = $mistral->simpleChat()->create(
messages: [['role' => 'user', 'content' => 'Hello!']],
model: Model::medium->value
);
echo $response->content; // Direct access to contentAccess via $mistral->embedding()
Methods:
create(array $input, ...): Response - Create embeddingscreateDto(array $input, ...): EmbeddingResponse - Create embeddings and return typed DTO
Example:
$embeddings = $mistral->embedding()->createDto([
'Text to embed',
'Another text'
]);Access via $mistral->models()
Methods:
list(): Response - List available modelslistDto(): ModelList - List models and return typed DTOretrieve(string $modelId): BaseModelCard|FTModelCard - Get model detailsdelete(string $modelId): DeleteModelOut - Delete a fine-tuned model
Example:
$models = $mistral->models()->listDto();
foreach ($models->data as $model) {
echo $model->id;
}Access via $mistral->ocr()
Methods:
process(...): Response - Process document with OCRprocessDto(...): OCRResponse - Process and return typed DTOprocessUrl(string $url, ...): Response - Process document from URLprocessUrlDto(string $url, ...): OCRResponse - Process URL and return typed DTOprocessBase64(string $base64, ...): Response - Process base64 encoded documentprocessBase64Dto(string $base64, ...): OCRResponse - Process base64 and return typed DTO
Example:
$result = $mistral->ocr()->processUrlDto(
url: 'https://example.com/document.pdf'
);Access via $mistral->fim()
Methods:
create(...): Response - Create FIM completioncreateDto(...): FIMCompletionResponse - Create and return typed DTOcreateStreamed(...): Generator - Stream FIM completions
Example:
$completion = $mistral->fim()->createDto(
model: 'codestral-latest',
prompt: 'def fibonacci(',
suffix: ' return result'
);Access via $mistral->agents()
Methods:
create(AgentCreationRequest $request): Response - Create an agentcreateDto(AgentCreationRequest $request): Agent - Create and return typed DTOlist(?int $page, ?int $pageSize): Response - List agentslistDto(?int $page, ?int $pageSize): AgentList - List and return typed DTOget(string $agentId): Response - Get agent detailsgetDto(string $agentId): Agent - Get agent and return typed DTOupdate(string $agentId, AgentUpdateRequest $request): Response - Update agentupdateDto(string $agentId, AgentUpdateRequest $request): Agent - Update and return typed DTOupdateVersion(string $agentId, int $version): Response - Switch agent versionupdateVersionDto(string $agentId, int $version): Agent - Switch version and return typed DTOlistVersions(string $agentId, ?int $page, ?int $pageSize): Response - List all versions of an agentlistVersionsDto(...): DataCollection<Agent> - List versions and return typed DTO collectiongetVersion(string $agentId, int $version): Response - Get a specific agent versiongetVersionDto(string $agentId, int $version): Agent - Get version and return typed DTOlistAliases(string $agentId): Response - List all aliases for an agentlistAliasesDto(string $agentId): DataCollection<AgentAliasResponse> - List aliases and return typed DTO collectioncreateAlias(string $agentId, string $alias, int $version): Response - Create or update an alias (idempotent PUT)createAliasDto(...): AgentAliasResponse - Create/update alias and return typed DTOdeleteAlias(string $agentId, string $alias): Response - Delete an alias (204 No Content)
Access via $mistral->conversations()
Methods:
create(ConversationRequest $request): Response - Create conversationcreateDto(ConversationRequest $request): ConversationResponse - Create and return typed DTOcreateStreamed(ConversationRequest $request): Generator - Create with streaminglist(?int $page, ?int $pageSize, ?string $order): Response - List conversationslistDto(...): ConversationList - List and return typed DTOget(string $conversationId): Response - Get conversationgetDto(string $conversationId): ConversationResponse - Get and return typed DTOappend(string $conversationId, ConversationAppendRequest $request): Response - Append to conversationappendDto(...): ConversationResponse - Append and return typed DTOappendStreamed(...): Generator - Append with streaminggetHistory(string $conversationId): Response - Get conversation historygetHistoryDto(string $conversationId): ConversationHistory - Get history and return typed DTOgetMessages(string $conversationId): Response - Get conversation messagesgetMessagesDto(string $conversationId): ConversationMessages - Get messages and return typed DTOrestart(string $conversationId, ConversationRestartRequest $request): Response - Restart conversationrestartDto(...): ConversationResponse - Restart and return typed DTOrestartStreamed(...): Generator - Restart with streaming
Access via $mistral->audio()
Methods:
Transcription (speech-to-text):
transcribe(string $filePath, ...): Response - Transcribe audiotranscribeDto(string $filePath, ...): TranscriptionResponse - Transcribe and return typed DTOtranscribeStreamed(string $filePath, ...): Generator - Transcribe with streaming
Speech (text-to-speech):
speech(SpeechRequest $request): Response - Generate speech audiospeechDto(SpeechRequest $request): SpeechResponse - Generate speech and return typed DTO (base64 audio +decoded()/saveTo()helpers)speechStreamed(SpeechRequest $request): Generator - Stream audio chunks (SpeechStreamAudioDelta+ finalSpeechStreamDone)
Voices:
listVoices(?int $limit, ?int $offset): Response - List voices (paginated)listVoicesDto(...): VoiceListResponsecreateVoice(VoiceCreateRequest $request): Response - Create a custom voice (useVoiceCreateRequest::fromFile()to load + base64 a local file)createVoiceDto(...): VoiceResponsegetVoice(string $voiceId): Response - Get a voicegetVoiceDto(string $voiceId): VoiceResponseupdateVoice(string $voiceId, VoiceUpdateRequest $request): Response - Update voice metadataupdateVoiceDto(...): VoiceResponsedeleteVoice(string $voiceId): Response - Delete a custom voice (returns the deleted voice)deleteVoiceDto(string $voiceId): VoiceResponsegetVoiceSample(string $voiceId): Response - Download the rawaudio/wavsample for a voice
Example — transcription:
$transcription = $mistral->audio()->transcribeDto(
filePath: '/path/to/audio.mp3',
model: 'voxtral-small-latest'
);Example — text-to-speech:
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');Access via $mistral->files()
Methods:
upload(string $filePath, ?FilePurpose $purpose): Response - Upload fileuploadDto(...): UploadFileOut - Upload and return typed DTOlist(...): Response - List files with filterslistDto(...): ListFilesOut - List and return typed DTOretrieve(string $fileId): Response - Get file metadataretrieveDto(string $fileId): RetrieveFileOut - Get metadata and return typed DTOdelete(string $fileId): Response - Delete filedeleteDto(string $fileId): DeleteFileOut - Delete and return typed DTOdownload(string $fileId): Response - Download file contentgetSignedUrl(string $fileId, ?int $expiry): Response - Get signed download URLgetSignedUrlDto(string $fileId, ?int $expiry): FileSignedURL - Get URL and return typed DTO
Access via $mistral->fineTuning()
Methods:
list(...): Response - List fine-tuning jobslistAsDto(...): JobsOut - List and return typed DTOcreate(JobIn $jobIn, ?bool $dryRun): Response - Create fine-tuning jobcreateAsDto(JobIn $jobIn, ?bool $dryRun): CompletionJobOut|ClassifierJobOut|LegacyJobMetadataOutget(string $jobId): Response - Get job detailsgetAsDto(string $jobId): CompletionDetailedJobOut|ClassifierDetailedJobOutcancel(string $jobId): Response - Cancel jobcancelAsDto(string $jobId): CompletionDetailedJobOut|ClassifierDetailedJobOutstart(string $jobId): Response - Start validated jobstartAsDto(string $jobId): CompletionDetailedJobOut|ClassifierDetailedJobOutupdateModel(string $modelId, UpdateFTModelIn $update): Response - Update model metadataupdateModelAsDto(...): CompletionFTModelOut|ClassifierFTModelOutarchiveModel(string $modelId): Response - Archive modelarchiveModelAsDto(string $modelId): ArchiveFTModelOutunarchiveModel(string $modelId): Response - Unarchive modelunarchiveModelAsDto(string $modelId): UnarchiveFTModelOut
Access via $mistral->batch()
Methods:
list(...): Response - List batch jobslistAsDto(...): BatchJobsOut - List and return typed DTOcreate(BatchJobIn $batchJobIn): Response - Create batch jobcreateAsDto(BatchJobIn $batchJobIn): BatchJobOut - Create and return typed DTOget(string $jobId): Response - Get batch job detailsgetAsDto(string $jobId): BatchJobOut - Get and return typed DTOcancel(string $jobId): Response - Cancel batch jobcancelAsDto(string $jobId): BatchJobOut - Cancel and return typed DTO
Access via $mistral->classifications()
Methods:
moderate(string $model, string|array $input): Response - Moderate contentmoderateAsDto(string $model, string|array $input): ModerationResponse - Moderate and return typed DTOmoderateChat(string $model, array $input): Response - Moderate chat messagesmoderateChatAsDto(string $model, array $input): ModerationResponse - Moderate chat and return typed DTOclassify(string $model, string|array $input): Response - Classify contentclassifyAsDto(string $model, string|array $input): ClassificationResponse - Classify and return typed DTOclassifyChat(string $model, array $messages): Response - Classify chatclassifyChatAsDto(string $model, array $messages): ClassificationResponse - Classify chat and return typed DTO
Example:
$moderation = $mistral->classifications()->moderateAsDto(
model: 'mistral-moderation-latest',
input: 'Text to moderate'
);Access via $mistral->libraries()
Methods:
list(?int $page, ?int $pageSize): Response - List librariescreate(LibraryIn $library): Response - Create libraryget(string $libraryId): Response - Get library detailsupdate(string $libraryId, LibraryInUpdate $library): Response - Update librarydelete(string $libraryId): Response - Delete librarylistDocuments(string $libraryId, ...): Response - List documents in libraryuploadDocument(string $libraryId, string $filePath): Response - Upload documentgetDocument(string $libraryId, string $documentId): Response - Get document detailsupdateDocument(string $libraryId, string $documentId, DocumentUpdateIn $update): Response - Update documentdeleteDocument(string $libraryId, string $documentId): Response - Delete documentlistSharing(string $libraryId): Response - List library sharing settingscreateSharing(string $libraryId, SharingIn $sharing): Response - Create/update sharingdeleteSharing(string $libraryId, SharingDelete $sharing): Response - Delete sharing
// 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',
'required' => [
'location',
],
'properties' => [
'location' => [
'type' => 'string',
'description' => 'The location to get the weather for.',
],
],
],
],
],
[
'type' => 'function',
'function' => [
'name' => 'sendWeatherNotification',
'description' => 'Send notification about weather to a user',
'parameters' => [
'type' => 'object',
'required' => [
'userId',
'message',
],
'properties' => [
'userId' => [
'type' => 'string',
'description' => 'the id of the user',
],
'message' => [
'type' => 'string',
'description' => 'the message to send the user',
],
],
],
],
],
],
toolChoice: 'any',
);
// Tool calls are returned in the response
$response->json('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'
}
}For convenience, the client also provides a simple chat completion method, which returns a simpler, condensed and flattened DTO, which is useful for quick prototyping.
$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'
}For convenience, here is a list of all the DTOs available in this package, organized by feature area.
- Chat/ChatCompletionChoice.php
- Chat/ChatCompletionMessage.php
- Chat/ChatCompletionRequest.php
- Chat/ChatCompletionResponse.php
- Chat/StreamedChatCompletionChoice.php
- Chat/StreamedChatCompletionDelta.php
- Chat/StreamedChatCompletionResponse.php
- Chat/FunctionCall.php
- Chat/ToolCalls.php
- Fim/FIMCompletionRequest.php
- Fim/FIMCompletionResponse.php
- Fim/FIMChoice.php
- Fim/StreamedFIMCompletionResponse.php
- Fim/StreamedFIMChoice.php
- Fim/StreamedFIMDelta.php
- OCR/OCRRequest.php
- OCR/OCRResponse.php
- OCR/Document.php
- OCR/Page.php
- OCR/Image.php
- OCR/Dimensions.php
- OCR/UsageInfo.php
- Models/Model.php
- Models/ModelList.php
- Models/ModelPermission.php
- Models/ModelCapabilities.php
- Models/BaseModelCard.php
- Models/FTModelCard.php
- Models/DeleteModelOut.php
- FineTuning/JobIn.php
- FineTuning/JobsOut.php
- FineTuning/JobMetadata.php
- FineTuning/LegacyJobMetadataOut.php
- FineTuning/CompletionJobOut.php
- FineTuning/ClassifierJobOut.php
- FineTuning/CompletionDetailedJobOut.php
- FineTuning/ClassifierDetailedJobOut.php
- FineTuning/CompletionFTModelOut.php
- FineTuning/ClassifierFTModelOut.php
- FineTuning/ArchiveFTModelOut.php
- FineTuning/UnarchiveFTModelOut.php
- FineTuning/UpdateFTModelIn.php
- FineTuning/TrainingFile.php
- FineTuning/TrainingParameters.php
- FineTuning/WandbIntegration.php
- FineTuning/Checkpoint.php
- FineTuning/CheckpointMetrics.php
- FineTuning/ValidationError.php
- Files/FileObject.php
- Files/UploadFileOut.php
- Files/ListFilesOut.php
- Files/ListFilesRequest.php
- Files/RetrieveFileOut.php
- Files/DeleteFileOut.php
- Files/FileSignedURL.php
- Audio/TranscriptionResponse.php
- Audio/TranscriptionSegment.php
- Audio/TranscriptionWord.php
- Audio/SpeechRequest.php
- Audio/SpeechResponse.php
- Audio/SpeechStreamAudioDelta.php
- Audio/SpeechStreamDone.php
- Audio/VoiceResponse.php
- Audio/VoiceListResponse.php
- Audio/VoiceCreateRequest.php
- Audio/VoiceUpdateRequest.php
- Classifications/ClassificationRequest.php
- Classifications/ChatClassificationRequest.php
- Classifications/ClassificationResponse.php
- Classifications/ClassificationResult.php
- Moderations/ChatModerationRequest.php
- Moderations/ModerationResponse.php
- Moderations/ModerationResult.php
- Moderations/ModerationCategories.php
- Moderations/ModerationCategoryScores.php
- Agents/Agent.php
- Agents/AgentList.php
- Agents/AgentCreationRequest.php
- Agents/AgentUpdateRequest.php
- Agents/AgentAliasResponse.php
- Conversations/ConversationRequest.php
- Conversations/ConversationAppendRequest.php
- Conversations/ConversationRestartRequest.php
- Conversations/ConversationResponse.php
- Conversations/ConversationList.php
- Conversations/ConversationHistory.php
- Conversations/ConversationMessages.php
- Conversations/ConversationEntry.php
- Conversations/ConversationMessage.php
- Conversations/ModelConversation.php
- Conversations/AgentConversation.php
- Libraries/LibraryIn.php
- Libraries/LibraryInUpdate.php
- Libraries/LibraryOut.php
- Libraries/ListLibraryOut.php
- Libraries/DocumentOut.php
- Libraries/DocumentUpdateIn.php
- Libraries/ListDocumentOut.php
- Libraries/SharingIn.php
- Libraries/SharingDelete.php
- Libraries/SharingOut.php
- Libraries/ListSharingOut.php
The following models are available in the Mistral API. You can use the Model enum in this package to refer to them, or use the string value directly.
| Enum Case | String Value | Type | Description |
|---|---|---|---|
Model::large->value |
'mistral-large-latest' |
Chat | Most capable model for complex reasoning and specialized tasks |
Model::medium->value |
'mistral-medium-latest' |
Chat | Balanced model for intermediate tasks |
Model::small->value |
'mistral-small-latest' |
Chat | Fast, efficient model for simple bulk tasks |
Model::magistralMedium->value |
'magistral-medium-latest' |
Reasoning | Advanced reasoning model |
Model::pixtralLarge->value |
'pixtral-large-latest' |
Vision | Advanced vision model for image understanding |
Model::pixtral12b->value |
'pixtral-12b-latest' |
Vision | Efficient vision model |
Model::codestral->value |
'codestral-latest' |
Code | Specialized model for code generation and understanding |
Model::ministral8b->value |
'ministral-8b-latest' |
Chat | Compact 8B parameter model for edge deployment |
Model::voxtralSmall->value |
'voxtral-small-latest' |
Audio | Audio transcription model |
Model::embed->value |
'mistral-embed' |
Embeddings | Text embedding model for semantic search and retrieval |
| Enum Case | String Value | Type | Description |
|---|---|---|---|
Model::mistral7b->value |
'open-mistral-7b' |
Chat | 7B parameter open source foundation model |
Model::mixtral->value |
'open-mixtral-8x7b' |
Chat | Mixture of Experts model with 8x7B parameters |
For the most up-to-date model information and capabilities, visit the Mistral AI Models Documentation.
cp .env.example .env
composer test
composer analyse srcThe MIT License (MIT). Please see License File for more information.
Mistral and the Mistral logo are trademarks of Mistral.ai. This package is not affiliated with, endorsed by, or sponsored by Mistral.ai. All trademarks and registered trademarks are the property of their respective owners.
See Mistral.AI for more information.
