Mistral AI Context Window Limits

The call succeeded, the JSON parsed, and the answer ignored the thing the user said four messages ago. Nothing failed — half your input just never reached the model.

12 min read
Staff Pick

📡 Monitor your APIs — know when they go down before your users do

Better Stack checks uptime every 30 seconds with instant Slack, email & SMS alerts. Free tier available.

Start Free →

Affiliate link — we may earn a commission at no extra cost to you

Context bugs are the least dramatic failures in an LLM integration and the hardest to attribute. There is no stack trace, no non-2xx status, and often no error at all — just an answer that is subtly worse than it was last month, in a system where nobody expects the output to be deterministic in the first place. By the time someone files it, the change that caused it is dozens of deploys back.

The short version

The window holds your input and the model's output together, so reserve room for the answer before you decide how much history fits. Check the finish reason on every response, because a truncated answer arrives as a 200. And do not treat the advertised window as a target — filling it costs money, adds latency, and makes answers worse.

Where the Tokens Actually Go

Most teams account for one of these and are surprised by the rest. The window is shared by everything in the list below, and the items you did not write are usually the ones that grow.

ConsumerGrows withUsually forgotten?
System promptEvery feature request, foreverNo — but its growth rate is
Conversation historySession lengthNo
Retrieved documentsCorpus size and top-kYes — the top-k tuned on short docs
Tool and function definitionsNumber of tools, schema verbosityYes — sent on every call, always
Tool resultsWhatever your API returnedYes — an unpaginated list is a bomb
The model's answermax output tokensYes — and this is the expensive one

The last row is the one that causes production incidents. Input and output share the window, so a request that fits perfectly on the way in can leave the model a few hundred tokens to answer in. It will use them, stop mid-sentence, and return a 200.

Reserve the Answer First

The correct order of operations is not the intuitive one. Do not fill the window with context and then ask how much room is left for the answer — decide the answer's budget first, subtract it, and let history compete for what remains.

// Order matters. Output budget is a requirement, not a leftover.
const WINDOW = windowForModel('mistral-large-latest');
const MAX_OUTPUT = 1_500;        // what a complete answer actually needs
const SAFETY_MARGIN = Math.ceil(WINDOW * 0.05); // estimation error, chat scaffolding

const systemTokens = estimateTokens(SYSTEM_PROMPT);
const toolTokens = estimateTokens(JSON.stringify(TOOL_DEFINITIONS));

const historyBudget = WINDOW - MAX_OUTPUT - SAFETY_MARGIN - systemTokens - toolTokens;

if (historyBudget < MIN_VIABLE_HISTORY) {
  // The fixed costs no longer leave room for a conversation. That is a
  // design problem, not a runtime one — fail loudly rather than sending
  // a request that cannot produce a good answer.
  throw new ContextBudgetExhausted({ systemTokens, toolTokens, WINDOW });
}

const messages = trimToFit(history, historyBudget);

The explicit throw matters more than the arithmetic. Without it, a system prompt that grew past the point of viability degrades silently: every request still succeeds, every answer is slightly worse, and the graph that would have shown you is one nobody built.

Four Trimming Strategies and What Each One Loses

StrategyWhat it losesUse when
Sliding window (drop oldest)The setup — constraints stated once at the startShort, self-contained exchanges
Pinned head + sliding tailThe middle, abruptly and visiblyDefault choice for most chat products
Rolling summary of the middlePrecision — a summary can quietly alter factsLong sessions where continuity is the product
Retrieval over historyRecency — relevant-but-old beats recentSessions long enough that summarising also fails

Two rules survive across all four. Never trim to a message boundary that separates a tool call from its result — most APIs reject the orphan, and the ones that do not will produce something stranger. And never summarise text the user needs reproduced verbatim: identifiers, code, exact quotes. Those get pinned or dropped, never paraphrased.

Reading a Context Failure

SymptomMost likely causeFix
Explicit context-length errorTotal input exceeds the windowTrim before sending; do not retry unchanged
Answer stops mid-sentence, status 200Output budget exhaustedRaise max output, or reserve it up front
Model ignores an early instructionHistory trimmed away the system contextPin the system prompt outside the trim window
Quality drops as sessions get longerSignal diluted by accumulated fillerTrim more aggressively, not less
Works in dev, fails for one customerTheir documents or history are much largerTest with p99 input size, not median
Cost per call rising without a traffic changePrompt or top-k grew; nobody measuredAlert on p95 input tokens per request

Rows two through four are the reason this family of bug survives so long: all three return a200 with a well-formed body. Nothing in a conventional error budget or uptime monitor will ever fire on them. The only instrument that catches them is a per-request record of input tokens, output tokens, and finish reason.

The Mistral Trap: Counting Tokens With Somebody Else’s Tokenizer

Most token-budgeting code in the wild was written against OpenAI first, which means it counts with a tiktoken encoding. That library does not know how a Mistral model segments text, and the gap is not a rounding error — it varies with the content. Code, non-English text, and heavy punctuation are exactly where the two disagree most, and exactly where prompts tend to be longest.

The failure this produces is quiet in the direction that matters. If your counter under-estimates, you build a trimmer that believes it left comfortable headroom, and it ships a request the API rejects — or worse, one the API accepts after silently dropping the part you cared about. The trimmer looks correct in every test you wrote, because your tests used English prose.

So either count with Mistral's own tokenizer, or stop pretending to count precisely and budget by characters with a deliberately pessimistic ratio. The second option is less elegant and much harder to get subtly wrong, and for a trimming heuristic that is the better trade.

Budget conservatively when you cannot count exactly:

// A tiktoken count is a guess for a Mistral model. If you are not using
// Mistral's own tokenizer, do not pretend to precision you do not have.
const PESSIMISTIC_CHARS_PER_TOKEN = 3; // deliberately low; over-reserves headroom

function estimateTokens(text) {
  return Math.ceil(text.length / PESSIMISTIC_CHARS_PER_TOKEN);
}

// Reserve room for the answer BEFORE deciding what history fits.
function budgetForHistory(windowTokens, systemPrompt, maxOutputTokens) {
  const reserved = estimateTokens(systemPrompt) + maxOutputTokens;
  const safetyMargin = Math.ceil(windowTokens * 0.05);
  return windowTokens - reserved - safetyMargin;
}

// Then trim history to fit budgetForHistory(...), oldest turns first.

When the Problem Is Not Your Budget

There is a class of incident that looks exactly like a context regression and is not one. During upstream degradation, answers get shorter and vaguer, requests time out before completing, and long prompts fail more often than short ones because they take longer to process. Every symptom points at the prompt change that shipped that morning.

The question that separates the two cases cannot be answered from your own logs, because your logs only contain your traffic. It needs something outside the application making real requests to api.mistral.ai on a fixed interval and recording latency and error rate independently — otherwise the first hour of every incident is spent bisecting a prompt that was never the problem.

Frequently Asked Questions

What happens when I exceed the Mistral AI context window?

One of two things, and they look nothing alike. If the whole request is over the limit, you get an explicit error before any generation happens — a fast, loud, honest failure that is easy to handle. The dangerous case is the request that fits on the way in but leaves too little room for the answer: generation starts, runs out of budget, and stops mid-sentence with a length finish reason. That comes back as a 200 with a plausible-looking body, so nothing in your error handling fires. Check the finish reason on every Mistral AI response, not just the status code.

How do I count tokens before sending a request to Mistral AI?

Exactly, using the tokenizer for the specific model, or approximately, using characters divided by a deliberately pessimistic ratio. What you should not do is count with a tokenizer borrowed from a different model family and treat the result as precise — the divergence is worst on code and non-English text, which is where prompts are longest. If the number drives a trimming decision, being wrong in the over-reserving direction costs you a little unused window; being wrong the other way ships a request that fails or silently truncates.

Should I summarise old conversation turns or just drop them?

Summarising preserves more of the thread but adds a call, adds latency, and adds a place for facts to be quietly altered — a summary is a lossy paraphrase generated by the same class of model that gets things wrong. Dropping is instant and honest about what it lost. The pragmatic split is to keep the system prompt and the most recent turns verbatim, summarise the middle only when the conversation is long enough that dropping it visibly breaks continuity, and never summarise anything the user typed that has to be reproduced exactly, such as an identifier or a snippet of code.

Why does a request that fits in the Mistral AI window still get a truncated answer?

Because the window holds the input and the output together. A prompt that consumes almost the entire window leaves the model a few hundred tokens to answer in, and it will use them and stop — mid-sentence, mid-object, or mid-list. This is the single most common context bug in production, and it does not look like a context bug: it looks like the model got lazy. Reserve the maximum output length up front, subtract it from the window, and only then decide how much history fits.

Does a bigger context window mean I should use it?

No, and treating the advertised number as a target is expensive in three separate ways. You pay for input tokens, so a full window costs more per call. Time-to-first-token grows with input length, so a full window is slower. And retrieval quality does not scale with volume — padding a prompt with marginally relevant material reliably makes answers worse, not better, because the relevant part is now a smaller fraction of what the model is attending to. The window is a ceiling to stay under, not a budget to spend.

Can I use tiktoken to count tokens for Mistral models?

You can, but only as a rough estimate, and you should assume the estimate is wrong in whichever direction hurts. Different model families segment text differently, and the divergence is largest on code, non-English text, and unusual punctuation — the same content that tends to make prompts long in the first place. If the count drives a trimming decision, either use Mistral's own tokenizer so the number is real, or switch to a character-based estimate with a pessimistic ratio so that being wrong means over-reserving headroom instead of shipping an oversized request.

Related Guides

A Truncated Answer and an Outage Both Return 200

Your monitoring cannot tell a context regression from Mistral AI having a bad hour, because neither one changes a status code. API Status Check probes api.mistral.ai and the rest of your stack independently and alerts on errors and latency, so the first question of every incident already has an answer.

Start Your Free Trial →

🛠 Tools We Use & Recommend

Tested across our own infrastructure monitoring 200+ APIs daily

Better StackBest for API Teams

Uptime Monitoring & Incident Management

Used by 100,000+ websites

Monitors your APIs every 30 seconds. Instant alerts via Slack, email, SMS, and phone calls when something goes down.

We use Better Stack to monitor every API on this site. It caught 23 outages last month before users reported them.

Free tier · Paid from $24/moStart Free Monitoring
1PasswordBest for Credential Security

Secrets Management & Developer Security

Trusted by 150,000+ businesses

Manage API keys, database passwords, and service tokens with CLI integration and automatic rotation.

After covering dozens of outages caused by leaked credentials, we recommend every team use a secrets manager.

SEMrushBest for SEO

SEO & Site Performance Monitoring

Used by 10M+ marketers

Track your site health, uptime, search rankings, and competitor movements from one dashboard.

We use SEMrush to track how our API status pages rank and catch site health issues early.

From $129.95/moTry SEMrush Free
View full comparison & more tools →Affiliate links — we earn a commission at no extra cost to you