This is v2 of the Mistral TypeScript SDK.
Key changes from v1: ESM-only, shorter type names, forward-compatible enums/unions, Zod v4. See the Migration Guide for full details.
To pin v1:
npm install @mistralai/mistralai@^1· v1 documentation and source
Mistral AI API: Our Chat Completion and Embeddings APIs specification. Create your account on La Plateforme to get access and read the docs to learn how to use it.
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
npm add @mistralai/mistralai
pnpm add @mistralai/mistralai
bun add @mistralai/mistralai
yarn add @mistralai/mistralai
[!NOTE] This package is published as an ES Module (ESM) only. For applications using CommonJS, use
await import("@mistralai/mistralai")to import and use this package.
For supported JavaScript runtimes, please consult RUNTIMES.md.
Before you begin, you will need a Mistral AI API key.
# set Mistral API Key (using zsh for example)
$ echo 'export MISTRAL_API_KEY=[your_key_here]' >> ~/.zshenv
# reload the environment (or just quit and open a new terminal)
$ source ~/.zshenv
Node workloads with a mounted service-account token can set MISTRAL_SA_TOKEN_PATH instead. The file is re-read on every request, so rotation is picked up. Credentials resolve in this order:
Authorization header passed per request via headersnew Mistral({ apiKey }), which also accepts an async functionMISTRAL_SA_TOKEN_PATHMISTRAL_API_KEYAn unreadable or empty token file fails the request with an UnexpectedClientError whose cause explains why.
This example shows how to create chat completions.
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.chat.complete({
model: "mistral-large-latest",
messages: [
{
role: "user",
content:
"Who is the best French painter? Answer in one short sentence.",
},
],
responseFormat: {
type: "text",
},
});
console.log(result);
}
run();
This example shows how to upload a file.
import { Mistral } from "@mistralai/mistralai";
import { openAsBlob } from "node:fs";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.files.upload({
file: await openAsBlob("example.file"),
});
console.log(result);
}
run();
This example shows how to create agents completions.
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.agents.complete({
messages: [
{
role: "user",
content:
"Who is the best French painter? Answer in one short sentence.",
},
],
responseFormat: {
type: "text",
},
agentId: "<id>",
});
console.log(result);
}
run();
This example shows how to create embedding request.
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.embeddings.create({
model: "mistral-embed",
inputs: [
"Embed this sentence.",
"As well as this one.",
],
});
console.log(result);
}
run();
We have dedicated SDKs for the following providers:
Server-sent events are used to stream content from certain
operations. These operations will expose the stream as an async iterable that
can be consumed using a for await...of loop. The loop will
terminate when the server no longer has any events to send and closes the
underlying connection.
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.conversations.startStream({
inputs: [
{
object: "entry",
type: "agent.handoff",
previousAgentId: "<id>",
previousAgentName: "<value>",
nextAgentId: "<id>",
nextAgentName: "<value>",
},
],
completionArgs: {
responseFormat: {
type: "text",
},
},
});
for await (const event of result) {
console.log(event);
}
}
run();
Some of the endpoints in this SDK support pagination. To use pagination, you
make your SDK calls as usual, but the returned response object will also be an
async iterable that can be consumed using the for await...of
syntax.
Here's an example of one such pagination call:
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.prompts.list();
for await (const page of result) {
console.log(page);
}
}
run();
Certain SDK methods accept files as part of a multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
[!TIP]
Depending on your JavaScript runtime, there are convenient utilities that return a handle to a file without reading the entire contents into memory:
- Node.js v20+: Since v20, Node.js comes with a native
openAsBlobfunction innode:fs.- Bun: The native
Bun.filefunction produces a file handle that can be used for streaming file uploads.- Browsers: All supported browsers return an instance to a
Filewhen reading the value from an<input type="file">element.- Node.js v18: A file stream can be created using the
fileFromhelper fromfetch-blob/from.js.
import { Mistral } from "@mistralai/mistralai";
import { openAsBlob } from "node:fs";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.libraries.documents.upload({
libraryId: "a02150d9-5ee0-4877-b62c-28b1fcdf3b76",
requestBody: {
file: await openAsBlob("example.file"),
},
});
console.log(result);
}
run();
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.prompts.list(undefined, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
for await (const page of result) {
console.log(page);
}
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.prompts.list();
for await (const page of result) {
console.log(page);
}
}
run();
MistralError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
|---|---|---|
error.message | string | Error message |
error.statusCode | number | HTTP response status code eg 404 |
error.headers | Headers | HTTP response headers |
error.body | string | HTTP body. Can be empty string if no body is returned. |
error.rawResponse | Response | Raw HTTP response |
error.data$ | Optional. Some errors may contain structured data. See Error Classes. |
import { Mistral } from "@mistralai/mistralai";
import * as errors from "@mistralai/mistralai/models/errors";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
try {
const result = await mistral.beta.serviceAccounts.create({
name: "<value>",
workspaceId: "cf2146d0-158c-4b19-b8b1-ca0c68f41143",
});
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.MistralError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.HTTPValidationError) {
console.log(error.data$.detail); // ValidationError[]
}
}
}
}
run();
Primary error:
MistralError: The base class for HTTP error responses.Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.Inherit from MistralError:
HTTPValidationError: Validation Error. Status code 422. Applicable to 165 of 278 methods.*ObservabilityError: Bad Request - Invalid request parameters or data. Applicable to 69 of 278 methods.*ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. See error.rawValue for the raw value and error.pretty() for a nicely formatted multi-line string.* Check the method documentation to see if the error is applicable.
You can override the default server globally by passing a server name to the server: keyof typeof ServerList optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:
| Name | Server | Description |
|---|---|---|
global | https://api.mistral.ai | Global Production server |
eu | https://api.eu.mistral.ai | EU Production server |
us | https://api.us.mistral.ai | US Production server |
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
server: "global",
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.prompts.list();
for await (const page of result) {
console.log(page);
}
}
run();
The default server can also be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
serverURL: "https://api.mistral.ai",
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.prompts.list();
for await (const page of result) {
console.log(page);
}
}
run();
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to:
"beforeRequest" hook to add a custom header and a timeout to requests"requestError" hook to log errorsimport { Mistral } from "@mistralai/mistralai";
import { ProxyAgent } from "undici";
import { HTTPClient } from "@mistralai/mistralai/lib/http";
const dispatcher = new ProxyAgent("http://proxy.example.com:8080");
const httpClient = new HTTPClient({
// 'fetcher' takes a function that has the same signature as native 'fetch'.
fetcher: (input, init) =>
// 'dispatcher' is specific to undici and not part of the standard Fetch API.
fetch(input, { ...init, dispatcher } as RequestInit),
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new Mistral({ httpClient: httpClient });
This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
|---|---|---|---|
apiKey | http | HTTP Bearer | MISTRAL_API_KEY |
To authenticate with the API the apiKey parameter must be set when initializing the SDK client instance. For example:
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.prompts.list();
for await (const page of result) {
console.log(page);
}
}
run();
Some operations in this SDK require the security scheme to be specified at the request level. For example:
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral();
async function run() {
const result = await mistral.beta.users.getIdentity({});
console.log(result);
}
run();
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
agentsComplete - Agents CompletionagentsStream - Stream Agents completionaudioSpeechComplete - SpeechaudioTranscriptionsComplete - Create TranscriptionaudioTranscriptionsStream - Create Streaming Transcription (SSE)audioVoicesCreate - Create a new voiceaudioVoicesDelete - Delete a custom voiceaudioVoicesGet - Get voice detailsaudioVoicesGetSampleAudio - Get voice sample audioaudioVoicesSearch - List voices, cursor-paginatedaudioVoicesUpdate - Update voice metadatabatchJobsCancel - Cancel Batch JobbatchJobsCreate - Create Batch JobbatchJobsDelete - Delete Batch JobbatchJobsGet - Get Batch JobbatchJobsList - Get Batch JobsbetaAgentsCreate - Create a agent that can be used within a conversation.betaAgentsCreateVersionAlias - Create or update an agent version alias.betaAgentsDelete - Delete an agent entity.betaAgentsDeleteVersionAlias - Delete an agent version alias.betaAgentsGet - Retrieve an agent entity.betaAgentsGetVersion - Retrieve a specific version of an agent.betaAgentsListPages - List agent entities, cursor-paginated.betaAgentsListVersionAliases - List all aliases for an agent.betaAgentsListVersions - List all versions of an agent.betaAgentsUpdate - Update an agent entity.betaAgentsUpdateVersion - Update an agent version.betaConnectorsActivateForConsumer - Activate a connector for the given consumer (organization, workspace, user).betaConnectorsCreate - Create a new connector.betaConnectorsCreateCredentials - Create consumer credentials for a connector.betaConnectorsDeactivateForConsumer - Deactivate a connector for the current consumer (at organization, workspace or user level).betaConnectorsDelete - Delete a connector.betaConnectorsDeleteAllUserCredentials - Delete all user credentials for a connector.betaConnectorsDeleteCredentials - Delete credentials for a consumer.betaConnectorsGet - Get a connector.betaConnectorsGetAuthenticationMethods - Get authentication methods for a connector.betaConnectorsGetAuthUrl - Get the auth URL for a connector.betaConnectorsList - List all connectors.betaConnectorsListOrganizationCredentials - List organization credentials for a connector.betaConnectorsListTools - List tools for a connector.betaConnectorsListUserCredentials - List user credentials for a connector.betaConnectorsListWorkspaceCredentials - List workspace credentials for a connector.betaConnectorsShare - Share a private connector to the current workspace.betaConnectorsShareToOrganization - Share a connector to the current organization.betaConnectorsUnshare - Unshare a connector from the current workspace.betaConnectorsUnshareFromOrganization - Unshare a connector from the current organization.betaConnectorsUpdate - Update a connector.betaConnectorsUpdateCredentials - Create or update consumer credentials for a connector.betaConversationsAppend - Append new entries to an existing conversation.betaConversationsAppendStream - Append new entries to an existing conversation.betaConversationsDelete - Delete a conversation.betaConversationsGet - Retrieve a conversation information.betaConversationsGetHistory - Retrieve all entries in a conversation.betaConversationsGetMessages - Retrieve all messages in a conversation.betaConversationsList - List all created conversations.betaConversationsRestart - Restart a conversation starting from a given entry.betaConversationsRestartStream - Restart a conversation starting from a given entry.betaConversationsStart - Create a conversation and append entries to it.betaConversationsStartStream - Create a conversation and append entries to it.betaLibrariesAccessesDelete - Delete an access level.betaLibrariesAccessesList - List all of the access to this library.betaLibrariesAccessesUpdateOrCreate - Create or update an access level.betaLibrariesCreate - Create a new Library.betaLibrariesDelete - Delete a library and all of it's document.betaLibrariesDocumentsDelete - Delete a document.betaLibrariesDocumentsExtractedTextSignedUrl - Retrieve the signed URL of text extracted from a given document.betaLibrariesDocumentsGet - Retrieve the metadata of a specific document.betaLibrariesDocumentsGetSignedUrl - Retrieve the signed URL of a specific document.betaLibrariesDocumentsList - List documents in a given library.betaLibrariesDocumentsReprocess - Reprocess a document.betaLibrariesDocumentsStatus - Retrieve the processing status of a specific document.betaLibrariesDocumentsTextContent - Retrieve the text content of a specific document.betaLibrariesDocumentsUpdate - Update the metadata of a specific document.betaLibrariesDocumentsUpload - Upload a new document.betaLibrariesGet - Detailed information about a specific Library.betaLibrariesList - List all libraries you have access to.betaLibrariesUpdate - Update a library.betaObservabilityDatasetsCreate - Create a new empty datasetbetaObservabilityDatasetsCreateRecord - Add a record to the datasetbetaObservabilityDatasetsDelete - Delete a datasetbetaObservabilityDatasetsExportToJsonl - Export to the Files API and retrieve presigned URL to download the resulting JSONL filebetaObservabilityDatasetsFetch - Get dataset by ID or slugbetaObservabilityDatasetsFetchTask - Get status of a dataset import taskbetaObservabilityDatasetsImportFromDatasetRecords - Populate the dataset with records from another datasetbetaObservabilityDatasetsImportFromFile - Populate the dataset with records from an uploaded filebetaObservabilityDatasetsImportFromPlayground - Populate the dataset with records from playground conversationsbetaObservabilityDatasetsImportFromSpans - Populate the dataset with records mapped from telemetry spansbetaObservabilityDatasetsList - List existing datasetsbetaObservabilityDatasetsListRecords - List existing records in the datasetbetaObservabilityDatasetsListTasks - List import tasks for the given datasetbetaObservabilityDatasetsRecordsBulkDelete - Delete multiple records from datasetsbetaObservabilityDatasetsRecordsDelete - Delete a record from a datasetbetaObservabilityDatasetsRecordsFetch - Get the content of a given dataset recordbetaObservabilityDatasetsRecordsJudge - Run Judge on a dataset record based on the given optionsbetaObservabilityDatasetsRecordsUpdatePayload - Update a dataset record payloadbetaObservabilityDatasetsRecordsUpdateProperties - Update dataset record propertiesbetaObservabilityDatasetsUpdate - Patch datasetbetaObservabilityEvaluationsCreatePipeline - Create a pipelinebetaObservabilityEvaluationsCreatePipelineConfig - Create a worker pipeline configurationbetaObservabilityEvaluationsDeletePipeline - Delete a pipelinebetaObservabilityEvaluationsDeletePipelineConfig - Delete a worker pipeline configurationbetaObservabilityEvaluationsGet - Get evaluation by slugbetaObservabilityEvaluationsGetPipeline - Get a pipelinebetaObservabilityEvaluationsGetPipelineConfig - Get a worker pipeline configurationbetaObservabilityEvaluationsList - List evaluations for a projectbetaObservabilityEvaluationsListPipelineConfigs - List worker pipeline configurationsbetaObservabilityEvaluationsListPipelines - List pipelinesbetaObservabilityEvaluationsOptimizationsGet - Get an optimization by id (with its anchored evaluation + project)betaObservabilityEvaluationsOptimizationsList - List optimizations with optional filtersbetaObservabilityEvaluationsOptimizationsListTrials - List an optimization's trials with their observation runs (paginated)betaObservabilityEvaluationsProjectsGet - Get project by slugbetaObservabilityEvaluationsProjectsList - List projectsbetaObservabilityEvaluationsRecordsGet - Get a specific record from an evaluation runbetaObservabilityEvaluationsRecordsSearch - Search records for an evaluation run with content filtersbetaObservabilityEvaluationsRunsComputeStatistics - Compute statistics for a specific evaluation run with optional filtersbetaObservabilityEvaluationsRunsGet - Get a specific evaluation run by IDbetaObservabilityEvaluationsRunsGetStatistics - Get statistics for a specific evaluation runbetaObservabilityEvaluationsRunsSearch - Search evaluation runs with filtersbetaObservabilityEvaluationsRunsSearchAll - Search evaluation runs across all evaluationsbetaObservabilityEvaluationsUpdatePipeline - Update a pipelinebetaObservabilityEvaluationsUpdatePipelineConfig - Replace a worker pipeline configurationbetaObservabilityJudgesCreate - Create a new judgebetaObservabilityJudgesDelete - Delete a judgebetaObservabilityJudgesFetch - Get judge by idbetaObservabilityJudgesJudgeConversation - Run a saved judge on a conversationbetaObservabilityJudgesList - Get judges with optional filtering and searchbetaObservabilityJudgesUpdate - Update a judgebetaObservabilityLogsFetchOptions - Get options for a log fieldbetaObservabilityLogsList - Get log field definitionsbetaObservabilityLogsSearch - Search logsbetaObservabilitySpansAggregate - Aggregate spansbetaObservabilitySpansAggregateSpanEvaluations - Aggregate span evaluationsbetaObservabilitySpansFetchSpanEvalFieldOptions - Get options for a span evaluation fieldbetaObservabilitySpansFetchSpanFieldOptions - Get options for a span fieldbetaObservabilitySpansListSpanEvalFields - Get span evaluation field definitionsbetaObservabilitySpansListSpanFields - Get span field definitionsbetaObservabilitySpansSearchLatestSpanEvaluations - Search latest span evaluationsbetaObservabilitySpansSearchSpanEvaluations - Search span evaluationsbetaObservabilitySpansSearchSpans - Search spansbetaObservabilityTracesAggregate - Aggregate tracesbetaObservabilityTracesFetchOptions - Get options for a trace fieldbetaObservabilityTracesGetSpanById - Get span by idbetaObservabilityTracesGetTraceById - Get trace by idbetaObservabilityTracesGetTraceFields - Get trace field definitionsbetaObservabilityTracesGetTraceSpans - Get trace spansbetaObservabilityTracesSearch - Search tracesbetaPromptsCreate - CreatePromptbetaPromptsCreateVersion - CreatePromptVersionbetaPromptsDelete - DeletePromptbetaPromptsGet - GetPromptbetaPromptsGetVersion - GetPromptVersionbetaPromptsList - ListPromptsbetaPromptsListVersions - ListPromptVersionsbetaPromptsUpdateMetadata - UpdatePromptbetaPromptsUpdateVersionMetadata - UpdatePromptVersionMetadatabetaRagIngestionPipelineConfigurationsList - List ingestion pipeline configurationsbetaRagIngestionPipelineConfigurationsRegister - Register ConfigbetaRagIngestionPipelineConfigurationsUpdateRunInfo - Update Run InfobetaRagManagedIndexesCreate - Create a managed indexbetaRagManagedIndexesDelete - Delete a managed indexbetaRagManagedIndexesDeleteDocuments - Delete documents from a managed indexbetaRagManagedIndexesGet - Get a managed indexbetaRagManagedIndexesGetChunk - Get a single chunk by idbetaRagManagedIndexesGrep - Grep for a pattern within a sourcebetaRagManagedIndexesIngestDocuments - Ingest documents into a managed indexbetaRagManagedIndexesList - List managed indexesbetaRagManagedIndexesNavigate - Navigate to adjacent chunksbetaRagManagedIndexesRead - Read chunks within a spanbetaRagManagedIndexesSearch - Search a managed indexbetaRagManagedIndexesUpdate - Update a managed index schemabetaRagSearchIndexesGetDeploymentSummaries - Get Deployment SummariesbetaRagSearchIndexesRegisterDeployment - Register (or re-register) a search indexbetaRagSearchIndexesUnregisterDeployment - Unregister DeploymentbetaRagSearchIndexesUpdateIndexMetrics - Update Index MetricsbetaServiceAccountsCreate - Create Service AccountbetaServiceAccountsDelete - Delete Service AccountbetaServiceAccountsGet - Get Service AccountbetaServiceAccountsList - List Service AccountsbetaServiceAccountsListAssignableRoles - List Assignable Service Account RolesbetaServiceAccountsListRoles - List Service Account RolesbetaServiceAccountsSetRoles - Set Service Account RolesbetaServiceAccountsUpdate - Update Service AccountbetaSkillsCreate - CreateSkillbetaSkillsCreateVersion - CreateSkillVersionbetaSkillsDelete - DeleteSkillbetaSkillsGet - GetSkillbetaSkillsGetVersion - GetSkillVersionbetaSkillsList - ListSkillsbetaSkillsListVersions - ListSkillVersionsbetaSkillsUpdateMetadata - UpdateSkillbetaSkillsUpdateVersionMetadata - UpdateSkillVersionMetadatabetaUsersGetIdentity - Get IdentitybetaUsersListOrganizations - List OrganizationsbetaUsersListWorkspaces - List WorkspaceschatComplete - Chat CompletionchatStream - Stream chat completionclassifiersClassify - ClassificationsclassifiersClassifyChat - Chat ClassificationsclassifiersModerate - ModerationsclassifiersModerateChat - Chat ModerationsembeddingsCreate - EmbeddingseventsGetStreamEvents - Get Stream EventseventsGetStreamEvents - Get Stream EventseventsGetWorkflowEvents - Get Workflow EventseventsGetWorkflowEvents - Get Workflow EventsfilesDelete - Delete FilefilesDownload - Download FilefilesGetSignedUrl - Get Signed UrlfilesList - List FilesfilesRetrieve - Retrieve FilefilesUpload - Upload FilefimComplete - Fim CompletionfimStream - Stream fim completionmodelsArchive - Archive Fine Tuned ModelmodelsDelete - Delete ModelmodelsList - List ModelsmodelsRetrieve - Retrieve ModelmodelsUnarchive - Unarchive Fine Tuned ModelmodelsUpdate - Update Fine Tuned ModelocrProcess - OCRrealtimeSessionsCreate - Create Client SessionworkflowsArchiveWorkflow - Archive WorkflowworkflowsBulkArchiveWorkflows - Bulk Archive WorkflowsworkflowsBulkUnarchiveWorkflows - Bulk Unarchive WorkflowsworkflowsDeploymentsCreateDeployment - Create DeploymentworkflowsDeploymentsDeleteDeployment - Delete DeploymentworkflowsDeploymentsGetDeployment - Get DeploymentworkflowsDeploymentsGetDeploymentLogs - Get Deployment LogsworkflowsDeploymentsListDeployments - List DeploymentsworkflowsDeploymentsListDeploymentWorkers - List Deployment WorkersworkflowsDeploymentsRestartDeployment - Restart DeploymentworkflowsDeploymentsStartDeployment - Start DeploymentworkflowsDeploymentsStopDeployment - Stop DeploymentworkflowsDeploymentsStreamDeploymentLogs - Stream Deployment LogsworkflowsDeploymentsUnhardenDeployment - Unharden DeploymentworkflowsDeploymentsUpdateDeployment - Update DeploymentworkflowsExecuteWorkflow - Execute WorkflowworkflowsExecutionsBatchCancelWorkflowExecutions - Batch Cancel Workflow ExecutionsworkflowsExecutionsBatchTerminateWorkflowExecutions - Batch Terminate Workflow ExecutionsworkflowsExecutionsCancelWorkflowExecution - Cancel Workflow ExecutionworkflowsExecutionsGetWorkflowExecution - Get Workflow ExecutionworkflowsExecutionsGetWorkflowExecutionHistory - Get Workflow Execution HistoryworkflowsExecutionsGetWorkflowExecutionLogs - Get Workflow Execution LogsworkflowsExecutionsGetWorkflowExecutionTraceEvents - Get Workflow Execution Trace EventsworkflowsExecutionsGetWorkflowExecutionTraceInfo - Get Workflow Execution Trace InfoworkflowsExecutionsGetWorkflowExecutionTraceOtel - Get Workflow Execution Trace OtelworkflowsExecutionsGetWorkflowExecutionTraceSummary - Get Workflow Execution Trace SummaryworkflowsExecutionsQueryWorkflowExecution - Query Workflow ExecutionworkflowsExecutionsResetWorkflow - Reset WorkflowworkflowsExecutionsSignalWorkflowExecution - Signal Workflow ExecutionworkflowsExecutionsStream - StreamworkflowsExecutionsStreamWorkflowExecutionLogs - Stream Workflow Execution LogsworkflowsExecutionsTerminateWorkflowExecution - Terminate Workflow ExecutionworkflowsExecutionsUpdateWorkflowExecution - Update Workflow ExecutionworkflowsGetWorkflow - Get WorkflowworkflowsGetWorkflowRegistration - Get Workflow RegistrationworkflowsGetWorkflowRegistrations - Get Workflow RegistrationsworkflowsGetWorkflows - Get WorkflowsworkflowsMetricsGetWorkflowMetrics - Get Workflow MetricsworkflowsRunsGetRun - Get RunworkflowsRunsGetRunHistory - Get Run HistoryworkflowsRunsListRuns - List RunsworkflowsSchedulesGetSchedule - Get ScheduleworkflowsSchedulesGetSchedules - Get SchedulesworkflowsSchedulesPauseSchedule - Pause ScheduleworkflowsSchedulesResumeSchedule - Resume ScheduleworkflowsSchedulesScheduleWorkflow - Schedule WorkflowworkflowsSchedulesTriggerSchedule - Trigger ScheduleworkflowsSchedulesUnscheduleWorkflow - Unschedule WorkflowworkflowsSchedulesUpdateSchedule - Update ScheduleworkflowsUnarchiveWorkflow - Unarchive WorkflowworkflowsUpdateWorkflow - Update WorkflowaudioVoicesListaudioVoicesSearch instead.betaAgentsListbetaAgentsListPages instead.betaConnectorsCallToolbetaLibrariesDocumentsLibrariesDocumentsUpdateV1betaLibrariesLibrariesUpdateV1workflowsExecuteWorkflowRegistrationYou can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { Mistral } from "@mistralai/mistralai";
const sdk = new Mistral({ debugLogger: console });
You can also enable a default debug logger by setting an environment variable MISTRAL_DEBUG to true.
The SDK can emit OpenTelemetry traces for the API calls it makes (chat, agents, embeddings, OCR, …), following the
GenAI semantic conventions.
Spans capture the operation, model, token usage, and — unless redacted — the input/output messages and tool calls. Telemetry is opt-in and lives in the @mistralai/mistralai/extra/observability module.
Dedicated mode loads the OpenTelemetry SDK and OTLP exporter on demand. Install them alongside the client:
npm install @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources
Either set an environment variable before creating the client:
export MISTRAL_SDK_TELEMETRY=dedicated # dedicated | global | false
or configure it in code:
import { Mistral } from "@mistralai/mistralai";
import { configureTelemetry } from "@mistralai/mistralai/extra/observability";
const client = new Mistral({ apiKey: process.env["MISTRAL_API_KEY"] });
// Dedicated mode (default): the SDK creates and owns an OTLP exporter that ships
// spans to the Mistral telemetry endpoint. Spans are redacted before export.
await configureTelemetry(client);
const response = await client.chat.complete({
model: "mistral-small-latest",
messages: [{ role: "user", content: "Hello!" }],
});
configureTelemetry(client, provider) selects where spans go and who owns the export pipeline:
provider | Who owns the exporter | Where spans go | Redaction |
|---|---|---|---|
"dedicated" (default) | The SDK | Mistral telemetry endpoint | Applied automatically |
"global" | Your application | Your global OpenTelemetry provider | Not applied — you need to wrap your own exporter |
a TracerProvider | Your application | The provider you pass | Not applied — you need to wrap your own exporter |
In global/custom modes your application owns the pipeline, so the redaction option is ignored (a warning is logged). Wrap your own exporter with RedactingSpanExporter to redact spans there:
import { trace } from "@opentelemetry/api";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { BasicTracerProvider, BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { Mistral } from "@mistralai/mistralai";
import { configureTelemetry, RedactingSpanExporter } from "@mistralai/mistralai/extra/observability";
const provider = new BasicTracerProvider({
spanProcessors: [
new BatchSpanProcessor(new RedactingSpanExporter(new OTLPTraceExporter())),
],
});
trace.setGlobalTracerProvider(provider);
const client = new Mistral({ apiKey: process.env["MISTRAL_API_KEY"] });
// SDK spans now flow through your global provider (already redacted above).
await configureTelemetry(client, "global");
In dedicated mode, redaction is on by default. Control it with the redaction option, which also accepts any of the reusable policies from @mistralai/mistralai/extra/observability:
import { AttributeRedactionPolicy } from "@mistralai/mistralai/extra/observability";
await configureTelemetry(client); // default policy (regex)
await configureTelemetry(client, "dedicated", { redaction: new AttributeRedactionPolicy() }); // very conservative key-oriented policy
await configureTelemetry(client, "dedicated", { redaction: false }); // disabled - no redaction
await configureTelemetry(client, "dedicated", { // custom callback to control how attributes get redacted
redaction: (key, value) => (key.includes("email") ? undefined : value),
});
| Policy | Strategy | Trade-off |
|---|---|---|
RegexRedactionPolicy (default, redaction: true) | Content-oriented: keeps keys and structure, redacts matched substrings (secret tokens plus PII — emails, card-like sequences, IPv4). | Redacts most sensitive data while preserving observability value; may miss free-form PII or secrets not in the pattern set. |
AttributeRedactionPolicy | Key-oriented: redacts whole values for sensitive keys (explicit set, fragment match, or non-primitive value), then scans kept values for secret token patterns. | Very conservative, but erases most prompt/response content. |
CallbackRedactionPolicy (redaction: <callback>) | Your (key, value) => value | undefined masker per attribute; return undefined to drop the attribute. | Full control; you own the logic. |
The built-in defaults are exported as constants, so you can extend them instead of replacing them wholesale:
import {
AttributeRedactionPolicy,
DEFAULT_PII_SECRET_PATTERNS,
DEFAULT_SENSITIVE_ATTRIBUTE_KEYS,
RegexRedactionPolicy,
configureTelemetry,
} from "@mistralai/mistralai/extra/observability";
// Content-oriented: add a custom secret pattern to the default set.
await configureTelemetry(client, "dedicated", {
redaction: new RegexRedactionPolicy([...DEFAULT_PII_SECRET_PATTERNS, /\bacme-[a-z0-9]{16}\b/g]),
});
// Key-oriented: mask an extra application attribute on top of the defaults.
await configureTelemetry(client, "dedicated", {
redaction: new AttributeRedactionPolicy({
sensitiveKeys: new Set([...DEFAULT_SENSITIVE_ATTRIBUTE_KEYS, "app.customer.email"]),
}),
});
Note: the RedactingSpanExporter primitive is reusable by any OpenTelemetry application, independent of the Mistral client.
| Variable | Description | Default |
|---|---|---|
MISTRAL_SDK_TELEMETRY | Auto-enable telemetry: dedicated, global, or false. | unset (disabled) |
MISTRAL_OTLP_TRACES_ENDPOINT | Override the OTLP traces endpoint used in dedicated mode. | https://api.mistral.ai/telemetry/v1/traces |
MISTRAL_API_KEY | Used as the bearer token for the dedicated-mode exporter. | — |
Runnable examples live in examples/src/observability.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
56 followers · starred Mar 2025
171 followers · starred Dec 2024
51 followers · starred Mar 2026
89 followers · starred Jan 2026
This is v2 of the Mistral TypeScript SDK.
Key changes from v1: ESM-only, shorter type names, forward-compatible enums/unions, Zod v4. See the Migration Guide for full details.
To pin v1:
npm install @mistralai/mistralai@^1· v1 documentation and source
Mistral AI API: Our Chat Completion and Embeddings APIs specification. Create your account on La Plateforme to get access and read the docs to learn how to use it.
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
npm add @mistralai/mistralai
pnpm add @mistralai/mistralai
bun add @mistralai/mistralai
yarn add @mistralai/mistralai
[!NOTE] This package is published as an ES Module (ESM) only. For applications using CommonJS, use
await import("@mistralai/mistralai")to import and use this package.
For supported JavaScript runtimes, please consult RUNTIMES.md.
Before you begin, you will need a Mistral AI API key.
# set Mistral API Key (using zsh for example)
$ echo 'export MISTRAL_API_KEY=[your_key_here]' >> ~/.zshenv
# reload the environment (or just quit and open a new terminal)
$ source ~/.zshenv
Node workloads with a mounted service-account token can set MISTRAL_SA_TOKEN_PATH instead. The file is re-read on every request, so rotation is picked up. Credentials resolve in this order:
Authorization header passed per request via headersnew Mistral({ apiKey }), which also accepts an async functionMISTRAL_SA_TOKEN_PATHMISTRAL_API_KEYAn unreadable or empty token file fails the request with an UnexpectedClientError whose cause explains why.
This example shows how to create chat completions.
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.chat.complete({
model: "mistral-large-latest",
messages: [
{
role: "user",
content:
"Who is the best French painter? Answer in one short sentence.",
},
],
responseFormat: {
type: "text",
},
});
console.log(result);
}
run();
This example shows how to upload a file.
import { Mistral } from "@mistralai/mistralai";
import { openAsBlob } from "node:fs";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.files.upload({
file: await openAsBlob("example.file"),
});
console.log(result);
}
run();
This example shows how to create agents completions.
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.agents.complete({
messages: [
{
role: "user",
content:
"Who is the best French painter? Answer in one short sentence.",
},
],
responseFormat: {
type: "text",
},
agentId: "<id>",
});
console.log(result);
}
run();
This example shows how to create embedding request.
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.embeddings.create({
model: "mistral-embed",
inputs: [
"Embed this sentence.",
"As well as this one.",
],
});
console.log(result);
}
run();
We have dedicated SDKs for the following providers:
Server-sent events are used to stream content from certain
operations. These operations will expose the stream as an async iterable that
can be consumed using a for await...of loop. The loop will
terminate when the server no longer has any events to send and closes the
underlying connection.
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.conversations.startStream({
inputs: [
{
object: "entry",
type: "agent.handoff",
previousAgentId: "<id>",
previousAgentName: "<value>",
nextAgentId: "<id>",
nextAgentName: "<value>",
},
],
completionArgs: {
responseFormat: {
type: "text",
},
},
});
for await (const event of result) {
console.log(event);
}
}
run();
Some of the endpoints in this SDK support pagination. To use pagination, you
make your SDK calls as usual, but the returned response object will also be an
async iterable that can be consumed using the for await...of
syntax.
Here's an example of one such pagination call:
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.prompts.list();
for await (const page of result) {
console.log(page);
}
}
run();
Certain SDK methods accept files as part of a multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
[!TIP]
Depending on your JavaScript runtime, there are convenient utilities that return a handle to a file without reading the entire contents into memory:
- Node.js v20+: Since v20, Node.js comes with a native
openAsBlobfunction innode:fs.- Bun: The native
Bun.filefunction produces a file handle that can be used for streaming file uploads.- Browsers: All supported browsers return an instance to a
Filewhen reading the value from an<input type="file">element.- Node.js v18: A file stream can be created using the
fileFromhelper fromfetch-blob/from.js.
import { Mistral } from "@mistralai/mistralai";
import { openAsBlob } from "node:fs";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.libraries.documents.upload({
libraryId: "a02150d9-5ee0-4877-b62c-28b1fcdf3b76",
requestBody: {
file: await openAsBlob("example.file"),
},
});
console.log(result);
}
run();
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.prompts.list(undefined, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
for await (const page of result) {
console.log(page);
}
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.prompts.list();
for await (const page of result) {
console.log(page);
}
}
run();
MistralError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
|---|---|---|
error.message | string | Error message |
error.statusCode | number | HTTP response status code eg 404 |
error.headers | Headers | HTTP response headers |
error.body | string | HTTP body. Can be empty string if no body is returned. |
error.rawResponse | Response | Raw HTTP response |
error.data$ | Optional. Some errors may contain structured data. See Error Classes. |
import { Mistral } from "@mistralai/mistralai";
import * as errors from "@mistralai/mistralai/models/errors";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
try {
const result = await mistral.beta.serviceAccounts.create({
name: "<value>",
workspaceId: "cf2146d0-158c-4b19-b8b1-ca0c68f41143",
});
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.MistralError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.HTTPValidationError) {
console.log(error.data$.detail); // ValidationError[]
}
}
}
}
run();
Primary error:
MistralError: The base class for HTTP error responses.Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.Inherit from MistralError:
HTTPValidationError: Validation Error. Status code 422. Applicable to 165 of 278 methods.*ObservabilityError: Bad Request - Invalid request parameters or data. Applicable to 69 of 278 methods.*ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. See error.rawValue for the raw value and error.pretty() for a nicely formatted multi-line string.* Check the method documentation to see if the error is applicable.
You can override the default server globally by passing a server name to the server: keyof typeof ServerList optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:
| Name | Server | Description |
|---|---|---|
global | https://api.mistral.ai | Global Production server |
eu | https://api.eu.mistral.ai | EU Production server |
us | https://api.us.mistral.ai | US Production server |
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
server: "global",
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.prompts.list();
for await (const page of result) {
console.log(page);
}
}
run();
The default server can also be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
serverURL: "https://api.mistral.ai",
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.prompts.list();
for await (const page of result) {
console.log(page);
}
}
run();
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to:
"beforeRequest" hook to add a custom header and a timeout to requests"requestError" hook to log errorsimport { Mistral } from "@mistralai/mistralai";
import { ProxyAgent } from "undici";
import { HTTPClient } from "@mistralai/mistralai/lib/http";
const dispatcher = new ProxyAgent("http://proxy.example.com:8080");
const httpClient = new HTTPClient({
// 'fetcher' takes a function that has the same signature as native 'fetch'.
fetcher: (input, init) =>
// 'dispatcher' is specific to undici and not part of the standard Fetch API.
fetch(input, { ...init, dispatcher } as RequestInit),
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new Mistral({ httpClient: httpClient });
This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
|---|---|---|---|
apiKey | http | HTTP Bearer | MISTRAL_API_KEY |
To authenticate with the API the apiKey parameter must be set when initializing the SDK client instance. For example:
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral({
apiKey: process.env["MISTRAL_API_KEY"] ?? "",
});
async function run() {
const result = await mistral.beta.prompts.list();
for await (const page of result) {
console.log(page);
}
}
run();
Some operations in this SDK require the security scheme to be specified at the request level. For example:
import { Mistral } from "@mistralai/mistralai";
const mistral = new Mistral();
async function run() {
const result = await mistral.beta.users.getIdentity({});
console.log(result);
}
run();
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
agentsComplete - Agents CompletionagentsStream - Stream Agents completionaudioSpeechComplete - SpeechaudioTranscriptionsComplete - Create TranscriptionaudioTranscriptionsStream - Create Streaming Transcription (SSE)audioVoicesCreate - Create a new voiceaudioVoicesDelete - Delete a custom voiceaudioVoicesGet - Get voice detailsaudioVoicesGetSampleAudio - Get voice sample audioaudioVoicesSearch - List voices, cursor-paginatedaudioVoicesUpdate - Update voice metadatabatchJobsCancel - Cancel Batch JobbatchJobsCreate - Create Batch JobbatchJobsDelete - Delete Batch JobbatchJobsGet - Get Batch JobbatchJobsList - Get Batch JobsbetaAgentsCreate - Create a agent that can be used within a conversation.betaAgentsCreateVersionAlias - Create or update an agent version alias.betaAgentsDelete - Delete an agent entity.betaAgentsDeleteVersionAlias - Delete an agent version alias.betaAgentsGet - Retrieve an agent entity.betaAgentsGetVersion - Retrieve a specific version of an agent.betaAgentsListPages - List agent entities, cursor-paginated.betaAgentsListVersionAliases - List all aliases for an agent.betaAgentsListVersions - List all versions of an agent.betaAgentsUpdate - Update an agent entity.betaAgentsUpdateVersion - Update an agent version.betaConnectorsActivateForConsumer - Activate a connector for the given consumer (organization, workspace, user).betaConnectorsCreate - Create a new connector.betaConnectorsCreateCredentials - Create consumer credentials for a connector.betaConnectorsDeactivateForConsumer - Deactivate a connector for the current consumer (at organization, workspace or user level).betaConnectorsDelete - Delete a connector.betaConnectorsDeleteAllUserCredentials - Delete all user credentials for a connector.betaConnectorsDeleteCredentials - Delete credentials for a consumer.betaConnectorsGet - Get a connector.betaConnectorsGetAuthenticationMethods - Get authentication methods for a connector.betaConnectorsGetAuthUrl - Get the auth URL for a connector.betaConnectorsList - List all connectors.betaConnectorsListOrganizationCredentials - List organization credentials for a connector.betaConnectorsListTools - List tools for a connector.betaConnectorsListUserCredentials - List user credentials for a connector.betaConnectorsListWorkspaceCredentials - List workspace credentials for a connector.betaConnectorsShare - Share a private connector to the current workspace.betaConnectorsShareToOrganization - Share a connector to the current organization.betaConnectorsUnshare - Unshare a connector from the current workspace.betaConnectorsUnshareFromOrganization - Unshare a connector from the current organization.betaConnectorsUpdate - Update a connector.betaConnectorsUpdateCredentials - Create or update consumer credentials for a connector.betaConversationsAppend - Append new entries to an existing conversation.betaConversationsAppendStream - Append new entries to an existing conversation.betaConversationsDelete - Delete a conversation.betaConversationsGet - Retrieve a conversation information.betaConversationsGetHistory - Retrieve all entries in a conversation.betaConversationsGetMessages - Retrieve all messages in a conversation.betaConversationsList - List all created conversations.betaConversationsRestart - Restart a conversation starting from a given entry.betaConversationsRestartStream - Restart a conversation starting from a given entry.betaConversationsStart - Create a conversation and append entries to it.betaConversationsStartStream - Create a conversation and append entries to it.betaLibrariesAccessesDelete - Delete an access level.betaLibrariesAccessesList - List all of the access to this library.betaLibrariesAccessesUpdateOrCreate - Create or update an access level.betaLibrariesCreate - Create a new Library.betaLibrariesDelete - Delete a library and all of it's document.betaLibrariesDocumentsDelete - Delete a document.betaLibrariesDocumentsExtractedTextSignedUrl - Retrieve the signed URL of text extracted from a given document.betaLibrariesDocumentsGet - Retrieve the metadata of a specific document.betaLibrariesDocumentsGetSignedUrl - Retrieve the signed URL of a specific document.betaLibrariesDocumentsList - List documents in a given library.betaLibrariesDocumentsReprocess - Reprocess a document.betaLibrariesDocumentsStatus - Retrieve the processing status of a specific document.betaLibrariesDocumentsTextContent - Retrieve the text content of a specific document.betaLibrariesDocumentsUpdate - Update the metadata of a specific document.betaLibrariesDocumentsUpload - Upload a new document.betaLibrariesGet - Detailed information about a specific Library.betaLibrariesList - List all libraries you have access to.betaLibrariesUpdate - Update a library.betaObservabilityDatasetsCreate - Create a new empty datasetbetaObservabilityDatasetsCreateRecord - Add a record to the datasetbetaObservabilityDatasetsDelete - Delete a datasetbetaObservabilityDatasetsExportToJsonl - Export to the Files API and retrieve presigned URL to download the resulting JSONL filebetaObservabilityDatasetsFetch - Get dataset by ID or slugbetaObservabilityDatasetsFetchTask - Get status of a dataset import taskbetaObservabilityDatasetsImportFromDatasetRecords - Populate the dataset with records from another datasetbetaObservabilityDatasetsImportFromFile - Populate the dataset with records from an uploaded filebetaObservabilityDatasetsImportFromPlayground - Populate the dataset with records from playground conversationsbetaObservabilityDatasetsImportFromSpans - Populate the dataset with records mapped from telemetry spansbetaObservabilityDatasetsList - List existing datasetsbetaObservabilityDatasetsListRecords - List existing records in the datasetbetaObservabilityDatasetsListTasks - List import tasks for the given datasetbetaObservabilityDatasetsRecordsBulkDelete - Delete multiple records from datasetsbetaObservabilityDatasetsRecordsDelete - Delete a record from a datasetbetaObservabilityDatasetsRecordsFetch - Get the content of a given dataset recordbetaObservabilityDatasetsRecordsJudge - Run Judge on a dataset record based on the given optionsbetaObservabilityDatasetsRecordsUpdatePayload - Update a dataset record payloadbetaObservabilityDatasetsRecordsUpdateProperties - Update dataset record propertiesbetaObservabilityDatasetsUpdate - Patch datasetbetaObservabilityEvaluationsCreatePipeline - Create a pipelinebetaObservabilityEvaluationsCreatePipelineConfig - Create a worker pipeline configurationbetaObservabilityEvaluationsDeletePipeline - Delete a pipelinebetaObservabilityEvaluationsDeletePipelineConfig - Delete a worker pipeline configurationbetaObservabilityEvaluationsGet - Get evaluation by slugbetaObservabilityEvaluationsGetPipeline - Get a pipelinebetaObservabilityEvaluationsGetPipelineConfig - Get a worker pipeline configurationbetaObservabilityEvaluationsList - List evaluations for a projectbetaObservabilityEvaluationsListPipelineConfigs - List worker pipeline configurationsbetaObservabilityEvaluationsListPipelines - List pipelinesbetaObservabilityEvaluationsOptimizationsGet - Get an optimization by id (with its anchored evaluation + project)betaObservabilityEvaluationsOptimizationsList - List optimizations with optional filtersbetaObservabilityEvaluationsOptimizationsListTrials - List an optimization's trials with their observation runs (paginated)betaObservabilityEvaluationsProjectsGet - Get project by slugbetaObservabilityEvaluationsProjectsList - List projectsbetaObservabilityEvaluationsRecordsGet - Get a specific record from an evaluation runbetaObservabilityEvaluationsRecordsSearch - Search records for an evaluation run with content filtersbetaObservabilityEvaluationsRunsComputeStatistics - Compute statistics for a specific evaluation run with optional filtersbetaObservabilityEvaluationsRunsGet - Get a specific evaluation run by IDbetaObservabilityEvaluationsRunsGetStatistics - Get statistics for a specific evaluation runbetaObservabilityEvaluationsRunsSearch - Search evaluation runs with filtersbetaObservabilityEvaluationsRunsSearchAll - Search evaluation runs across all evaluationsbetaObservabilityEvaluationsUpdatePipeline - Update a pipelinebetaObservabilityEvaluationsUpdatePipelineConfig - Replace a worker pipeline configurationbetaObservabilityJudgesCreate - Create a new judgebetaObservabilityJudgesDelete - Delete a judgebetaObservabilityJudgesFetch - Get judge by idbetaObservabilityJudgesJudgeConversation - Run a saved judge on a conversationbetaObservabilityJudgesList - Get judges with optional filtering and searchbetaObservabilityJudgesUpdate - Update a judgebetaObservabilityLogsFetchOptions - Get options for a log fieldbetaObservabilityLogsList - Get log field definitionsbetaObservabilityLogsSearch - Search logsbetaObservabilitySpansAggregate - Aggregate spansbetaObservabilitySpansAggregateSpanEvaluations - Aggregate span evaluationsbetaObservabilitySpansFetchSpanEvalFieldOptions - Get options for a span evaluation fieldbetaObservabilitySpansFetchSpanFieldOptions - Get options for a span fieldbetaObservabilitySpansListSpanEvalFields - Get span evaluation field definitionsbetaObservabilitySpansListSpanFields - Get span field definitionsbetaObservabilitySpansSearchLatestSpanEvaluations - Search latest span evaluationsbetaObservabilitySpansSearchSpanEvaluations - Search span evaluationsbetaObservabilitySpansSearchSpans - Search spansbetaObservabilityTracesAggregate - Aggregate tracesbetaObservabilityTracesFetchOptions - Get options for a trace fieldbetaObservabilityTracesGetSpanById - Get span by idbetaObservabilityTracesGetTraceById - Get trace by idbetaObservabilityTracesGetTraceFields - Get trace field definitionsbetaObservabilityTracesGetTraceSpans - Get trace spansbetaObservabilityTracesSearch - Search tracesbetaPromptsCreate - CreatePromptbetaPromptsCreateVersion - CreatePromptVersionbetaPromptsDelete - DeletePromptbetaPromptsGet - GetPromptbetaPromptsGetVersion - GetPromptVersionbetaPromptsList - ListPromptsbetaPromptsListVersions - ListPromptVersionsbetaPromptsUpdateMetadata - UpdatePromptbetaPromptsUpdateVersionMetadata - UpdatePromptVersionMetadatabetaRagIngestionPipelineConfigurationsList - List ingestion pipeline configurationsbetaRagIngestionPipelineConfigurationsRegister - Register ConfigbetaRagIngestionPipelineConfigurationsUpdateRunInfo - Update Run InfobetaRagManagedIndexesCreate - Create a managed indexbetaRagManagedIndexesDelete - Delete a managed indexbetaRagManagedIndexesDeleteDocuments - Delete documents from a managed indexbetaRagManagedIndexesGet - Get a managed indexbetaRagManagedIndexesGetChunk - Get a single chunk by idbetaRagManagedIndexesGrep - Grep for a pattern within a sourcebetaRagManagedIndexesIngestDocuments - Ingest documents into a managed indexbetaRagManagedIndexesList - List managed indexesbetaRagManagedIndexesNavigate - Navigate to adjacent chunksbetaRagManagedIndexesRead - Read chunks within a spanbetaRagManagedIndexesSearch - Search a managed indexbetaRagManagedIndexesUpdate - Update a managed index schemabetaRagSearchIndexesGetDeploymentSummaries - Get Deployment SummariesbetaRagSearchIndexesRegisterDeployment - Register (or re-register) a search indexbetaRagSearchIndexesUnregisterDeployment - Unregister DeploymentbetaRagSearchIndexesUpdateIndexMetrics - Update Index MetricsbetaServiceAccountsCreate - Create Service AccountbetaServiceAccountsDelete - Delete Service AccountbetaServiceAccountsGet - Get Service AccountbetaServiceAccountsList - List Service AccountsbetaServiceAccountsListAssignableRoles - List Assignable Service Account RolesbetaServiceAccountsListRoles - List Service Account RolesbetaServiceAccountsSetRoles - Set Service Account RolesbetaServiceAccountsUpdate - Update Service AccountbetaSkillsCreate - CreateSkillbetaSkillsCreateVersion - CreateSkillVersionbetaSkillsDelete - DeleteSkillbetaSkillsGet - GetSkillbetaSkillsGetVersion - GetSkillVersionbetaSkillsList - ListSkillsbetaSkillsListVersions - ListSkillVersionsbetaSkillsUpdateMetadata - UpdateSkillbetaSkillsUpdateVersionMetadata - UpdateSkillVersionMetadatabetaUsersGetIdentity - Get IdentitybetaUsersListOrganizations - List OrganizationsbetaUsersListWorkspaces - List WorkspaceschatComplete - Chat CompletionchatStream - Stream chat completionclassifiersClassify - ClassificationsclassifiersClassifyChat - Chat ClassificationsclassifiersModerate - ModerationsclassifiersModerateChat - Chat ModerationsembeddingsCreate - EmbeddingseventsGetStreamEvents - Get Stream EventseventsGetStreamEvents - Get Stream EventseventsGetWorkflowEvents - Get Workflow EventseventsGetWorkflowEvents - Get Workflow EventsfilesDelete - Delete FilefilesDownload - Download FilefilesGetSignedUrl - Get Signed UrlfilesList - List FilesfilesRetrieve - Retrieve FilefilesUpload - Upload FilefimComplete - Fim CompletionfimStream - Stream fim completionmodelsArchive - Archive Fine Tuned ModelmodelsDelete - Delete ModelmodelsList - List ModelsmodelsRetrieve - Retrieve ModelmodelsUnarchive - Unarchive Fine Tuned ModelmodelsUpdate - Update Fine Tuned ModelocrProcess - OCRrealtimeSessionsCreate - Create Client SessionworkflowsArchiveWorkflow - Archive WorkflowworkflowsBulkArchiveWorkflows - Bulk Archive WorkflowsworkflowsBulkUnarchiveWorkflows - Bulk Unarchive WorkflowsworkflowsDeploymentsCreateDeployment - Create DeploymentworkflowsDeploymentsDeleteDeployment - Delete DeploymentworkflowsDeploymentsGetDeployment - Get DeploymentworkflowsDeploymentsGetDeploymentLogs - Get Deployment LogsworkflowsDeploymentsListDeployments - List DeploymentsworkflowsDeploymentsListDeploymentWorkers - List Deployment WorkersworkflowsDeploymentsRestartDeployment - Restart DeploymentworkflowsDeploymentsStartDeployment - Start DeploymentworkflowsDeploymentsStopDeployment - Stop DeploymentworkflowsDeploymentsStreamDeploymentLogs - Stream Deployment LogsworkflowsDeploymentsUnhardenDeployment - Unharden DeploymentworkflowsDeploymentsUpdateDeployment - Update DeploymentworkflowsExecuteWorkflow - Execute WorkflowworkflowsExecutionsBatchCancelWorkflowExecutions - Batch Cancel Workflow ExecutionsworkflowsExecutionsBatchTerminateWorkflowExecutions - Batch Terminate Workflow ExecutionsworkflowsExecutionsCancelWorkflowExecution - Cancel Workflow ExecutionworkflowsExecutionsGetWorkflowExecution - Get Workflow ExecutionworkflowsExecutionsGetWorkflowExecutionHistory - Get Workflow Execution HistoryworkflowsExecutionsGetWorkflowExecutionLogs - Get Workflow Execution LogsworkflowsExecutionsGetWorkflowExecutionTraceEvents - Get Workflow Execution Trace EventsworkflowsExecutionsGetWorkflowExecutionTraceInfo - Get Workflow Execution Trace InfoworkflowsExecutionsGetWorkflowExecutionTraceOtel - Get Workflow Execution Trace OtelworkflowsExecutionsGetWorkflowExecutionTraceSummary - Get Workflow Execution Trace SummaryworkflowsExecutionsQueryWorkflowExecution - Query Workflow ExecutionworkflowsExecutionsResetWorkflow - Reset WorkflowworkflowsExecutionsSignalWorkflowExecution - Signal Workflow ExecutionworkflowsExecutionsStream - StreamworkflowsExecutionsStreamWorkflowExecutionLogs - Stream Workflow Execution LogsworkflowsExecutionsTerminateWorkflowExecution - Terminate Workflow ExecutionworkflowsExecutionsUpdateWorkflowExecution - Update Workflow ExecutionworkflowsGetWorkflow - Get WorkflowworkflowsGetWorkflowRegistration - Get Workflow RegistrationworkflowsGetWorkflowRegistrations - Get Workflow RegistrationsworkflowsGetWorkflows - Get WorkflowsworkflowsMetricsGetWorkflowMetrics - Get Workflow MetricsworkflowsRunsGetRun - Get RunworkflowsRunsGetRunHistory - Get Run HistoryworkflowsRunsListRuns - List RunsworkflowsSchedulesGetSchedule - Get ScheduleworkflowsSchedulesGetSchedules - Get SchedulesworkflowsSchedulesPauseSchedule - Pause ScheduleworkflowsSchedulesResumeSchedule - Resume ScheduleworkflowsSchedulesScheduleWorkflow - Schedule WorkflowworkflowsSchedulesTriggerSchedule - Trigger ScheduleworkflowsSchedulesUnscheduleWorkflow - Unschedule WorkflowworkflowsSchedulesUpdateSchedule - Update ScheduleworkflowsUnarchiveWorkflow - Unarchive WorkflowworkflowsUpdateWorkflow - Update WorkflowaudioVoicesListaudioVoicesSearch instead.betaAgentsListbetaAgentsListPages instead.betaConnectorsCallToolbetaLibrariesDocumentsLibrariesDocumentsUpdateV1betaLibrariesLibrariesUpdateV1workflowsExecuteWorkflowRegistrationYou can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { Mistral } from "@mistralai/mistralai";
const sdk = new Mistral({ debugLogger: console });
You can also enable a default debug logger by setting an environment variable MISTRAL_DEBUG to true.
The SDK can emit OpenTelemetry traces for the API calls it makes (chat, agents, embeddings, OCR, …), following the
GenAI semantic conventions.
Spans capture the operation, model, token usage, and — unless redacted — the input/output messages and tool calls. Telemetry is opt-in and lives in the @mistralai/mistralai/extra/observability module.
Dedicated mode loads the OpenTelemetry SDK and OTLP exporter on demand. Install them alongside the client:
npm install @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources
Either set an environment variable before creating the client:
export MISTRAL_SDK_TELEMETRY=dedicated # dedicated | global | false
or configure it in code:
import { Mistral } from "@mistralai/mistralai";
import { configureTelemetry } from "@mistralai/mistralai/extra/observability";
const client = new Mistral({ apiKey: process.env["MISTRAL_API_KEY"] });
// Dedicated mode (default): the SDK creates and owns an OTLP exporter that ships
// spans to the Mistral telemetry endpoint. Spans are redacted before export.
await configureTelemetry(client);
const response = await client.chat.complete({
model: "mistral-small-latest",
messages: [{ role: "user", content: "Hello!" }],
});
configureTelemetry(client, provider) selects where spans go and who owns the export pipeline:
provider | Who owns the exporter | Where spans go | Redaction |
|---|---|---|---|
"dedicated" (default) | The SDK | Mistral telemetry endpoint | Applied automatically |
"global" | Your application | Your global OpenTelemetry provider | Not applied — you need to wrap your own exporter |
a TracerProvider | Your application | The provider you pass | Not applied — you need to wrap your own exporter |
In global/custom modes your application owns the pipeline, so the redaction option is ignored (a warning is logged). Wrap your own exporter with RedactingSpanExporter to redact spans there:
import { trace } from "@opentelemetry/api";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { BasicTracerProvider, BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { Mistral } from "@mistralai/mistralai";
import { configureTelemetry, RedactingSpanExporter } from "@mistralai/mistralai/extra/observability";
const provider = new BasicTracerProvider({
spanProcessors: [
new BatchSpanProcessor(new RedactingSpanExporter(new OTLPTraceExporter())),
],
});
trace.setGlobalTracerProvider(provider);
const client = new Mistral({ apiKey: process.env["MISTRAL_API_KEY"] });
// SDK spans now flow through your global provider (already redacted above).
await configureTelemetry(client, "global");
In dedicated mode, redaction is on by default. Control it with the redaction option, which also accepts any of the reusable policies from @mistralai/mistralai/extra/observability:
import { AttributeRedactionPolicy } from "@mistralai/mistralai/extra/observability";
await configureTelemetry(client); // default policy (regex)
await configureTelemetry(client, "dedicated", { redaction: new AttributeRedactionPolicy() }); // very conservative key-oriented policy
await configureTelemetry(client, "dedicated", { redaction: false }); // disabled - no redaction
await configureTelemetry(client, "dedicated", { // custom callback to control how attributes get redacted
redaction: (key, value) => (key.includes("email") ? undefined : value),
});
| Policy | Strategy | Trade-off |
|---|---|---|
RegexRedactionPolicy (default, redaction: true) | Content-oriented: keeps keys and structure, redacts matched substrings (secret tokens plus PII — emails, card-like sequences, IPv4). | Redacts most sensitive data while preserving observability value; may miss free-form PII or secrets not in the pattern set. |
AttributeRedactionPolicy | Key-oriented: redacts whole values for sensitive keys (explicit set, fragment match, or non-primitive value), then scans kept values for secret token patterns. | Very conservative, but erases most prompt/response content. |
CallbackRedactionPolicy (redaction: <callback>) | Your (key, value) => value | undefined masker per attribute; return undefined to drop the attribute. | Full control; you own the logic. |
The built-in defaults are exported as constants, so you can extend them instead of replacing them wholesale:
import {
AttributeRedactionPolicy,
DEFAULT_PII_SECRET_PATTERNS,
DEFAULT_SENSITIVE_ATTRIBUTE_KEYS,
RegexRedactionPolicy,
configureTelemetry,
} from "@mistralai/mistralai/extra/observability";
// Content-oriented: add a custom secret pattern to the default set.
await configureTelemetry(client, "dedicated", {
redaction: new RegexRedactionPolicy([...DEFAULT_PII_SECRET_PATTERNS, /\bacme-[a-z0-9]{16}\b/g]),
});
// Key-oriented: mask an extra application attribute on top of the defaults.
await configureTelemetry(client, "dedicated", {
redaction: new AttributeRedactionPolicy({
sensitiveKeys: new Set([...DEFAULT_SENSITIVE_ATTRIBUTE_KEYS, "app.customer.email"]),
}),
});
Note: the RedactingSpanExporter primitive is reusable by any OpenTelemetry application, independent of the Mistral client.
| Variable | Description | Default |
|---|---|---|
MISTRAL_SDK_TELEMETRY | Auto-enable telemetry: dedicated, global, or false. | unset (disabled) |
MISTRAL_OTLP_TRACES_ENDPOINT | Override the OTLP traces endpoint used in dedicated mode. | https://api.mistral.ai/telemetry/v1/traces |
MISTRAL_API_KEY | Used as the bearer token for the dedicated-mode exporter. | — |
Runnable examples live in examples/src/observability.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
56 followers · starred Mar 2025
171 followers · starred Dec 2024
51 followers · starred Mar 2026
89 followers · starred Jan 2026