Guides

Mistral Large 4 API: Python, JavaScript & cURL

Start with a small server-side request and record its usage.

Before your first request

  1. Create an API key in your Mistral Studio workspace. Confirm model access and available billing credits.
  2. Store the key as MISTRAL_API_KEY in a server environment or secret manager. Keep it out of browser code, source control, logs and screenshots.
  3. Use https://api.mistral.ai/v1/chat/completions with model mistral-large-4. The optional base override below is only for your own trusted test endpoint.

cURL: one request

Shell
#!/bin/sh
set -eu
: "${MISTRAL_API_KEY:?Set MISTRAL_API_KEY first}"
curl --fail-with-body --silent --show-error \
  "${MISTRAL_API_BASE:-https://api.mistral.ai/v1}/chat/completions" \
  -H "Authorization: Bearer $MISTRAL_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{"model":"mistral-large-4","messages":[{"role":"user","content":"Explain mixture-of-experts in two sentences."}],"max_tokens":128}'

Download cURL example. Set the key in your terminal environment, then run sh first-request.sh. It prints the raw JSON.

Python: no extra packages

Python 3
import json, os, urllib.request

base = os.environ.get("MISTRAL_API_BASE", "https://api.mistral.ai/v1")
payload = {
    "model": "mistral-large-4",
    "messages": [{"role": "user", "content": "Explain mixture-of-experts in two sentences."}],
    "max_tokens": 128,
}
request = urllib.request.Request(
    base.rstrip("/") + "/chat/completions",
    data=json.dumps(payload).encode(),
    headers={"Authorization": "Bearer " + os.environ["MISTRAL_API_KEY"],
             "Content-Type": "application/json"},
)
with urllib.request.urlopen(request, timeout=60) as response:
    result = json.load(response)
print(result["choices"][0]["message"]["content"])
print(json.dumps(result.get("usage", {})))

Download Python example. Run python3 first-request.py; the standard library prints the answer and usage.

JavaScript: server-side fetch

Node.js 18+
// Node.js 18+; run with: node first-request.mjs
const key = process.env.MISTRAL_API_KEY;
if (!key) throw new Error("Set MISTRAL_API_KEY first");
const base = process.env.MISTRAL_API_BASE ?? "https://api.mistral.ai/v1";
const response = await fetch(base.replace(/\/$/, "") + "/chat/completions", {
  method: "POST",
  headers: { "Authorization": "Bearer " + key, "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "mistral-large-4",
    messages: [{role: "user", content: "Explain mixture-of-experts in two sentences."}],
    max_tokens: 128,
  }),
  signal: AbortSignal.timeout(60000),
});
if (!response.ok) throw new Error("HTTP " + response.status + ": " + await response.text());
const result = await response.json();
console.log(result.choices[0].message.content);
console.log(result.usage);

Download JavaScript example. Run node first-request.mjs in Node, never in a page containing your secret.

Stream a response

Shell · server-sent events
#!/bin/sh
set -eu
: "${MISTRAL_API_KEY:?Set MISTRAL_API_KEY first}"
curl --no-buffer --fail-with-body --silent --show-error \
  "${MISTRAL_API_BASE:-https://api.mistral.ai/v1}/chat/completions" \
  -H "Authorization: Bearer $MISTRAL_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{"model":"mistral-large-4","messages":[{"role":"user","content":"Explain mixture-of-experts in two sentences."}],"max_tokens":128,"stream":true}'

With stream: true, parse SSE data: lines and choices[0].delta.content; stop at [DONE]. Buffer partial lines because an event can span network chunks. Download the streaming request. Local protocol checks do not measure model speed.

Add an image

JSON template
{
  "model": "mistral-large-4",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Describe this image and quote visible labels."
        },
        {
          "type": "image_url",
          "image_url": "https://your-public-image-host.example/chart.png"
        }
      ]
    }
  ],
  "max_tokens": 512
}

Replace the example-domain URL with a public image you are allowed to share. Send this JSON to the same endpoint with authentication. The image is a content part, not an image-generation request. Check current encodings, pixel limits and token handling in Mistral Chat Completion API.

Structured output and tools

  • For JSON mode, use response_format: {"type":"json_object"} and ask explicitly for JSON. Validate the response schema and factual values.
  • For tools, supply function schemas in tools, inspect returned calls, run authorized functions in your application and send tool results back in the documented message format.
  • Your application controls execution, permissions, timeouts and errors. These feature outlines have not been live-tested against Large 4.

Mistral Chat Completion API provides the authoritative request schema.

Handle failures

ConditionCheck
400Identifier, messages, supported parameters and input size.
401Key presence and validity; rotate compromised credentials.
403Workspace permissions or preview entitlement; read the exact response.
429Limits; retry with bounded exponential backoff and jitter.
5xx / timeoutCap retries and log request IDs; avoid duplicate application actions.
Unexpected outputHandle absent choices and incomplete finish reasons; validate tool arguments, JSON and citations.

Save response usage for cost estimates.

Sources & verification

Research snapshot: . Source statements are dated; API access and prices can change.

Original model runs are marked “not run” unless a trace is provided. Read our editorial method.