Why Structured Output Breaks in Production
Getting JSON out of a language model is easy. Getting the same shape of JSON out of it on every call is the part that eats engineering time. Most teams start by writing "respond in JSON" in the system prompt, ship it, and then spend a month writing regex to repair trailing commas, renamed keys and fields the model politely invented.
DeepSeek gives you two levers: JSON mode and function calling. JSON mode guarantees the response parses. Function calling gives the model a schema to fill in, which is a much stronger constraint, and it also unlocks multi-step tool use. Below are the three patterns that hold up in production pipelines, plus the validation layer that keeps them honest.
JSON Mode vs Function Calling
| JSON mode (`response_format`) | Function calling (`tools`) | |
|---|---|---|
| Schema enforcement | None — you describe the shape in the prompt | Field names, types and enums are in the schema |
| Multi-intent routing | No | Yes — the model picks which tool to call |
| Best for | One fixed shape, cheap classification, summarisation | Multiple schemas, tool dispatch, agent loops |
| Typical failure | Key drift, partial objects, invalid values | Wrong tool, missing field, stringified numbers |
JSON mode is the cheapest option and perfectly fine when the object has five flat fields and you control both sides. It is a good first move because it costs almost nothing in prompt tokens. Start here and only reach for tools when you need the model to choose between shapes, or when a wrong key would actually break something downstream.
Here is the minimum viable JSON-mode call against the AiCredits endpoint. Any OpenAI-compatible SDK works; you only swap the base URL and the model name.
from openai import OpenAI
client = OpenAI(
api_key="YOUR_AICREDITS_KEY",
base_url="https://api.aicreditsapi.com/v1",
)
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[
{"role": "system", "content": "Return only JSON with keys: sentiment, confidence, keywords."},
{"role": "user", "content": "Ticket: the export button spins forever on Safari."},
],
response_format={"type": "json_object"},
temperature=0,
)
print(resp.choices[0].message.content)
Pattern 1: Force a Single Tool Call for Extraction
When you know exactly which object you want, do not leave the choice to the model. Pass one tool and set tool_choice to that function by name. The model can no longer reply with prose, and the argument string it produces is the object you asked for. Set temperature=0 so repeated runs converge instead of drifting between plausible readings.
Notice the details in the schema below: enum for currency, minimum on quantities, and a description that tells the model to copy values verbatim. Those descriptions are not decoration — they are prompt tokens the model reads at exactly the moment it fills that field.
import json
from openai import OpenAI
client = OpenAI(
api_key="YOUR_AICREDITS_KEY",
base_url="https://api.aicreditsapi.com/v1",
)
invoice_tool = {
"type": "function",
"function": {
"name": "extract_invoice",
"description": "Extract invoice fields from raw OCR text.",
"parameters": {
"type": "object",
"properties": {
"invoice_number": {"type": "string", "description": "Exactly as printed, including prefixes."},
"currency": {"type": "string", "enum": ["USD", "EUR", "GBP", "CNY", "JPY"]},
"total": {"type": "number", "description": "Grand total, numeric only, no symbols."},
"due_date": {"type": "string", "description": "ISO 8601 date, YYYY-MM-DD."},
"line_items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": {"type": "string"},
"quantity": {"type": "integer", "minimum": 1},
"unit_price": {"type": "number", "minimum": 0},
},
"required": ["description", "quantity", "unit_price"],
},
},
},
"required": ["invoice_number", "line_items"],
},
},
}
raw = """Invoice INV-2026-0142
Due 2026-04-30
2 x Ceramic mug @ 12.00
1 x Shipping @ 6.00
Total: 30.00 EUR"""
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[
{"role": "system", "content": "You extract invoice data. Copy values from the text; omit any field you cannot find. Never guess."},
{"role": "user", "content": raw},
],
tools=[invoice_tool],
tool_choice={"type": "function", "function": {"name": "extract_invoice"}},
temperature=0,
)
data = json.loads(resp.choices[0].message.tool_calls[0].function.arguments)
print(data)
Design the Schema, Not the Prompt
Only require what you actually need. Every
requiredfield is a chance for the model to fabricate a value rather than admit it is missing. Mark the rest optional and handleNonedownstream.Use
enumfor anything categorical. Free-text status fields are the single biggest source of downstream pain; a five-value enum costs almost nothing and makes the output trivially filterable.Keep descriptions short and mechanical. "ISO 8601 date, YYYY-MM-DD" works. A paragraph of explanation is wasted tokens on every call.
Avoid deep nesting. Two levels is comfortable; past three, models start dropping siblings. Flatten with IDs and a lookup table instead.
Separate read tools from write tools. A tool that mutates state should never be the model's first choice; force it explicitly after the lookup step.
Pattern 2: Validate, Then Repair With a Retry Loop
Schema adherence is best-effort, not a contract. Treat the parsed arguments as untrusted user input: validate against the same model you use for your own API, and when validation fails, feed the error back in a tool message. The model is usually capable of fixing its own output once it can see the specific complaint.
Two retries is plenty for schema violations. If it still fails, the input is genuinely ambiguous — send it to a human queue rather than burning more tokens.
from datetime import datetime
from typing import List
from openai import OpenAI
from pydantic import BaseModel, Field, ValidationError
client = OpenAI(
api_key="YOUR_AICREDITS_KEY",
base_url="https://api.aicreditsapi.com/v1",
)
TOOLS = [{
"type": "function",
"function": {
"name": "save_event",
"description": "Record a calendar event parsed from free text.",
"parameters": {
"type": "object",
"properties": {
"title": {"type": "string"},
"start_iso": {"type": "string", "description": "ISO 8601 date-time, e.g. 2026-03-06T12:30:00Z"},
"duration_minutes": {"type": "integer", "minimum": 5},
"attendees": {"type": "array", "items": {"type": "string"}},
},
"required": ["title", "start_iso", "duration_minutes"],
},
},
}]
class Event(BaseModel):
title: str
start_iso: datetime
duration_minutes: int = Field(ge=5)
attendees: List[str] = []
def extract_event(text: str, retries: int = 2) -> Event:
messages = [
{"role": "system", "content": "Parse the calendar request. Resolve relative dates against the 'Today is ...' date in the user message."},
{"role": "user", "content": text},
]
for attempt in range(retries + 1):
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=messages,
tools=TOOLS,
tool_choice={"type": "function", "function": {"name": "save_event"}},
temperature=0,
)
msg = resp.choices[0].message
call = msg.tool_calls[0]
try:
return Event.model_validate_json(call.function.arguments)
except ValidationError as exc:
if attempt == retries:
raise
messages.append(msg.model_dump(exclude_none=True))
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": f"Validation failed: {exc.errors()}. Call save_event again with corrected arguments.",
})
print(extract_event("Lunch with Ana ([email protected]) next Friday at 12:30, one hour. Today is 2026-03-02."))
Pattern 3: Route Between Tools With a Handler Map
For assistant-style endpoints, you want the model to pick a tool, read the result, and decide again. Leave tool_choice="auto" and run a loop. Keep the dispatch table explicit — mapping function names to Python callables — so an unexpected tool name raises instead of silently doing nothing.
Keep write actions behind a clear description threshold ("only after the order has been looked up"). Models follow ordering instructions in tool descriptions noticeably better than ordering instructions buried in the system prompt.
import json
from openai import OpenAI
client = OpenAI(
api_key="YOUR_AICREDITS_KEY",
base_url="https://api.aicreditsapi.com/v1",
)
tools = [
{"type": "function", "function": {
"name": "search_orders",
"description": "Look up a customer's orders by email address.",
"parameters": {
"type": "object",
"properties": {
"email": {"type": "string"},
"limit": {"type": "integer", "minimum": 1, "maximum": 20},
},
"required": ["email"],
},
}},
{"type": "function", "function": {
"name": "create_refund",
"description": "Issue a refund for one order. Only call this after search_orders has confirmed the order exists.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string"},
"reason": {"type": "string", "enum": ["damaged", "not_received", "wrong_item", "other"]},
},
"required": ["order_id", "reason"],
},
}},
]
def search_orders(email, limit=5):
return [{"order_id": "A-1042", "email": email, "status": "delivered", "total": 30.0}][:limit]
def create_refund(order_id, reason):
return {"refund_id": "R-7781", "order_id": order_id, "reason": reason, "status": "queued"}
HANDLERS = {"search_orders": search_orders, "create_refund": create_refund}
messages = [{"role": "user", "content": "Refund order A-1042 — the mug arrived cracked. My email is [email protected]."}]
while True:
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=messages,
tools=tools,
tool_choice="auto",
temperature=0,
)
msg = resp.choices[0].message
messages.append(msg.model_dump(exclude_none=True))
if not msg.tool_calls:
print(msg.content)
break
for call in msg.tool_calls:
handler = HANDLERS[call.function.name]
result = handler(**json.loads(call.function.arguments))
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
Streaming, Long Arrays and the Model Choice
If you stream, tool-call arguments arrive in fragments: you must concatenate delta.tool_calls[i].function.arguments per index before parsing, and the index is not guaranteed to arrive in order. It is easy to get subtly wrong and rarely worth it for extraction work — call without streaming, or stream only the natural-language answer after the tool results come back.
For very long arrays, do not hope one response holds everything. Batch the input yourself, emit one tool call per batch, and concatenate downstream. That keeps each call inside the output limit and makes partial failures recoverable.
Which model? Use deepseek-v4-flash for the overwhelming majority of extraction and classification work — it is the default and the cheapest per call. Reach for deepseek-v4-pro when the schema is deeply nested, the source text is genuinely ambiguous, or a wrong tool call is expensive to undo. A useful rule: if you are adding a third retry, switch models instead.
| Situation | Model |
|---|---|
| Bulk extraction, flat schema, high volume | deepseek-v4-flash |
| Classification into a handful of labels | deepseek-v4-flash |
| Nested objects, messy OCR or chat transcripts | deepseek-v4-pro |
| Multi-step agent where a bad tool call mutates state | deepseek-v4-pro |
Production Checklist
Pin
temperature=0for anything that writes to a database.Force
tool_choiceto a named function whenever exactly one schema is valid.Log the raw
argumentsstring before validation — that is your only evidence when a schema violation appears in production.Bound retries at two, then route to a human queue.
Count the schema's tokens: large tool definitions are re-sent on every call, so trim unused properties.
Keep a frozen set of tricky inputs and run them against your prompt on every schema change.
Reuse the same system prompt across calls so cached input applies — cached tokens cost less than fresh ones.
If a field can be computed downstream from data you already have, leave it out of the schema. Every unnecessary field is one more chance for the model to be wrong confidently.
Frequently Asked Questions
Yes. JSON mode returns parseable JSON, but it does not enforce your key names or types. Use it for simple flat objects; use function calling when the shape matters.
Schemas are guidance, not a hard contract. Reject unknown keys in your validator or set additionalProperties to false in the schema, and treat anything that slips through as a bug rather than something to tolerate.
Not in a single completion — the model emits one round of tool calls, you execute them, then you send the results back. The handler-map loop above is the standard way to do multi-step work.
Not through AiCredits. You sign up with an email address and pay by international card or PayPal, then point any OpenAI SDK at our base URL — no Chinese phone number, bank account or ID required.
Qualitatively: flash is the cheaper default, pro costs more per call, off-peak usage costs less than peak, and cached prompt tokens are cheaper than fresh ones. Current rates are listed at aicreditsapi.com/pricing.
The pattern that survives contact with production is boring and layered: a tight schema, a forced tool choice, a validator, and a bounded retry that feeds the error back. That combination turns a probabilistic text generator into something you can put behind an HTTP endpoint.
If you are already using the OpenAI SDK, moving to DeepSeek is a two-line change — swap base_url to https://api.aicreditsapi.com/v1 and set the model to deepseek-v4-flash. Top up with a card or PayPal at aicreditsapi.com, keep an eye on the pricing page for current rates, and start with deepseek-v4-flash until your evals tell you otherwise.