mistralai_dart 6.0.0
mistralai_dart: ^6.0.0 copied to clipboard
Dart client for the Mistral AI API - chat, embeddings, fine-tuning, agents, and more.
Mistral AI Dart Client #
Dart client for the Mistral AI API with chat completions, streaming, tool calling, multimodal inputs, TTS, voice management, reasoning effort, embeddings, OCR, and more. It gives Dart and Flutter applications a pure Dart, type-safe client across iOS, Android, macOS, Windows, Linux, Web, and server-side Dart.
Tip
Coding agents: start with llms.txt. It links to the package docs, examples, and optional references in a compact format.
Table of Contents
Features #
Coverage: This client covers the full Mistral AI API surface. See API Coverage for details.
Generation and streaming #
- Chat completions with streaming, tool calling, vision, JSON mode, and structured output
- Embeddings, FIM code completions, and reasoning effort control
- Model management and discovery
Tools and media #
- Built-in web search, code interpreter, and document library tools
- Audio transcription, text-to-speech, and voice management
- OCR, moderations, and classifications
Operational APIs #
- Files, fine-tuned model management, and batch processing
- Agents, conversations, connectors, and libraries (beta)
- Prompts and skills: versioned, shareable templates and instructions (beta)
- Observability: campaigns, datasets, judges, and chat completion events (beta)
- Workflows: execution, scheduling, managed deployments, and management (beta)
- RAG: ingestion pipeline configuration and search index management (beta)
- Users: current authenticated user identity (beta)
Why choose this client? #
- Pure Dart with no Flutter dependency — works in mobile apps, backends, and CLIs.
- Type-safe request and response models with minimal dependencies (
http,logging,meta). - Streaming, retries, interceptors, and error handling built into the client.
- Covers the full Mistral AI API surface, including beta agents, conversations, connectors, libraries, prompts, skills, observability, workflows, RAG, and users.
- Strict semver versioning so downstream packages can depend on stable, predictable version ranges.
Quickstart #
dependencies:
mistralai_dart: ^6.0.0
import 'package:mistralai_dart/mistralai_dart.dart';
Future<void> main() async {
final client = MistralClient.fromEnvironment();
try {
final response = await client.chat.create(
request: ChatCompletionRequest(
model: 'mistral-small-latest',
messages: [
ChatMessage.user('Hello! How are you?'),
],
),
);
print(response.text);
} finally {
client.close();
}
}
Configuration #
Configure auth, retries, and custom endpoints
Use MistralClient.fromEnvironment() when MISTRAL_API_KEY is available. Switch to MistralConfig when you need a proxy, custom timeout, or a non-default retry policy.
// Simple API key authentication
final client = MistralClient.withApiKey('your-api-key');
// From environment variables (reads MISTRAL_API_KEY and optional MISTRAL_BASE_URL)
final client = MistralClient.fromEnvironment();
// Custom base URL (for proxies or self-hosted)
final client = MistralClient.withApiKey(
'your-api-key',
baseUrl: 'https://my-proxy.example.com',
);
// Full configuration
final client = MistralClient(
config: MistralConfig(
authProvider: ApiKeyProvider('your-api-key'),
baseUrl: 'https://api.mistral.ai',
retryPolicy: RetryPolicy(
maxRetries: 3,
initialDelay: Duration(seconds: 1),
),
),
);
// Always close when done
client.close();
Environment variables:
MISTRAL_API_KEYMISTRAL_BASE_URL
Use explicit configuration on web builds where runtime environment variables are not available.
Usage #
How do I use chat completions? #
Show example
Use client.chat.create(...) to send messages and receive a completion. Set reasoningEffort on reasoning-capable models to control how deeply the model thinks.
// Basic chat
final response = await client.chat.create(
request: ChatCompletionRequest(
model: 'mistral-small-latest',
messages: [
ChatMessage.system('You are a helpful assistant.'),
ChatMessage.user('What is the capital of France?'),
],
temperature: 0.7,
maxTokens: 500,
),
);
print(response.text);
// Control reasoning depth for reasoning-capable models
final response = await client.chat.create(
request: ChatCompletionRequest(
model: 'mistral-large-latest',
messages: [
ChatMessage.user('Solve this step by step: what is 23 * 47?'),
],
reasoningEffort: ReasoningEffort.high,
),
);
print(response.text);
How do I stream responses? #
Show example
Use client.chat.createStream(...) to receive tokens as they are generated via SSE. Each chunk exposes a text extension for easy access.
final stream = client.chat.createStream(
request: ChatCompletionRequest(
model: 'mistral-small-latest',
messages: [
ChatMessage.user('Tell me a story'),
],
),
);
await for (final chunk in stream) {
if (chunk.text != null) {
stdout.write(chunk.text); // Extension method
}
}
How do I use vision? #
Show example
Pass multimodal content parts (text + image URLs or base64 data URLs) using ChatMessage.userMultimodal(...) with a vision-capable model like Pixtral.
final response = await client.chat.create(
request: ChatCompletionRequest(
model: 'pixtral-12b-2409',
messages: [
ChatMessage.userMultimodal([
ContentPart.text('Describe this image'),
ContentPart.imageUrl('https://example.com/image.jpg'),
// Or use base64 via data URL
// ContentPart.imageUrl('data:image/png;base64,$base64Data'),
]),
],
),
);
How do I use tool calling? #
Show example
Define custom tools with JSON Schema parameters, or use built-in tools like web search, code interpreter, and document library. Send tool results back in a follow-up message turn.
// Define tools
final weatherTool = Tool.function(
name: 'get_weather',
description: 'Get weather for a location',
parameters: {
'type': 'object',
'properties': {
'location': {'type': 'string'},
'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']},
},
'required': ['location'],
},
);
// Request with tools
final response = await client.chat.create(
request: ChatCompletionRequest(
model: 'mistral-large-latest',
messages: [ChatMessage.user('What is the weather in Paris?')],
tools: [weatherTool],
toolChoice: const ToolChoiceAuto(),
),
);
// Check for tool calls using extension
if (response.hasToolCalls) {
for (final toolCall in response.toolCalls) {
print('Function: ${toolCall.function.name}');
print('Arguments: ${toolCall.function.arguments}');
// Execute tool and send result back
final toolResult = await executeFunction(toolCall);
// Continue conversation with tool result
final followUp = await client.chat.create(
request: ChatCompletionRequest(
model: 'mistral-large-latest',
messages: [
ChatMessage.user('What is the weather in Paris?'),
ChatMessage.assistant(null, toolCalls: response.toolCalls),
ChatMessage.tool(
toolCallId: toolCall.id,
content: toolResult,
),
],
tools: [weatherTool],
),
);
}
}
// Web search tool
final webTool = Tool.webSearch();
// Code interpreter
final codeTool = Tool.codeInterpreter();
// Image generation
final imageTool = Tool.imageGeneration();
// Document library (for RAG)
final docTool = Tool.documentLibrary(libraryIds: ['lib-123']);
final response = await client.chat.create(
request: ChatCompletionRequest(
model: 'mistral-large-latest',
messages: [ChatMessage.user('Search for latest AI news')],
tools: [webTool],
toolChoice: const ToolChoiceAuto(),
),
);
How do I use structured output? #
Show example
Use ResponseFormatJsonObject for simple JSON mode or ResponseFormatJsonSchema to enforce a specific schema on the response.
// Simple JSON mode
final response = await client.chat.create(
request: ChatCompletionRequest(
model: 'mistral-small-latest',
messages: [
ChatMessage.system('Respond in JSON format.'),
ChatMessage.user('List 3 programming languages'),
],
responseFormat: const ResponseFormatJsonObject(),
),
);
// JSON with schema validation
final response = await client.chat.create(
request: ChatCompletionRequest(
model: 'mistral-small-latest',
messages: [ChatMessage.user('Generate a product')],
responseFormat: ResponseFormatJsonSchema(
name: 'product',
schema: {
'type': 'object',
'properties': {
'name': {'type': 'string'},
'price': {'type': 'number'},
'in_stock': {'type': 'boolean'},
},
'required': ['name', 'price'],
},
),
),
);
How do I create embeddings? #
Show example
Use client.embeddings.create(...) with a single text or a batch of texts. The response contains embedding vectors you can use for search, clustering, or classification.
// Single text
final response = await client.embeddings.create(
request: EmbeddingRequest.single(
model: 'mistral-embed',
input: 'Hello, world!',
),
);
print('Dimensions: ${response.data.first.embedding.length}');
// Batch embeddings
final response = await client.embeddings.create(
request: EmbeddingRequest.batch(
model: 'mistral-embed',
input: ['Text 1', 'Text 2', 'Text 3'],
),
);
How do I use code completions? #
Show example
Use client.fim.create(...) for fill-in-the-middle code completion with Codestral. Provide a prompt and optional suffix to generate the middle portion.
final response = await client.fim.create(
request: FimCompletionRequest(
model: 'codestral-latest',
prompt: 'def fibonacci(n):',
suffix: '\n return result',
maxTokens: 100,
),
);
print(response.choices.first.message);
// Streaming FIM
final stream = client.fim.createStream(
request: FimCompletionRequest(
model: 'codestral-latest',
prompt: 'function add(a, b) {',
suffix: '}',
),
);
How do I list and manage models? #
Show example
Use client.models to list, retrieve, and delete models. Use client.fineTuning.models to update, archive, and unarchive fine-tuned models.
// List all models
final models = await client.models.list();
for (final model in models.data) {
print('${model.id}: ${model.name}');
}
// Get a specific model
final model = await client.models.get('mistral-small-latest');
print('Max context: ${model.maxContextLength}');
// Delete a fine-tuned model
await client.models.delete('ft:mistral-small:my-model:xyz');
// Update a fine-tuned model's metadata
final updated = await client.fineTuning.models.update(
modelId: 'ft:mistral-small:my-model:xyz',
name: 'My Improved Model',
description: 'Fine-tuned for customer support',
);
// Archive a model
final archived = await client.fineTuning.models.archive(
modelId: 'ft:mistral-small:my-model:xyz',
);
// Unarchive a model
await client.fineTuning.models.unarchive(
modelId: 'ft:mistral-small:my-model:xyz',
);
How do I manage files? #
Show example
Use client.files to upload, list, download, and delete files. File-path uploads are native-only; on web, use byte-based uploads instead.
Note: File-path based uploads (
filePath) are only available on native platforms. On web, use byte-based uploads (bytes) instead. Other file operations (list, retrieve, download, delete) are supported on all platforms.
// Upload a file
final file = await client.files.upload(
filePath: 'training_data.jsonl',
purpose: FilePurpose.fineTune,
);
// List files
final files = await client.files.list();
// Download file content
final content = await client.files.download(fileId: file.id);
// Delete file
await client.files.delete(fileId: file.id);
How do I manage fine-tuned models and batch? #
Show example
The fine-tuning jobs API has been removed upstream; use client.fineTuning.models to manage the fine-tuned models that result from training runs launched outside this client, and client.batch.jobs for batch processing. Batch jobs support a polling helper for long-running operations.
// Update a fine-tuned model's metadata
final updated = await client.fineTuning.models.update(
modelId: 'ft:mistral-small:my-model:xyz',
name: 'My Model v2',
);
// Archive / unarchive a fine-tuned model
await client.fineTuning.models.archive(modelId: updated.id);
await client.fineTuning.models.unarchive(modelId: updated.id);
// List available models with pagination
final paginator = Paginator<AgentList, Agent>(
fetcher: (page, size) => client.agents.list(page: page, pageSize: size),
getItems: (response) => response.data,
);
await for (final agent in paginator.items()) {
print('Agent: ${agent.id}');
}
// Create batch job
final job = await client.batch.jobs.create(
request: CreateBatchJobRequest(
inputFiles: ['file-abc123'],
endpoint: '/v1/chat/completions',
model: 'mistral-small-latest',
),
);
// Poll for completion
final poller = BatchJobPoller(client: client, jobId: job.id);
final completed = await poller.poll();
// Download results
final results = await client.files.download(fileId: completed.outputFile!);
How do I moderate content? #
Show example
Use client.moderations for text and chat-aware content moderation, and client.classifications for text classification. Both flag content categories automatically.
// Text moderation
final result = await client.moderations.create(
request: ModerationRequest(
model: 'mistral-moderation-2603',
input: ['Check this content for safety'],
),
);
for (final item in result.results) {
if (item.flagged) {
print('Content flagged: ${item.categories}');
}
}
// Chat-aware moderation
final result = await client.moderations.createChat(
request: ChatModerationRequest(
model: 'mistral-moderation-2603',
input: [
ChatMessage.user('Hello'),
ChatMessage.assistant('Hi there!'),
],
),
);
final result = await client.classifications.create(
request: ClassificationRequest(
model: 'mistral-moderation-2603',
input: ['Is this spam?'],
),
);
for (final item in result.results) {
print('Categories: ${item.categories}');
}
How do I extract text from documents? #
Show example
Use client.ocr.process(...) to extract text from documents and images. Supports both URL and base64-encoded inputs, and returns markdown per page.
// From URL
final result = await client.ocr.process(
request: OcrRequest(
model: 'mistral-ocr-latest',
document: OcrDocument.fromUrl('https://example.com/document.pdf'),
),
);
for (final page in result.pages) {
print('Page ${page.index}: ${page.markdown}');
}
// From base64
final result = await client.ocr.process(
request: OcrRequest(
model: 'mistral-ocr-latest',
document: OcrDocument.fromBase64(base64Data, type: 'application/pdf'),
),
);
How do I use audio? #
Show example
Use client.audio.transcriptions for speech-to-text, client.audio.speech for text-to-speech, and client.audio.voices to manage custom voices. Both transcription and speech support streaming.
// Upload audio file first, then transcribe using file ID
// Basic transcription
final result = await client.audio.transcriptions.create(
request: TranscriptionRequest(
model: 'mistral-stt-latest',
file: audioFileId, // ID from client.files.upload()
),
);
print('Transcription: ${result.text}');
// Streaming transcription
final stream = client.audio.transcriptions.createStream(
request: TranscriptionRequest(
model: 'mistral-stt-latest',
file: audioFileId,
),
);
await for (final event in stream) {
print(event.text);
}
// Generate speech
final response = await client.audio.speech.create(
request: SpeechRequest(
input: 'Hello, world!',
voiceId: 'voice-id',
),
);
print('Audio data: ${response.audioData.length} chars');
// Stream speech
final stream = client.audio.speech.createStream(
request: SpeechRequest(input: 'Hello!'),
);
await for (final event in stream) {
if (event is SpeechStreamAudioDelta) {
// Process audio chunk
}
}
// List voices
final voices = await client.audio.voices.list();
for (final voice in voices.items) {
print('${voice.name}: ${voice.id}');
}
// Create a custom voice
final voice = await client.audio.voices.create(
request: VoiceCreateRequest(
name: 'My Voice',
sampleAudio: base64EncodedAudio,
),
);
print('Created voice: ${voice.id}');
How do I use agents? #
Show example
Use client.agents to create, list, update, and delete agents. Agents can use tools and follow custom instructions. Use complete(...) to chat with an agent.
// Create an agent
final agent = await client.agents.create(
request: CreateAgentRequest(
name: 'Research Assistant',
model: 'mistral-large-latest',
instructions: 'You are a helpful research assistant.',
tools: [Tool.webSearch()],
),
);
// Chat with agent
final response = await client.agents.complete(
request: AgentCompletionRequest(
agentId: agent.id,
messages: [ChatMessage.user('Search for latest AI papers')],
),
);
print(response.text); // Extension for output text content
// List agents
final agents = await client.agents.list();
// Update agent
await client.agents.update(
agentId: agent.id,
request: UpdateAgentRequest(name: 'Updated Name'),
);
// Delete agent
await client.agents.delete(agentId: agent.id);
How do I use conversations? #
Show example
Use client.conversations to manage stateful multi-turn conversations with agents. The server maintains conversation history so you do not have to resend it.
// Start a conversation
final conversation = await client.conversations.start(
request: StartConversationRequest(
agentId: 'agent-123',
inputs: [MessageInputEntry(content: 'Hello!')],
),
);
print('Assistant: ${conversation.text}');
// Continue the conversation
final response = await client.conversations.sendMessage(
conversationId: conversation.conversationId,
message: 'Tell me more',
);
// Get conversation details
final details = await client.conversations.retrieve(
conversationId: conversation.conversationId,
);
How do I use libraries? #
Show example
Use client.libraries to create document libraries for RAG. Upload files first, add them as documents, then reference the library in chat via Tool.documentLibrary(...).
// Create a library
final library = await client.libraries.create(
name: 'Research Papers',
);
// Add a document (file must be uploaded first via client.files.upload())
final doc = await client.libraries.documents.create(
libraryId: library.id,
fileId: fileId, // ID from client.files.upload()
);
// List documents
final docs = await client.libraries.documents.list(libraryId: library.id);
// Use library with chat
final response = await client.chat.create(
request: ChatCompletionRequest(
model: 'mistral-large-latest',
messages: [ChatMessage.user('What does the paper say about AI?')],
tools: [Tool.documentLibrary(libraryIds: [library.id])],
),
);
// Delete library
await client.libraries.delete(libraryId: library.id);
How do I use prompts? #
Show example
Use client.prompts to manage versioned, shareable prompt templates (Beta). Each prompt has one or more versions; aliases (e.g. production) let you point consumers at a specific version without changing their code.
// Create a prompt
final prompt = await client.prompts.create(
request: const CreatePromptRequest(
name: 'greeting',
definition: PromptDefinition(content: 'Hello, {{name}}!'),
),
);
// List prompts
final prompts = await client.prompts.list(pageSize: 10);
// Create a new version
final version = await client.prompts.createVersion(
promptId: prompt.id,
request: const CreatePromptVersionRequest(
definition: PromptDefinition(content: 'Hi there, {{name}}!'),
),
);
// Point an alias at the new version
await client.prompts.updateVersion(
promptId: prompt.id,
version: version.version ?? 2,
request: const UpdatePromptVersionRequest(
aliases: AliasList(values: ['production']),
),
);
// Retrieve by alias
final latest = await client.prompts.retrieve(
promptId: prompt.id,
alias: 'production',
);
print(latest.definition?.content);
// Delete the prompt
await client.prompts.delete(promptId: prompt.id);
How do I use skills? #
Show example
Use client.skills to manage versioned, shareable model instructions with optional file assets (Beta). Skills follow the same version/alias model as prompts.
// Create a skill with a text asset
final skill = await client.skills.create(
request: const CreateSkillRequest(
name: 'summarizer',
definition: SkillDefinition(
description: 'Summarizes long documents.',
body: 'Summarize the input in three bullet points.',
assets: {
'style_guide.txt': SkillAssetContent.text(
textContent: 'Use concise, plain language.',
),
},
),
),
);
// List skills
final skills = await client.skills.list(pageSize: 10);
// Create a new version and point an alias at it
final version = await client.skills.createVersion(
skillId: skill.id,
request: const CreateSkillVersionRequest(
definition: SkillDefinition(body: 'Summarize in three short bullets.'),
),
);
await client.skills.updateVersion(
skillId: skill.id,
version: version.version ?? 2,
request: const UpdateSkillVersionRequest(
aliases: AliasList(values: ['production']),
),
);
// Delete the skill
await client.skills.delete(skillId: skill.id);
How do I use connectors? #
Show example
Use client.connectors to manage MCP connectors (Beta): create and configure connectors, manage their credentials, activate or deactivate them at the organization, workspace, or user level, share a private connector with the workspace, and list or call their tools.
// Create an MCP connector
final connector = await client.connectors.create(
request: const CreateConnectorRequest(
name: 'my_connector',
description: 'My MCP connector',
server: 'https://mcp.example.com',
visibility: PublicResourceVisibility.sharedOrg,
),
);
// Configure user-level credentials
await client.connectors.createOrUpdateUserCredentials(
connectorIdOrName: connector.id,
request: const CredentialsCreateOrUpdate(
name: 'my-cred',
credentials: ConnectionCredentials(bearerToken: 'secret-token'),
),
);
// Activate the connector for the organization
await client.connectors.activateForOrganization(connectorId: connector.id);
// Share a private connector with the current workspace
await client.connectors.share(connectorId: connector.id);
// Remove all user-level credentials for the connector
await client.connectors.deleteAllUserCredentials(
connectorIdOrName: connector.id,
);
// List and call the connector's tools
final tools = await client.connectors.listTools(
connectorIdOrName: connector.id,
);
final result = await client.connectors.callTool(
connectorIdOrName: connector.id,
toolName: 'search',
request: const ConnectorCallToolRequest(arguments: {'query': 'mistral'}),
);
How do I use observability? #
Show example
Use client.observability to manage campaigns, datasets, dataset records, judges, chat completion events, and chat completion fields. You can also explore OpenTelemetry traces, spans, and logs. These APIs help you monitor and evaluate your Mistral AI usage.
// List datasets
final datasetList = await client.observability.datasets.list();
for (final dataset in datasetList.datasets.results) {
print('${dataset.name}: ${dataset.id}');
}
// Create a dataset
final dataset = await client.observability.datasets.create(
request: PostDatasetInSchema(
name: 'My Dataset',
description: 'A sample dataset',
),
);
// Manage dataset records
final records = await client.observability.datasets.listRecords(
datasetId: dataset.id,
);
// List judges
final judges = await client.observability.judges.list();
// List campaigns
final campaigns = await client.observability.campaigns.list();
// Browse chat completion fields
final fields = await client.observability.chatCompletionFields.list();
// Search traces and inspect their spans
final traces = await client.observability.traces.search(
request: const TracesRequest(searchExpression: 'status_code = "Error"'),
);
final spans = await client.observability.spans.search();
// Search structured logs
final logs = await client.observability.logs.search();
How do I use RAG? #
Show example
Use client.rag to configure document ingestion pipelines and manage the Vespa-backed search indexes used for retrieval (Beta). The ingestionPipelineConfigurations sub-resource registers and lists pipeline configurations, while the searchIndexes sub-resource registers, inspects, and unregisters search indexes.
// List ingestion pipeline configurations
final configs = await client.rag.ingestionPipelineConfigurations.list();
// Register a configuration
final config = await client.rag.ingestionPipelineConfigurations.register(
request: const CreateIngestionPipelineConfigurationRequest(
name: 'My ingestion pipeline',
),
);
// Update the run info after a pipeline run
await client.rag.ingestionPipelineConfigurations.updateRunInfo(
id: config.id,
request: UpdateRunInfo(
executionTime: DateTime.now().toUtc(),
chunksCount: 128,
),
);
// Register a Vespa-backed search index
final registered = await client.rag.searchIndexes.register(
request: const RegisterSearchIndexRequest(
name: 'My search index',
index: RegisterVespaIndexRequest(
k8sCluster: 'cluster',
k8sNamespace: 'namespace',
vespaInstanceName: 'instance',
vespaVersion: '8.0.0',
queryUrl: 'https://vespa.example.com',
schemas: [],
),
),
);
// Fetch detailed information and list summaries
final detail = await client.rag.searchIndexes.getDetail(
indexId: registered.id,
);
final summaries = await client.rag.searchIndexes.listSummaries();
// Unregister the search index
await client.rag.searchIndexes.unregister(indexId: registered.id);
How do I use workflows? #
Show example
Use client.workflows to manage and execute workflows via the workflowCore resource, check execution status, list registrations, monitor runs, view metrics, inspect workers, and configure schedules.
// List registered workflows
final workflows = await client.workflows.core.list();
for (final wf in workflows.workflowRegistrations) {
print('${wf.workflow?.name}: ${wf.workflowId}');
}
// Execute a workflow
final result = await client.workflows.core.executeAsync(
workflowIdentifier: 'my-workflow',
request: WorkflowExecutionRequest(
input: {'key': 'value'},
),
);
print('Execution: ${result.executionId}');
// Get execution status
final execution = await client.workflows.executions.get(
executionId: result.executionId,
);
print('Status: ${execution.status}');
// List runs and check metrics
final runs = await client.workflows.runs.list();
final metrics = await client.workflows.metrics.get(
workflowName: 'my-workflow',
);
// Check worker status
final worker = await client.workflows.workers.whoami();
// List registrations
final registrations = await client.workflows.registrations.list();
// List schedules
final schedules = await client.workflows.schedules.list();
// Create, start, and monitor a managed deployment
final deployment = await client.workflows.deployments.create(
request: const CreateDeploymentRequest(
name: 'my-deployment',
spec: DeploymentWorkerSpecInput(
githubUrl: 'https://github.com/my-org/my-worker',
),
),
);
await client.workflows.deployments.start(name: deployment.name);
final logs = await client.workflows.deployments.getLogs(
name: deployment.name,
limit: 50,
);
print('Fetched ${logs.results.length} log record(s)');
await for (final log in client.workflows.deployments.streamLogs(
name: deployment.name,
)) {
print('${log.severityText}: ${log.body}');
}
How do I get the current user? #
Show example
Use client.users to retrieve the identity of the currently authenticated user (Beta), including their organization, workspace, and the API key used for the request.
final identity = await client.users.me();
print('Signed in as: ${identity.email}');
print('Organization: ${identity.organization?.name}');
print('Workspace: ${identity.workspace?.name}');
Error Handling #
Handle retries, validation failures, and request aborts
mistralai_dart throws typed exceptions so retry logic and validation handling stay explicit. Catch ApiException and its subclasses first, then fall back to MistralException for other transport or parsing failures.
import 'dart:io';
import 'package:mistralai_dart/mistralai_dart.dart';
Future<void> main() async {
final client = MistralClient.fromEnvironment();
try {
await client.chat.create(
request: ChatCompletionRequest(
model: 'mistral-small-latest',
messages: [ChatMessage.user('Ping')],
),
);
} on RateLimitException catch (error) {
stderr.writeln('Retry after: ${error.retryAfter}');
} on ApiException catch (error) {
stderr.writeln('Mistral API error ${error.statusCode}: ${error.message}');
} on MistralException catch (error) {
stderr.writeln('Mistral client error: $error');
} finally {
client.close();
}
}
Examples #
See the example/ directory for complete examples:
| Example | Description |
|---|---|
chat_example.dart |
Basic chat completions |
streaming_example.dart |
Streaming responses |
tool_calling_example.dart |
Tool calling |
json_mode_example.dart |
Structured output |
vision_example.dart |
Multimodal inputs |
embeddings_example.dart |
Text embeddings |
fim_example.dart |
Code completion |
files_example.dart |
File management |
fine_tuning_example.dart |
Fine-tuned model management |
batch_example.dart |
Batch processing |
moderation_example.dart |
Content moderation |
classification_example.dart |
Text classification |
ocr_example.dart |
Document text extraction |
audio_example.dart |
Audio transcription and TTS |
agents_example.dart |
AI agents (beta) |
conversations_example.dart |
Multi-turn conversations (beta) |
libraries_example.dart |
Document storage (beta) |
prompts_example.dart |
Versioned prompt templates (beta) |
skills_example.dart |
Versioned model instructions and assets (beta) |
connectors_example.dart |
MCP connector management (beta) |
observability_example.dart |
Observability: datasets, judges, campaigns (beta) |
workflows_example.dart |
Workflow execution, scheduling, and managed deployments (beta) |
rag_index_example.dart |
RAG ingestion pipelines and search indexes (beta) |
users_example.dart |
Current authenticated user identity (beta) |
models_example.dart |
Model listing |
error_handling_example.dart |
Exception handling patterns |
config_example.dart |
Client configuration options |
multi_turn_example.dart |
Multi-turn conversation management |
parallel_requests_example.dart |
Parallel and concurrent requests |
rag_example.dart |
Retrieval Augmented Generation |
semantic_search_example.dart |
Semantic search with embeddings |
system_message_example.dart |
System message patterns |
API Coverage #
| API | Status |
|---|---|
| Chat | ✅ Full |
| Embeddings | ✅ Full |
| Models | ✅ Full |
| FIM | ✅ Full |
| Files | ✅ Full |
| Fine-tuned models (management) | ✅ Full |
| Batch | ✅ Full |
| Moderations | ✅ Full |
| Classifications | ✅ Full |
| OCR | ✅ Full |
| Audio (Transcription, Speech, Voices) | ✅ Full |
| Agents (Beta) | ✅ Full |
| Conversations (Beta) | ✅ Full |
| Libraries (Beta) | ✅ Full |
| Connectors (Beta) | ✅ Full |
| Prompts (Beta) | ✅ Full |
| Skills (Beta) | ✅ Full |
| Observability (Beta) | ✅ Full |
| Workflows (Beta) | ✅ Full |
| RAG (Beta) | ✅ Full |
| Users (Beta) | ✅ Full |
Official Documentation #
Sponsor #
If these packages are useful to you or your company, please consider sponsoring the project. Development and maintenance are provided to the community for free, but integration tests against real APIs and the tooling required to build and verify releases still have real costs. Your support, at any level, helps keep these packages maintained and free for the Dart & Flutter community.
License #
This package is licensed under the MIT License.
This is a community-maintained package and is not affiliated with or endorsed by Mistral AI.