Two ways to get structured data
An application usually needs the model's answer in a shape code can read: a record with a title, a category and a score, or a call to a function with typed arguments. This API, an independent OpenAI-compatible service running one open-weight model, gives you two tools for that. It is not the official API of Mistral or any other vendor, so check the feature list here rather than assuming parity with theirs.
JSON mode asks the model to reply with a single JSON object. You enable it with response_format: {"type": "json_object"}. It suits extraction, classification and any task where the output is one record.
Tool calling lets you describe functions with tools, steer the choice with tool_choice, and receive the model's arguments in tool_calls. You run the function yourself and send the result back as a role: "tool" message. It suits agents and any flow where the model decides what to do next.
Which one? If the output is the final product, use JSON mode. If the output is an instruction for your code to act on, use tools. Both work with the model ID uncensored on the same POST /v1/chat/completions method.
You can also combine them. A common agent loop uses tools to fetch data and then asks for a final answer in JSON mode so that the last message is machine-readable and your code can store it without any cleanup. Keep the two stages as separate calls, with tools in the first and the response format in the second, because that makes each step easier to log and to test on its own.
JSON mode in practice
Set the response format and, just as important, describe the shape in the prompt. The flag asks for a JSON object; your instructions decide which keys it has. Give the keys, their types and an example.
import json
from openai import OpenAI
client = OpenAI(
base_url="https://api.mistralapi.top/v1",
api_key="YOUR_API_KEY",
)
system = (
"You extract data from support emails. Reply with one JSON object with keys: "
'"sentiment" (one of "positive", "neutral", "negative"), '
'"topic" (short string), "urgent" (true or false).'
)
email = "My order arrived broken and nobody answers my messages. I need this fixed today."
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": system},
{"role": "user", "content": email},
],
response_format={"type": "json_object"},
temperature=0,
)
data = json.loads(resp.choices[0].message.content)
print(data)
Two settings help here. A temperature of 0 (or close to it) reduces variation between runs, and a fixed seed is passed through if you need repeatable output for tests. Keep max_tokens high enough for the whole object: if a reply is cut off at the limit, the JSON is incomplete and parsing fails. Leaving it unset lets the completion use the rest of the 100,000-token window.
The same request as curl:
curl https://api.mistralapi.top/v1/chat/completions -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d '{
"model": "uncensored",
"response_format": {"type": "json_object"},
"messages": [
{"role": "system", "content": "Reply with a JSON object with keys "summary" and "tags" (array of strings)."},
{"role": "user", "content": "Summarize: the meeting moved to Friday and the budget was approved."}
]
}'Validate every reply
JSON mode gives you a JSON object. It does not promise the object matches your schema, and no prompt can promise that either. Treat model output the way you treat input from a web form: parse it, check it, and handle failure. A small validator and a retry loop turn an occasional bad reply into a non-event.
import json
from openai import OpenAI
client = OpenAI(base_url="https://api.mistralapi.top/v1", api_key="YOUR_API_KEY")
ALLOWED = {"positive", "neutral", "negative"}
def valid(d):
return (
isinstance(d, dict)
and d.get("sentiment") in ALLOWED
and isinstance(d.get("topic"), str)
and isinstance(d.get("urgent"), bool)
)
def extract(email, tries=3):
messages = [
{"role": "system", "content": system},
{"role": "user", "content": email},
]
for _ in range(tries):
r = client.chat.completions.create(
model="uncensored",
messages=messages,
response_format={"type": "json_object"},
temperature=0,
)
text = r.choices[0].message.content
try:
d = json.loads(text)
if valid(d):
return d
problem = "The JSON did not match the required keys and types."
except json.JSONDecodeError:
problem = "That was not valid JSON."
messages.append({"role": "assistant", "content": text})
messages.append({"role": "user", "content": problem + " Reply again with only the corrected JSON object."})
raise ValueError("no valid JSON after retries")
Feeding the error back to the model, as above, often fixes the problem on the second attempt. Because failed or refused requests are not charged, a retry that fails at the API level costs nothing, though a completed reply that you reject is billed like any other.
Tool calling step by step
With tools, you describe a function using a JSON Schema for its parameters. The model answers either with text or with a request to call a function. Your code runs the function and sends the result back so the model can finish its answer.
import json
from openai import OpenAI
client = OpenAI(base_url="https://api.mistralapi.top/v1", api_key="YOUR_API_KEY")
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its id.",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
},
}]
messages = [{"role": "user", "content": "Where is order A-1042?"}]
first = client.chat.completions.create(
model="uncensored",
messages=messages,
tools=tools,
tool_choice="auto",
)
msg = first.choices[0].message
if msg.tool_calls:
call = msg.tool_calls[0]
args = json.loads(call.function.arguments)
result = {"order_id": args["order_id"], "status": "shipped", "eta": "2 days"} # your real lookup here
messages.append(msg.model_dump(exclude_none=True))
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)
else:
print(msg.content)
Three details trip people up. The arguments field is a string holding JSON, so parse it and handle a parse error. The tool_call_id in your tool message must match the call's id. And the assistant message that contained the tool call has to stay in the history before the tool result, which is why it is appended first.
Forcing or forbidding a call
tool_choice controls the behavior. Use "auto" to let the model decide, "none" to prevent calls, or name a specific function to force it. Forcing a single function is a good way to get typed arguments out of free text: define a function called save_contact with the fields you want and force it, then read the arguments instead of using JSON mode.
Streaming and structured output
Both features work with stream: true, with some care. Streamed JSON mode arrives as text pieces that only form valid JSON once the stream ends, so collect all pieces and parse at the end. Streamed tool calls arrive as fragments in delta.tool_calls, each carrying an index. Join the arguments text per index, then parse.
import json
from openai import OpenAI
client = OpenAI(base_url="https://api.mistralapi.top/v1", api_key="YOUR_API_KEY")
# "tools" is the list defined in the previous example
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Where is order B-77?"}],
tools=tools,
stream=True,
)
calls = {}
for chunk in stream:
if not chunk.choices:
continue
for tc in chunk.choices[0].delta.tool_calls or []:
slot = calls.setdefault(tc.index, {"id": "", "name": "", "args": ""})
if tc.id:
slot["id"] = tc.id
if tc.function and tc.function.name:
slot["name"] = tc.function.name
if tc.function and tc.function.arguments:
slot["args"] += tc.function.arguments
for slot in calls.values():
print(slot["name"], json.loads(slot["args"]))
Remember that a streamed request holds one of your concurrency slots until the stream ends. A full key allows 8 at once; a trial key allows 2. If an agent fans out many parallel tool calls, cap the pool or you will see HTTP 429 with the error code concurrency.
Prompt habits that improve results
- Show one example object in the system message. Models imitate examples closely.
- Use enums in words. "sentiment is one of positive, neutral, negative" beats an open field you must clean up later.
- Keep schemas flat. Deeply nested objects fail more often than lists of simple fields.
- Say what to do with missing data. "Use null when the email gives no order number" prevents invented values.
- Describe tools well. The
descriptionfields are the model's only guide to when a function applies. - Separate extraction from judgment. Ask for facts first and decisions in a second call if accuracy matters.
On cost: structured calls are usually short. A 400-token prompt with a 100-token JSON reply costs 0.00006 + 0.00005 = $0.00011 at $0.15 and $0.50 per 1M tokens, so 10,000 extractions come to $1.10. The pricing page has top-up amounts and bonus tiers.
Failure modes and how to fix them
Structured output goes wrong in a handful of predictable ways. Knowing them saves debugging time.
| Symptom | Likely cause | Fix |
|---|---|---|
| JSON parse error at the end of the text | Reply cut off at max_tokens | Raise the limit or leave it unset; check finish_reason for length |
| Text before or after the object | No clear instruction, or JSON mode not enabled | Set response_format and say "reply with only the JSON object" |
| Wrong key names | Schema described loosely | List exact key names and include one example object |
| Numbers returned as strings | Type not stated | Say "score is a number between 0 and 1" and validate in code |
| Tool never called | Vague function description | Rewrite the description, or force the call with tool_choice |
| Invented values | Field missing from the source text | Allow null and tell the model to use it |
Log the raw reply whenever validation fails. A week of failed replies shows you which instruction is unclear much faster than guessing. Store the X-Request-Id response header with each log line so you can quote it if you ask support about a specific call.
Testing without spending much
Keep a file of 30 to 50 sample inputs with the output you expect, and run it whenever you change a prompt. At 400 input and 100 output tokens per case, a pass of 50 cases costs 50 x $0.00011 = $0.0055, about half a cent. That makes prompt regression tests cheap enough to run on every commit. Use a fixed seed and low temperature so differences you see come from the prompt change, not from sampling noise.
Where to go next
The quickstart covers the base URL change for common SDKs, and the API key page explains sign-up and the one-click trial credit. The service is text only: there are no embeddings, image or audio endpoints, so pair it with another tool if your pipeline needs those.
