Why DeepSeek JSON Output Breaks (And It's Rarely the Model)
If your DeepSeek integration occasionally returns a friendly sentence, a markdown fence, or a field that changes type between calls, the model is not being disobedient. It is being creative, because nothing in the request told it not to be. A language model will produce anything that looks like an answer, and "looks like an answer" is a very wide target.
Reliability comes from narrowing that target in three places: the prompt, the request parameters, and your own validation layer. Skip any one of them and you get the classic failure pattern — ninety-nine clean parses, then one that takes down a nightly job.
Three mistakes cause most of it: describing the schema in prose instead of as a schema, forgetting to enable JSON mode, and trusting the output enough to skip validation. Fix those and JSON parsing stops being a source of 3 a.m. alerts.
The Four-Part Prompt Structure That Works
Every extraction prompt that survives contact with production has the same four parts, in the same order.
Contract line (system message). One sentence: reply with a single JSON object and nothing else. State it, don't ask for it politely.
Schema block. Real field names, real types, which fields are required, the allowed values for any enum, and an explicit rule for missing data.
Delimited input. Wrap the document in clear markers so the model never confuses your instructions with the data it is reading.
Closing reminder. Restate the output contract after the input. It is the last thing the model reads before it starts generating, so it carries outsized weight.
A prompt that describes JSON is a wish. A prompt that defines a schema is a contract.
A Minimal Working Call
Here is the smallest version that behaves well in practice. Note the lowercase word "json" in the user message — OpenAI-compatible JSON modes generally require the prompt to mention JSON before they will engage, and DeepSeek follows the same convention.
import os
import json
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
invoice_text = "Invoice #A-1042\nWidget Pro x2 ...\nTotal: 149.00 USD"
resp = client.chat.completions.create(
model="deepseek-v4-flash",
temperature=0,
response_format={"type": "json_object"},
messages=[
{
"role": "system",
"content": "You are an extraction engine. Reply with one JSON object and nothing else.",
},
{
"role": "user",
"content": (
"Return json with exactly these keys: "
"invoice_id (string), total (number), currency (ISO 4217 string), "
"line_items (array of objects with description: string, amount: number). "
"If a value is not stated, use null. Never guess.\n\n"
f"Invoice:\n{invoice_text}"
),
},
],
)
data = json.loads(resp.choices[0].message.content)
print(data["invoice_id"], data["total"])
Set temperature to 0 for extraction work. That is not clever engineering, it simply removes sampling noise from a task that has exactly one correct answer. If you need variety — alt text, summaries, names — use higher temperature on a different call and keep your structured extraction boring.
Schema-First Prompting With a Validation Loop
Prose schemas drift. Field names get reworded, someone forgets a required key, and the prompt slowly stops matching the code that consumes it. Generate the schema from a Pydantic model instead, inject it into the prompt, and validate every response against that same model.
When validation fails, do not silently fire the identical request again. Send the error back. Models are generally good at repairing their own output once you show them exactly which field broke and why.
import json
import os
from typing import List
from openai import OpenAI
from pydantic import BaseModel, ValidationError
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
class LineItem(BaseModel):
description: str
amount: float
class Invoice(BaseModel):
invoice_id: str
total: float
currency: str
line_items: List[LineItem]
SCHEMA = json.dumps(Invoice.model_json_schema())
SYSTEM = (
"You output only valid JSON matching the given JSON Schema. "
"No markdown fences, no comments, no prose."
)
def extract_invoice(text: str, attempts: int = 3) -> Invoice:
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"Schema:\n{SCHEMA}\n\nDocument:\n{text}"},
]
for _ in range(attempts):
resp = client.chat.completions.create(
model="deepseek-v4-flash",
temperature=0,
response_format={"type": "json_object"},
messages=messages,
)
raw = resp.choices[0].message.content or ""
try:
return Invoice.model_validate_json(raw)
except ValidationError as err:
messages.append({"role": "assistant", "content": raw})
messages.append(
{
"role": "user",
"content": f"Validation failed:\n{err}\nReturn corrected JSON only.",
}
)
raise RuntimeError("Model never returned valid JSON")
if __name__ == "__main__":
invoice = extract_invoice("Invoice #A-1042 ... Total: 149.00 USD")
print(invoice.model_dump())
Two details make this loop safe. The repair turn appends both the failed output and the error, so the conversation stays consistent instead of drifting. And the loop is bounded: after a few attempts the function raises. A pipeline that logs a validation error is dramatically cheaper than one that quietly writes half-parsed rows into your database.
Failure Modes and Their Fixes
Top-level arrays. Ask for
{"items": [...]}instead of a bare list. Object roots are more stable and easier to extend when you add pagination or metadata later.Markdown fences. JSON mode prevents most of these, but keep a tolerant parser for the stragglers and for non-JSON-mode calls.
Wandering enums. List every allowed value in the schema. A field called "category" with no options becomes free text within two weeks.
Silent inventions. Define null explicitly: if the document does not state a value, return null. Otherwise the model fills gaps with plausible fiction that passes every check except a human's.
Truncation. Check
finish_reasonbefore parsing. A clipped JSON object is a token-budget problem, not a prompt problem.Type drift.
"149.00"versus149is a schema problem. Declare number, then let validation reject or coerce.
def load_json(text: str) -> dict:
"""Parse a model reply, tolerating markdown fences."""
text = text.strip()
if text.startswith("```"):
text = text.split("```")[1]
if text.startswith("json"):
text = text[4:]
text = text.strip()
return json.loads(text)
def parse_reply(resp) -> dict:
choice = resp.choices[0]
if choice.finish_reason == "length":
raise RuntimeError("Truncated output - raise max_tokens or shorten the input")
return load_json(choice.message.content or "")
Choosing Between deepseek-v4-flash and deepseek-v4-pro
| Job | deepseek-v4-flash | deepseek-v4-pro |
|---|---|---|
| High-volume field extraction from clean text | The sensible default - fast and the lowest-cost route to a correct parse | Usually unnecessary |
| Messy documents, nested tables, mixed layouts | Works with a tight schema and one repair pass | Better first-pass accuracy on genuinely ambiguous input |
| Enum classification (sentiment, category, intent) | Well suited | Well suited; reserve it for the hard cases |
| Multi-step reasoning that must end in JSON | Fine for short reasoning chains | Stronger on long, branching instructions |
Start with flash and measure. If a small slice of your traffic keeps failing validation, route only that slice to pro instead of paying the higher rate on every request. Splitting by document type is almost always more effective than splitting by hope. The API surface is identical, so switching is a one-string change.
Reliability, Retries, and What They Actually Cost
Every retry is another request, and every request is billable. That is the real price of a sloppy schema: you pay twice for the same row and still end up with a null. Two habits cut this down. Keep the schema tight enough that the first pass succeeds, and reuse an identical system prompt plus schema block across calls — DeepSeek caches repeated prompt prefixes automatically, and cache hits are billed at a lower effective rate than fresh input.
Off-peak requests also cost less than peak ones on DeepSeek's API, which quietly makes overnight batch extraction the cheapest way to process a backlog. If you are running hundreds of thousands of documents, scheduling matters as much as prompt quality.
AiCredits sells DeepSeek API credits to developers outside China — card or PayPal, no Chinese phone number or bank account needed — and the same base URL and SDK setup work for both v4 models. Current rates are listed at aicreditsapi.com/pricing.
Checklist Before You Ship
response_format={"type": "json_object"}is set, and the prompt contains the word json.Temperature is 0 for extraction calls.
The schema is generated from a typed model, not hand-written into a docstring.
Every response is validated before it touches your database.
The repair loop is bounded and feeds the validation error back to the model.
finish_reasonis checked, and truncated output raises instead of parsing.Failures are logged with the raw model output so you can improve the schema.
Large batch jobs are scheduled off-peak and share one cached prompt prefix.
Frequently Asked Questions
Yes. Set response_format to {"type": "json_object"} and make sure the prompt itself mentions JSON. Check the current API docs for whether strict schema-constrained output is available in your region; the schema-in-prompt pattern above works either way.
Only if flash keeps failing on a specific document type. Both models accept the same parameters, so route the difficult slice to deepseek-v4-pro and keep the bulk on deepseek-v4-flash.
Three things together: mark fields as required in the schema, define null as the correct answer for absent data, and validate the response against a typed model so invented keys are visible. Instructions alone are weaker than instructions plus validation.
The token budget ran out. Check finish_reason for "length", raise max_tokens, or shorten the input. Parsing a truncated object is never the right recovery path.