Mistral AI Free code examples in C#, Python, Java and JavaScript
Open-weight and hosted models from the French lab, with strong small models.
Try it without writing code: Prompt Generator — free in the browser.
WHAT THIS PAGE COVERS
Chat and function calling, plus running the same weights locally.
mistral-large-latest
mistralai
Model ids change. If a sample returns a 404 on the model, that is the first thing to check against the official docs.
There is no official Mistral SDK for .NET — Mistral ships Python and TypeScript only. Rather than take an unofficial dependency, point the OpenAI client at Mistral's endpoint: it is the same wire format, and it is a package you probably already have.
dotnet add package OpenAI
setx MISTRAL_API_KEY "..."
OpenAIClientOptions.Endpoint is how you retarget the client. From here every OpenAI C# sample in this guide applies unchanged — streaming, tool calling, ClientResultException.
using System.ClientModel;
using OpenAI;
using OpenAI.Chat;
ChatClient client = new(
model: "mistral-large-latest",
credential: new ApiKeyCredential(
Environment.GetEnvironmentVariable("MISTRAL_API_KEY")!),
options: new OpenAIClientOptions
{
Endpoint = new Uri("https://api.mistral.ai/v1"),
});
ChatCompletion completion = await client.CompleteChatAsync(
[
new SystemChatMessage("You are a concise technical assistant."),
new UserChatMessage("Explain a database index in two sentences."),
]);
Console.WriteLine(completion.Content[0].Text);
Identical to the OpenAI page — same client type, same update shape. Shown so you can confirm the endpoint swap changed nothing else.
using OpenAI.Chat;
await foreach (StreamingChatCompletionUpdate update
in client.CompleteChatStreamingAsync(
[new UserChatMessage("Write a haiku about indexes.")]))
{
foreach (ChatMessageContentPart part in update.ContentUpdate)
{
Console.Write(part.Text);
}
}
Console.WriteLine();
Mistral's endpoint speaks the OpenAI wire format, not the whole OpenAI API. These are the limits.
// 1. MODEL IDS ARE MISTRAL'S. "gpt-5.4-mini" is a 404 here.
// mistral-large-latest is an alias, so it survives releases.
// 2. OPENAI-ONLY FEATURES ARE NOT THERE. Anything on the Responses
// API, or a parameter OpenAI added last month, will be rejected or
// ignored. Chat completions is the portable subset.
// 3. ERROR BODIES ARE MISTRAL'S, but ClientResultException still
// carries the HTTP status, so branch on .Status as usual.
// 4. IF YOU NEED MISTRAL-SPECIFIC FEATURES — their structured output
// or document understanding — use the REST API directly or the
// Python SDK. This path is the portable subset, not everything.
The official SDK. Note the class is Mistral, not MistralClient — that older name is from the v0 package and is the most common import error.
pip install mistralai
export MISTRAL_API_KEY="..." # macOS / Linux
setx MISTRAL_API_KEY "..." # Windows, then open a new shell
chat.complete, not chat.completions.create — the method names differ from OpenAI even though the response shape does not.
import os
from mistralai import Mistral
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
response = client.chat.complete(
model="mistral-large-latest",
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain a database index in two sentences."},
],
)
print(response.choices[0].message.content)
print(response.usage.prompt_tokens, response.usage.completion_tokens)
chat.stream returns events wrapping the chunk in .data — one level deeper than OpenAI's. Reading event.choices directly is the usual AttributeError here.
stream = client.chat.stream(
model="mistral-large-latest",
messages=[{"role": "user", "content": "Write a haiku about indexes."}],
)
for event in stream:
delta = event.data.choices[0].delta.content # note .data
if delta:
print(delta, end="", flush=True)
print()
Mistral publishes open weights, which is the reason to pick it over a closed model: the same prompt can run on their API today and on your own hardware when the data cannot leave. Serve the weights with Ollama or vLLM and only the client changes.
import os
from openai import OpenAI
LOCAL_KEY = "unused" # required by the client, ignored by Ollama
# Ollama and vLLM both expose an OpenAI-compatible endpoint, so a
# locally served Mistral is reachable with the OpenAI client.
local = OpenAI(
base_url="http://localhost:11434/v1", # ollama serve
api_key=LOCAL_KEY,
)
response = local.chat.completions.create(
model="mistral", # ollama pull mistral
messages=[{"role": "user", "content": "Explain a database index."}],
)
print(response.choices[0].message.content)
# Keep the prompt in one place and switch only the client, so the
# hosted and local paths cannot drift apart.
There is no official Mistral SDK for Java — Mistral ships Python and TypeScript only. The OpenAI Java SDK pointed at Mistral's endpoint is the same wire format without an unofficial dependency.
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.69.2</version>
</dependency>
baseUrl retargets the client. From here every OpenAI Java sample in this guide applies unchanged.
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(System.getenv("MISTRAL_API_KEY"))
.baseUrl("https://api.mistral.ai/v1")
.build();
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("mistral-large-latest")
.addSystemMessage("You are a concise technical assistant.")
.addUserMessage("Explain a database index in two sentences.")
.build();
ChatCompletion completion = client.chat().completions().create(params);
completion.choices().get(0).message().content()
.ifPresent(System.out::println);
Identical to the OpenAI page. Close the stream — it holds an HTTP connection open.
import com.openai.core.http.StreamResponse;
import com.openai.models.chat.completions.ChatCompletionChunk;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("mistral-large-latest")
.addUserMessage("Write a haiku about indexes.")
.build();
try (StreamResponse<ChatCompletionChunk> stream =
client.chat().completions().createStreaming(params)) {
stream.stream()
.flatMap(chunk -> chunk.choices().stream())
.flatMap(choice -> choice.delta().content().stream())
.forEach(System.out::print);
}
Mistral speaks the OpenAI wire format, not the whole OpenAI API.
// 1. MODEL IDS ARE MISTRAL'S. mistral-large-latest is an alias and so
// survives releases; an OpenAI id is a 404 here.
// 2. OPENAI-ONLY FEATURES ARE ABSENT. Anything newer than chat
// completions will be rejected or quietly ignored.
// 3. ERROR BODIES ARE MISTRAL'S, but the typed exceptions still work
// because they branch on HTTP status, not on the vendor.
// 4. FOR MISTRAL-SPECIFIC FEATURES, call their REST API directly.
// This path is the portable subset, not the full surface.
The official TypeScript SDK. Server-side only.
npm install @mistralai/mistralai
export MISTRAL_API_KEY="..."
chat.complete, not chat.completions.create. The response shape matches OpenAI's, the method names do not.
import { Mistral } from "@mistralai/mistralai";
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
const response = await client.chat.complete({
model: "mistral-large-latest",
messages: [
{ role: "system", content: "You are a concise technical assistant." },
{ role: "user", content: "Explain a database index in two sentences." },
],
});
console.log(response.choices[0].message.content);
Events wrap the chunk in .data — one level deeper than OpenAI's. Reading event.choices directly returns undefined rather than throwing, so the loop looks like it works and prints nothing.
const stream = await client.chat.stream({
model: "mistral-large-latest",
messages: [{ role: "user", content: "Write a haiku about indexes." }],
});
for await (const event of stream) {
const delta = event.data.choices[0]?.delta?.content; // note .data
if (delta) process.stdout.write(delta);
}
Open weights are the reason to pick Mistral. Serve them with Ollama or vLLM and only the client changes.
import OpenAI from "openai";
const LOCAL_KEY = "unused"; // required by the client, ignored by Ollama
// Ollama and vLLM expose an OpenAI-compatible endpoint.
const local = new OpenAI({
baseURL: "http://localhost:11434/v1", // ollama serve
apiKey: LOCAL_KEY,
});
const response = await local.chat.completions.create({
model: "mistral", // ollama pull mistral
messages: [{ role: "user", content: "Explain a database index." }],
});
console.log(response.choices[0].message.content);
QUESTIONS
Which languages are the Mistral AI examples in?
C#, Python, Java and JavaScript. Every sample runs as pasted and reads its credentials from an environment variable — no key is ever written into the code.
Which package do I install for Mistral AI?
The samples use mistralai. The install step on each language tab gives the exact command.
Which Mistral AI model do these examples use?
mistral-large-latest, checked against the official documentation on 25 September 2026. Model ids change often; if a call returns a model-not-found error, check the current list in the official docs.
Where is the official Mistral AI documentation?
https://docs.mistral.ai/ — it is linked at the bottom of this page, and it is the authority whenever it disagrees with a sample here.
ALSO IN LANGUAGE MODELS
The authority
Official Mistral AI documentation
Model names, pricing and rate limits change faster than any page here can. When this page and the official docs disagree, the official docs are right.
https://docs.mistral.ai/