EN ▾

OpenAI-compatible API for uncensored LLMs

Mistral API Examples: Streaming, Tools and JSON Mode

These mistral api examples use an OpenAI-compatible endpoint that serves one uncensored open-weight model. Each snippet is complete: copy it, add your key and run it.

Updated

Three streams of data in a terminal, standing for streaming, tool calls and JSON output examples

Key points

  1. Every example uses the base URL https://api.mistraluncensored.com/v1 and the model ID uncensored.
  2. Streaming, JSON mode and tool calling use the same request format as other OpenAI-style APIs.
  3. Handle 429 responses with a retry that respects Retry-After.
  4. Cap parallel work at 8 requests on a full key.

One client for every example

Here are the mistral api examples most projects need, written against an endpoint that is not Mistral's own: it is an independent OpenAI-format API serving one open-weight model with no content refusals for lawful adult use. Because the format is the standard one, you build a single client object and reuse it everywhere. Install the package and keep the key in an environment variable.

pip install openai
export UNCENSORED_API_KEY="paste-your-key-here"
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.mistraluncensored.com/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
)
MODEL = "uncensored"

The snippets below assume this block sits at the top of the file. If you still need a key, the key page shows the one-click trial credit.

Basic chat with sampling controls

The simplest call sends a system message and a user message. Sampling settings such as temperature, top_p, stop, seed and the penalties are passed through to the model, so you can tune style without changing models.

resp = client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You write short, vivid scenes in second person."},
        {"role": "user", "content": "A courier waits in a rainy station for a package that never arrives."},
    ],
    temperature=0.9,
    top_p=0.95,
    frequency_penalty=0.3,
    stop=["THE END"],
    seed=42,
)
print(resp.choices[0].message.content)
print(resp.usage)

A fixed seed helps when you compare two prompts: it removes some of the randomness, so differences come from your wording. Treat it as a debugging aid and test repeated runs rather than assuming identical output. For creative work, raise temperature toward 1; for extraction and classification, lower it toward 0.2.

Streaming in Python and Node

Streaming returns tokens as they are produced over server-sent events, which makes chat interfaces feel faster. The last chunk carries usage, and that chunk has no choices, so guard for it.

stream = client.chat.completions.create(
    model=MODEL,
    messages=[{"role": "user", "content": "Describe a market at dawn in five sentences."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if getattr(chunk, "usage", None):
        print("\n", chunk.usage)

The same thing in Node:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.mistraluncensored.com/v1",
  apiKey: process.env.UNCENSORED_API_KEY,
});

const stream = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Describe a market at dawn in five sentences." }],
  stream: true,
});

for await (const chunk of stream) {
  const piece = chunk.choices?.[0]?.delta?.content;
  if (piece) process.stdout.write(piece);
}

One detail that bites in production: a streaming request occupies one of your concurrency slots until the stream ends. If a browser tab disconnects and your server keeps reading, you keep paying for the slot. Abort the upstream request when the client goes away.

Keeping conversation history

The API is stateless. It does not remember earlier calls, so a chat feature works by resending the history each time. Keep a list of messages, append the user turn, call the model, then append the assistant reply before the next round.

history = [{"role": "system", "content": "You are the narrator of a slow-burn mystery."}]

def turn(user_text):
    history.append({"role": "user", "content": user_text})
    r = client.chat.completions.create(model=MODEL, messages=history, max_tokens=400)
    reply = r.choices[0].message.content
    history.append({"role": "assistant", "content": reply})
    return reply

Two habits keep this cheap and reliable. First, every call pays for the whole history as input, so a conversation that grows to 20,000 tokens makes each new message cost more than the one before. When the list gets long, summarize the oldest turns into one short message and keep the last few verbatim. Second, store the history in your own database keyed by user, not in server memory, so a restart does not wipe a long story. The context window is 100,000 tokens for prompt and completion together, which is generous, but a quiet cap of your own at, say, 30,000 tokens of history keeps both cost and latency steady.

JSON mode for structured output

When you need a machine-readable reply, switch on JSON mode and describe the shape in the system prompt.

import json

resp = client.chat.completions.create(
    model=MODEL,
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Return a JSON object with keys name, genre and logline."},
        {"role": "user", "content": "Invent a short fantasy novel about a clockmaker."},
    ],
)
book = json.loads(resp.choices[0].message.content)
missing = [k for k in ("name", "genre", "logline") if k not in book]
if missing:
    raise ValueError(f"model skipped keys: {missing}")

JSON mode keeps the syntax valid, but the content is still model output. The key check above costs nothing and catches the occasional miss; on failure, retry once with the missing keys named in the prompt.

A tool call in curl

Tool calling uses the standard tools array. This minimal request asks the model to call a dice function.

curl https://api.mistraluncensored.com/v1/chat/completions   -H "Authorization: Bearer $UNCENSORED_API_KEY"   -H "Content-Type: application/json"   -d '{
    "model": "uncensored",
    "messages": [{"role": "user", "content": "Roll two six-sided dice."}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "roll_dice",
        "description": "Roll dice and return the results.",
        "parameters": {
          "type": "object",
          "properties": {
            "count": {"type": "integer"},
            "sides": {"type": "integer"}
          },
          "required": ["count", "sides"]
        }
      }
    }],
    "tool_choice": "auto"
  }'

The reply holds a tool_calls array. Run the function in your code, then send a follow-up request that contains the original messages, the assistant message with the calls and a message per result with role: "tool" and the matching tool_call_id. The docs describe the fields.

Picking the right pattern for your app

The snippets above are building blocks, and most real features use two or three of them together. A short guide to what goes where:

  • Interactive chat or story apps want streaming, a history list and a modest max_tokens. Users see text immediately and you control the length of each turn.
  • Back-office jobs, such as tagging or rewriting a thousand rows, want no streaming at all. Use plain calls with a semaphore, JSON mode for the output and a low temperature.
  • Agents and assistants that act want tool calling, a hard cap on loop turns and validation of every argument before it touches your data.
  • Character and persona products want a stable system prompt, a higher temperature, penalties to reduce repetition and a periodic summary of the story so far.

Start with the simplest version of your feature, check the real token counts in the usage object and add complexity only when you see a reason. Most first integrations fail on small things, not on the model: a key with a trailing newline, a base URL missing /v1, a streaming connection left open, or a batch that ignores the concurrency limit. When a call misbehaves, log the X-Request-Id header, check the status code first and look at your request body second.

Retries and parallel requests

The limits on a full key are 8 concurrent requests and 300 requests per minute; a trial key gets 2 and 60. Going over returns HTTP 429, with error code rate_limited for the per-minute limit and concurrency for too many at once. Short overloads also return 429, with Retry-After: 5. This helper handles all three:

import time
from openai import RateLimitError

def ask(messages, tries=5):
    for attempt in range(tries):
        try:
            return client.chat.completions.create(model=MODEL, messages=messages)
        except RateLimitError as err:
            retry_after = err.response.headers.get("Retry-After")
            if retry_after:
                wait = int(retry_after)
            else:
                wait = min(2 ** attempt, 30)
            time.sleep(wait)
    raise RuntimeError("still rate limited after retries")

For batch jobs, use a pool sized to your concurrency, never larger. A semaphore does the job in asyncio:

import asyncio
from openai import AsyncOpenAI

aclient = AsyncOpenAI(
    base_url="https://api.mistraluncensored.com/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
)
gate = asyncio.Semaphore(8)

async def one(prompt):
    async with gate:
        r = await aclient.chat.completions.create(
            model="uncensored",
            messages=[{"role": "user", "content": prompt}],
            max_tokens=300,
        )
        return r.choices[0].message.content

async def main(prompts):
    return await asyncio.gather(*(one(p) for p in prompts))

With 8 workers and 300 requests per minute, the per-minute cap is the next limit you reach, so a job of 3,000 requests needs at least ten minutes however many workers you run.

Reading balance and cost from responses

Each response carries X-Request-Id, X-Balance-USD and the rate limit headers. With the Python SDK you can read them through the raw response:

raw = client.chat.completions.with_raw_response.create(
    model=MODEL,
    messages=[{"role": "user", "content": "Say hello in French."}],
)
print(raw.headers.get("X-Balance-USD"), raw.headers.get("X-Request-Id"))
resp = raw.parse()

Cost per call follows from the usage object: input tokens at $0.15 per 1M and output tokens at $0.50 per 1M. A call with 1,200 input tokens and 800 output tokens costs $0.00018 + $0.0004 = $0.00058. The pricing page explains top-ups and bonuses, and failed or refused requests are not charged.

A word on budgeting for the examples on this page. Running every snippet once while you learn costs a fraction of a cent, so the $0.50 trial credit goes a long way. When you move to real traffic, multiply your average tokens by the two rates, add a margin of 20 to 30 percent for spikes, and top up with a round number. Any whole amount from $20 to $500 works, and credit never expires, so there is no penalty for buying more than you will use this month. If a request fails or is refused, you are not charged for it, which keeps your retry logic from inflating the bill.

For production code, put the client in one module, read the key from the environment and expose a single ask function that every feature calls. That one place then owns the model ID, the retry policy, the timeout and the logging of request IDs. When you need to change a setting, you change it once.

Questions and answers

Are these examples official Mistral code?

No. They target an independent OpenAI-compatible API that serves one open-weight model. The code uses the OpenAI SDK and a different base URL.

Which languages can I use?

Any language with an OpenAI SDK or an HTTP client. This page shows Python, Node.js and curl.

Does the API support streaming and tool calling?

Yes. Both work with the standard OpenAI request fields, and streaming returns usage at the end.

How many requests can I run in parallel?

A full key allows 8 concurrent requests and 300 per minute. A trial key allows 2 and 60.

How large can a request be?

The context window is 100,000 tokens for prompt plus completion, and the maximum request body is 8 MB.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API keyRead the docs