> ## Documentation Index
> Fetch the complete documentation index at: https://docs.braintrust.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Mistral

> Trace Mistral SDK calls and evaluate Mistral models in Braintrust

[Mistral AI](https://docs.mistral.ai/) provides language models, embeddings, and agent APIs. Braintrust traces Mistral calls and lets you run evaluations against Mistral models.

**TypeScript**

## Tracing

You can trace Mistral calls through the native `@mistralai/mistralai` SDK (auto-instrumentation or `wrapMistral()`), or by routing through the [Braintrust gateway](https://docs.braintrust.dev/deploy/gateway.md) using an OpenAI-compatible client.

### Setup

Install the Braintrust SDK and either the native Mistral SDK, the OpenAI SDK (for the gateway path), or both, then set your API keys.

**1. Install packages**

```bash pnpm theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
pnpm add braintrust @mistralai/mistralai
pnpm add braintrust openai
```

```bash npm theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
npm install braintrust @mistralai/mistralai
npm install braintrust openai
```

**2. Set environment variables**

```bash title=".env" theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
BRAINTRUST_API_KEY=<your-braintrust-api-key>
MISTRAL_API_KEY=<your-mistral-api-key>

# For organizations on the EU data plane, use https://api-eu.braintrust.dev
# For self-hosted deployments, use your data plane URL
# BRAINTRUST_API_URL=<your-braintrust-api-url>
```

If you only use the Braintrust gateway, your application code only needs `BRAINTRUST_API_KEY`.

Native SDK tracing requires `@mistralai/mistralai` v1.0.0 or later.

### Auto-instrumentation

To trace Mistral calls without modifying your application code, run your app with Braintrust's import hook to patch the native Mistral SDK at startup.

```javascript title="trace-mistral-auto.js" theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import { initLogger } from "braintrust";
import { Mistral } from "@mistralai/mistralai";

initLogger({
  projectName: "mistral-example", // Replace with your project name
  apiKey: process.env.BRAINTRUST_API_KEY,
});

const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
const response = await client.chat.complete({
  model: "mistral-small-latest",
  messages: [{ role: "user", content: "Explain tracing in one sentence." }],
});

console.log(response.choices?.[0]?.message?.content);
```

Run with the import hook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
node --import braintrust/hook.mjs trace-mistral-auto.js
```

The auto-instrumentation example uses plain JavaScript so `node --import` can run the file directly. The Braintrust APIs work the same in TypeScript projects. Compile your TypeScript to JavaScript and run the compiled file with the import hook, or [run TypeScript directly](https://docs.braintrust.dev/instrument/trace-llm-calls.md#auto-instrumentation) with a TypeScript loader.

> [!NOTE]
>
> If you're using a bundler, see [Trace LLM calls](https://docs.braintrust.dev/instrument/trace-llm-calls.md#auto-instrumentation) for plugin and loader setup.

### Manual instrumentation

To trace Mistral calls manually, wrap the client yourself with `wrapMistral()`. Use this when you want to instrument selected clients rather than patching the SDK globally.

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import { initLogger, wrapMistral } from "braintrust";
import { Mistral } from "@mistralai/mistralai";

initLogger({
  projectName: "mistral-example", // Replace with your project name
  apiKey: process.env.BRAINTRUST_API_KEY,
});

const client = wrapMistral(
  new Mistral({ apiKey: process.env.MISTRAL_API_KEY }),
);
const response = await client.chat.complete({
  model: "mistral-small-latest",
  messages: [{ role: "user", content: "Explain tracing in one sentence." }],
});

console.log(response.choices?.[0]?.message?.content);
```

### Gateway

To route Mistral calls through the Braintrust gateway, point an OpenAI-compatible client at the gateway URL and pass your Braintrust API key. Add Mistral as an [AI provider](https://docs.braintrust.dev/admin/ai-providers.md) at the organization or project level first; the gateway uses your stored Mistral API key to call Mistral on your behalf.

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import { initLogger } from "braintrust";
import OpenAI from "openai";

initLogger({
  projectName: "mistral-example", // Replace with your project name
  apiKey: process.env.BRAINTRUST_API_KEY,
});

const client = new OpenAI({
  baseURL: "https://gateway.braintrust.dev/v1",
  apiKey: process.env.BRAINTRUST_API_KEY,
});

const response = await client.responses.create({
  model: "mistral-small-latest",
  input: "Explain tracing in one sentence.",
});

console.log(response.output_text);
```

> [!NOTE]
>
> API keys are stored as one-way cryptographic hashes, never in plaintext.

### What Braintrust traces

Braintrust patches the native `@mistralai/mistralai` SDK and creates an LLM-typed span per call:

* Chat completion spans (`mistral.chat.complete` and `mistral.chat.stream`), with messages and request parameters as input; response choices and token usage as output.
* Mistral Agents call spans (`mistral.agents.complete` and `mistral.agents.stream`), with messages and request parameters as input; response choices and token usage.
* Embedding spans (`mistral.embeddings.create`), with input text; output summarized as embedding length.
* Classification and moderation spans (`mistral.classifiers.classify`, `mistral.classifiers.classifyChat`, `mistral.classifiers.moderate`, and `mistral.classifiers.moderateChat`), with input text or messages as input; classification results as output.
* Fill-in-the-middle completion spans (`mistral.fim.complete` and `mistral.fim.stream`), with prompt as input; completion text and token usage.
* Token usage metrics (prompt, completion, total, plus cached and reasoning tokens when the provider reports them) and request metadata (model and selected request parameters).
* Parent-child nesting under any enclosing Braintrust span.
* Errors captured on every call.

### Tracing resources

* [Mistral documentation](https://docs.mistral.ai/)
* [@mistralai/mistralai on npm](https://www.npmjs.com/package/@mistralai/mistralai)
* [Use the Braintrust gateway](https://docs.braintrust.dev/deploy/gateway.md)

## Evals

Evaluate Mistral-powered tasks with Braintrust the same way you evaluate other model providers. The example below uses the Braintrust gateway, so the same pattern works whether you trace via the native SDK or the gateway.

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import { Eval } from "braintrust";
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://gateway.braintrust.dev/v1",
  apiKey: process.env.BRAINTRUST_API_KEY,
});

Eval("Mistral evaluation", {
  data: () => [
    { input: "What is 2 + 2?", expected: "4" },
    { input: "What is the capital of France?", expected: "Paris" },
  ],
  task: async (input) => {
    const response = await client.responses.create({
      model: "mistral-small-latest",
      input,
    });
    return response.output_text;
  },
  scores: [
    {
      name: "accuracy",
      scorer: ({ output, expected }) => (output === expected ? 1 : 0),
    },
  ],
});
```

### Eval resources

* [Create experiments](https://docs.braintrust.dev/evaluate/run-evaluations.md)
* [Use the Braintrust gateway](https://docs.braintrust.dev/deploy/gateway.md)

**Python**

## Tracing

You can trace Mistral calls through the native `mistralai` SDK (auto-instrumentation or `wrap_mistral()`), or by routing through the [Braintrust gateway](https://docs.braintrust.dev/deploy/gateway.md) using an OpenAI-compatible client.

### Setup

Install the Braintrust SDK and either the native Mistral SDK, the OpenAI SDK (for the gateway path), or both, then set your API keys.

**1. Install packages**

```bash theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
pip install braintrust openai "mistralai>=1.12.4"
```

**2. Set environment variables**

```bash title=".env" theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
BRAINTRUST_API_KEY=<your-braintrust-api-key>
MISTRAL_API_KEY=<your-mistral-api-key>

# For organizations on the EU data plane, use https://api-eu.braintrust.dev
# For self-hosted deployments, use your data plane URL
# BRAINTRUST_API_URL=<your-braintrust-api-url>
```

If you only use the Braintrust gateway, your application code only needs `BRAINTRUST_API_KEY`.

Native SDK tracing requires `mistralai>=1.12.4`.

### Auto-instrumentation

To trace Mistral alongside Braintrust's other supported libraries, call `braintrust.auto_instrument()` before creating your Mistral client.

```python Python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import os

import braintrust

braintrust.auto_instrument()
braintrust.init_logger(
    api_key=os.environ["BRAINTRUST_API_KEY"],
    project="mistral-example",  # Replace with your project name
)

from mistralai import Mistral

client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
response = client.chat.complete(
    model="mistral-small-latest",
    messages=[
        {"role": "user", "content": "Explain tracing in one sentence."},
    ],
)

print(response.choices[0].message.content)
```

To enable Mistral-only auto-patching without `braintrust.auto_instrument()`, call `MistralIntegration.setup()`.

```python Python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
from braintrust.integrations.mistral import MistralIntegration

MistralIntegration.setup()
```

### Manual instrumentation

To trace Mistral calls manually, wrap the client yourself with `wrap_mistral()`. Use this when you want to instrument selected clients rather than patching the SDK globally.

```python Python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import os

from braintrust import init_logger
from braintrust.integrations.mistral import wrap_mistral
from mistralai import Mistral

init_logger(
    api_key=os.environ["BRAINTRUST_API_KEY"],
    project="mistral-example",  # Replace with your project name
)

client = wrap_mistral(Mistral(api_key=os.environ["MISTRAL_API_KEY"]))
response = client.chat.complete(
    model="mistral-small-latest",
    messages=[
        {"role": "user", "content": "Explain tracing in one sentence."},
    ],
)

print(response.choices[0].message.content)
```

### Gateway

To route Mistral calls through the Braintrust gateway, point an OpenAI-compatible client at the gateway URL and pass your Braintrust API key. Add Mistral as an [AI provider](https://docs.braintrust.dev/admin/ai-providers.md) at the organization or project level first; the gateway uses your stored Mistral API key to call Mistral on your behalf.

```python Python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import os

from braintrust import init_logger
from openai import OpenAI

init_logger(
    project="mistral-example",  # Replace with your project name
    api_key=os.environ["BRAINTRUST_API_KEY"],
)

client = OpenAI(
    base_url="https://gateway.braintrust.dev/v1",
    api_key=os.environ["BRAINTRUST_API_KEY"],
)

response = client.responses.create(
    model="mistral-small-latest",
    input="Explain tracing in one sentence.",
)

print(response.output_text)
```

> [!NOTE]
>
> API keys are stored as one-way cryptographic hashes, never in plaintext.

### What Braintrust traces

Braintrust patches the native `mistralai` SDK and creates an LLM-typed span per call. All call types support sync and async variants:

* Chat completion spans (`mistral.chat.complete` and `mistral.chat.stream`), with messages as input, request parameters as metadata (including `service_tier`, `top_k`, `repetition_penalty`, `min_tokens`, `logprobs`, `top_logprobs`, `prompt_logprobs`, and `top_prompt_logprobs`), and response choices as output. Choices include `logprobs` and `prompt_logprobs` when Mistral returns them, aggregated across chunks for streaming calls.
* Mistral Agents call spans (`mistral.agents.complete` and `mistral.agents.stream`), with messages as input, request parameters as metadata, and response choices as output, including `logprobs` and `prompt_logprobs` when Mistral returns them.
* Tool call spans (`tool: <function_name>`) for each tool call returned by `mistral.chat.complete`, `mistral.chat.stream`, `mistral.agents.complete`, and `mistral.agents.stream`, with the tool arguments as input and `tool_call_id`, `tool_type`, `tool_index`, and `choice_index` as metadata.
* Beta conversations API spans (`mistral.beta.conversations.start`, `.append`, and `.restart`, plus matching `_stream` suffix variants like `start_stream`), with conversation inputs; outputs and `conversation_id` returned. Tool executions within the conversation produce child `tool: <name>` spans.
* Embedding spans (`mistral.embeddings.create`), with input text; output summarized as embeddings count and the first embedding's vector length.
* Fill-in-the-middle completion spans (`mistral.fim.complete` and `mistral.fim.stream`), with prompt and suffix as input; completion text and token usage.
* Audio transcription spans (`mistral.audio.transcriptions.complete` and `.stream`), with the input audio captured as an attachment and the transcribed text as output.
* Audio speech spans (`mistral.audio.speech.complete`), with text input; generated audio captured as an attachment.
* OCR spans (`mistral.ocr.process`), with the document input captured as an attachment and extracted text and structure as output.
* Token usage metrics (prompt, completion, total, plus cached and reasoning tokens when the provider reports them) and request metadata (model and selected request parameters).
* The service tier reported in the response usage, as `usage_service_tier` metadata.
* Time-to-first-token timing for streaming calls.
* Parent-child nesting under any enclosing Braintrust span.
* Errors captured on every call.

### Tracing resources

* [Mistral documentation](https://docs.mistral.ai/)
* [mistralai on PyPI](https://pypi.org/project/mistralai/)
* [Use the Braintrust gateway](https://docs.braintrust.dev/deploy/gateway.md)

## Evals

Evaluate Mistral-powered tasks with Braintrust the same way you evaluate other model providers. The example below uses the Braintrust gateway, so the same pattern works whether you trace via the native SDK or the gateway.

```python Python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import os

from braintrust import Eval
from openai import OpenAI

client = OpenAI(
    base_url="https://gateway.braintrust.dev/v1",
    api_key=os.environ["BRAINTRUST_API_KEY"],
)

def task(input):
    response = client.responses.create(
        model="mistral-small-latest",
        input=input,
    )
    return response.output_text

def accuracy_scorer(output, expected, **_kwargs):
    return 1 if output == expected else 0

Eval(
    "Mistral evaluation",
    data=[
        {"input": "What is 2 + 2?", "expected": "4"},
        {"input": "What is the capital of France?", "expected": "Paris"},
    ],
    task=task,
    scores=[accuracy_scorer],
)
```

### Eval resources

* [Create experiments](https://docs.braintrust.dev/evaluate/run-evaluations.md)
* [Use the Braintrust gateway](https://docs.braintrust.dev/deploy/gateway.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.