Mistral Large 4 · Call Mistral from your application
A server-side integration checklist, a minimal request, and streaming guidance.
On this page
Server-side integration
Use your own Mistral provider key in MISTRAL_API_KEY, never in browser code. Node.js 24+, Python 3.11+ and cURL are the supported examples. Download the matching file below before running it. These calls use your provider account; website credits are separate.
Examples
cURL
#!/usr/bin/env sh
# Server-side cURL example; set your own provider key. No automatic retry.
# Source: https://docs.mistral.ai/api/endpoint/chat; checked 2026-10-12.
set -eu
: "${MISTRAL_API_KEY:?Set MISTRAL_API_KEY on the server}"
curl --fail --silent --show-error --max-time 35 \
https://api.mistral.ai/v1/chat/completions \
-H "Authorization: Bearer $MISTRAL_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"model":"mistral-large-4","messages":[{"role":"user","content":"Explain safe retries in three sentences."}],"max_tokens":1024}'
Python
"""Python 3.11+ standard-library example; importing makes no request.
Source: https://docs.mistral.ai/api/endpoint/chat; checked 2026-10-12.
Run: python mistral-chat.py [text|json|image|stream] [public HTTPS image URL]
"""
import json, os, sys, urllib.request, urllib.error, urllib.parse
def body(mode='text', image_url=None):
content = 'Explain safe retries in three sentences.'
result = {'model': 'mistral-large-4', 'max_tokens': 1024, 'stream': mode == 'stream'}
if mode == 'image':
image = urllib.parse.urlparse(image_url or '')
if image.scheme != 'https' or not image.hostname or image.username or image.password:
raise ValueError('Use a public HTTPS image URL')
content = [{'type': 'text', 'text': 'Describe visible labels; mark unreadable text.'}, {'type': 'image_url', 'image_url': image_url}]
if mode == 'json':
content = 'Return JSON with a string summary and an array of string checks for safe retries.'
result['response_format'] = {'type': 'json_schema', 'json_schema': {'name': 'retry_summary', 'strict': True, 'schema': {'type': 'object', 'properties': {'summary': {'type': 'string'}, 'checks': {'type': 'array', 'items': {'type': 'string'}}}, 'required': ['summary', 'checks'], 'additionalProperties': False}}}
result['messages'] = [{'role': 'user', 'content': content}]
return result
def validate_summary(text):
value = json.loads(text)
if not isinstance(value, dict) or set(value) != {'summary', 'checks'} or not isinstance(value['summary'], str) or not isinstance(value['checks'], list) or not all(isinstance(item, str) for item in value['checks']):
raise ValueError('JSON did not match the requested schema')
return value
def chat(key, mode='text', image_url=None, opener=urllib.request.urlopen):
if not key:
raise ValueError('Set MISTRAL_API_KEY on the server')
request = urllib.request.Request('https://api.mistral.ai/v1/chat/completions', data=json.dumps(body(mode, image_url)).encode(), headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'})
try:
with opener(request, timeout=35) as response:
if mode != 'stream':
result = json.load(response); choices = result.get('choices') or []
if not choices or not isinstance(choices[0].get('message', {}).get('content'), str):
raise ValueError('Provider returned no text choice')
if choices[0].get('finish_reason') == 'length':
raise ValueError('Output reached its token limit')
text = choices[0]['message']['content']
return validate_summary(text) if mode == 'json' else text
text = ''; data = []; done = False; limited = False
for line in response:
line = line.decode().rstrip('\r\n')
if line.startswith('data:'):
data.append(line[5:].lstrip())
if line == '' and data:
payload = '\n'.join(data); data = []
if payload == '[DONE]':
done = True; break
event = json.loads(payload)
if event.get('error'):
raise ValueError('Provider interrupted the response')
for choice in event.get('choices', []):
limited |= choice.get('finish_reason') == 'length'
delta = choice.get('delta', {}).get('content')
if isinstance(delta, str):
text += delta
if not done:
raise ValueError('Stream interrupted; partial text is not a completed answer')
if limited or not text:
raise ValueError('Output was limited or empty')
return text
except urllib.error.HTTPError as error:
# Do not print provider bodies, prompts or credentials.
if error.code == 429:
raise RuntimeError('Provider rate limit; Retry-After: ' + (error.headers.get('Retry-After') or 'unspecified')) from None
raise RuntimeError('Provider request failed (' + str(error.code) + ')') from None
if __name__ == '__main__':
try:
mode = sys.argv[1] if len(sys.argv) > 1 else 'text'
if mode not in {'text', 'json', 'image', 'stream'}:
raise ValueError('Choose text, json, image or stream')
result = chat(os.environ.get('MISTRAL_API_KEY', ''), mode, sys.argv[2] if len(sys.argv) > 2 else None)
print(json.dumps(result, ensure_ascii=False) if isinstance(result, dict) else result)
except (ValueError, RuntimeError, TimeoutError, urllib.error.URLError, KeyboardInterrupt):
print('Request did not complete. Check settings, connectivity and rate limits; no automatic retry.', file=sys.stderr)
sys.exit(1)
TypeScript
// Server-side Node.js 24+ example. Importing this file performs no request.
// Source: https://docs.mistral.ai/api/endpoint/chat (checked 2026-10-12).
export type Mode = 'text' | 'image' | 'json' | 'stream'
export function requestBody(mode: Mode, imageUrl?: string) {
if (mode === 'image') {
const image = new URL(imageUrl || '')
if (image.protocol !== 'https:' || image.username || image.password)
throw new Error('Use a public HTTPS image URL')
}
return {
model: 'mistral-large-4',
max_tokens: 1024,
stream: mode === 'stream',
messages: [
{
role: 'user',
content:
mode === 'image'
? [
{ type: 'text', text: 'Describe the visible labels; mark unreadable text.' },
{ type: 'image_url', image_url: imageUrl },
]
: mode === 'json'
? 'Return JSON with a string summary and an array of string checks for safe retries.'
: 'Explain safe retries in three sentences.',
},
],
...(mode === 'json'
? {
response_format: {
type: 'json_schema',
json_schema: {
name: 'retry_summary',
strict: true,
schema: {
type: 'object',
properties: {
summary: { type: 'string' },
checks: { type: 'array', items: { type: 'string' } },
},
required: ['summary', 'checks'],
additionalProperties: false,
},
},
},
}
: {}),
}
}
export function validateSummary(text: string) {
const value = JSON.parse(text)
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
typeof value.summary !== 'string' ||
!Array.isArray(value.checks) ||
!value.checks.every((item: unknown) => typeof item === 'string') ||
Object.keys(value).some((key) => !['summary', 'checks'].includes(key))
)
throw new Error('JSON did not match the requested schema')
return value as { summary: string; checks: string[] }
}
export class ExampleError extends Error {
status: number
retryAfter: string | null
constructor(status: number, retryAfter: string | null) {
super(
status === 429
? 'Provider rate limit; inspect Retry-After before retrying'
: `Provider request failed (${status})`,
)
this.status = status
this.retryAfter = retryAfter
}
}
export async function chat({
key,
mode = 'text',
imageUrl,
signal,
fetcher = fetch,
onText = () => {},
}: {
key: string
mode?: Mode
imageUrl?: string
signal?: AbortSignal
fetcher?: typeof fetch
onText?: (text: string) => void
}) {
if (!key) throw new Error('Set MISTRAL_API_KEY on the server')
const timeout = AbortSignal.timeout(35_000)
const response = await fetcher('https://api.mistral.ai/v1/chat/completions', {
method: 'POST',
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
body: JSON.stringify(requestBody(mode, imageUrl)),
})
if (!response.ok) throw new ExampleError(response.status, response.headers.get('Retry-After'))
if (mode !== 'stream') {
const result = await response.json()
const choice = result.choices?.[0]
if (!choice || typeof choice.message?.content !== 'string')
throw new Error('Provider returned no text choice')
if (choice.finish_reason === 'length') throw new Error('Output reached its token limit')
return mode === 'json' ? validateSummary(choice.message.content) : choice.message.content
}
if (!response.body) throw new Error('Provider returned no stream')
const reader = response.body.getReader(),
decoder = new TextDecoder()
let buffer = '',
text = '',
done = false,
limited = false
try {
while (!done) {
const part = await reader.read()
buffer += decoder.decode(part.value, { stream: !part.done })
buffer = buffer.replace(/\r\n/g, '\n')
let end: number
while ((end = buffer.indexOf('\n\n')) >= 0) {
const lines = buffer.slice(0, end).split('\n')
buffer = buffer.slice(end + 2)
const data = lines
.filter((line) => line.startsWith('data:'))
.map((line) => line.slice(5).trimStart())
.join('\n')
if (!data) continue
if (data === '[DONE]') {
done = true
break
}
const event = JSON.parse(data)
if (event.error) throw new Error('Provider interrupted the response')
for (const choice of event.choices || []) {
if (choice.finish_reason === 'length') limited = true
if (typeof choice.delta?.content === 'string') {
text += choice.delta.content
onText(choice.delta.content)
}
}
}
if (part.done) break
}
if (!done) throw new Error('Stream interrupted; partial text is not a completed answer')
if (limited) throw new Error('Output reached its token limit')
if (!text) throw new Error('Provider returned no text')
return text
} finally {
await reader.cancel().catch(() => {})
reader.releaseLock()
}
}
Text, image, JSON and streaming
Python CLI: python mistral-chat.py text; replace text with image, json or stream. Image mode takes a public HTTPS image URL as its second argument. Import the TypeScript chat function and pass key, mode and an optional AbortSignal. Imports and downloads make no request.
Validate and recover
The helpers enforce a 35-second timeout, detect empty choices, handle HTTP errors and parse split SSE events. JSON output is checked again locally; syntax and schema validity do not establish factual accuracy. Partial streams are not completed results. Handle cancellation and 429 Retry-After before deciding whether to retry; no automatic retries are made. Keep tool authorization on your server. Local fixtures verify these paths; real provider execution was not performed.
Download the server examples
TypeScript and Python cover text, image URLs, JSON validation and streaming. Local fixtures verify errors and partial streams; real provider execution is unverified.
Node.js 24+ · Python 3.11+ · cURL. Set MISTRAL_API_KEY only on your server. Downloading does not execute a request.
TypeScript ↓Python ↓cURL ↓