DEV Community

jidonglab
jidonglab

Posted on

Structured Outputs Field Order: 'answer' First Cost Me 39 of 500

My refund-routing classifier lost 39 correct answers out of 500 overnight. No prompt change. No model change. No temperature change. The diff that did it was one argument in a caching helper: sort_keys=True.

That argument alphabetized my JSON schema. answer sorts before reasoning. So the model started writing its verdict first and its explanation second. Structured outputs field order is generation order, and I had just told the model to decide before thinking.

TL;DR

  • Structured outputs field order is generation order. Constrained decoders emit JSON keys in the order your schema lists them, one token at a time, left to right.
  • If answer comes before reasoning, the reasoning can't influence the answer. The answer tokens are already sampled. Everything after is a post-hoc justification.
  • Alphabetical sorting silently puts answer first. json.dumps(sort_keys=True), some schema normalizers, and hand-written YAML all reorder keys.
  • Fix: declare reasoning (or analysis, evidence) before the decision field, and add a test that asserts the order of schema["properties"].
  • In my eval: 451/500 correct with reasoning first, 412/500 with answer first.

What actually broke?

The task: read a customer support ticket plus a short refund policy, and output one of approve, deny, or escalate. The policy has conditions that stack. Purchased within 30 days, unless it's a digital download that was opened, unless the download was defective, in which case escalate.

That's exactly the kind of decision where writing out the steps helps a model. The schema looked like this:

from pydantic import BaseModel
from typing import Literal

class RefundDecision(BaseModel):
    reasoning: str
    answer: Literal["approve", "deny", "escalate"]
Enter fullscreen mode Exit fullscreen mode

I pass RefundDecision.model_json_schema() to the API's structured output mode. For weeks it was fine. Then I added a small cache so I wasn't regenerating schemas on every request, and keyed it like this:

key = hashlib.sha256(
    json.dumps(schema, sort_keys=True).encode()
).hexdigest()
_schema_cache[key] = json.loads(json.dumps(schema, sort_keys=True))
Enter fullscreen mode Exit fullscreen mode

The hash was the point. Storing the sorted copy was laziness. sort_keys=True sorts every nested dict, including properties. My schema went out the door as {"answer": ..., "reasoning": ...}.

Same model, same 500 labeled tickets from my own backlog, same prompt:

Schema property order Correct Accuracy
reasoning, then answer 451 / 500 90.2%
answer, then reasoning 412 / 500 82.4%

That's my data and my policy, not a benchmark. Your gap will differ. But the direction is not a fluke, and the mechanism explains why.

Why does structured outputs field order change the answer?

Because an LLM generates tokens strictly left to right, and a constrained decoder forces the JSON keys to appear in the order your schema defines them. Whatever field comes first is produced with no access to anything written in later fields.

Here's what "structured outputs" does under the hood. At each step, the model produces a probability distribution over the vocabulary. The decoder holds a grammar compiled from your schema (a state machine, basically) and masks out every token that would make the output invalid JSON for that schema. The model samples from what's left.

The grammar doesn't just allow "any valid object." For most implementations it encodes one specific key sequence. OpenAI's Structured Outputs docs say outputs are produced in the same order as the keys in the schema. Open-source decoders like Outlines compile object properties into a pattern in declaration order too. So the grammar literally says: after {, the next thing must be "answer".

With answer first, the model's output starts like this:

{"answer": "approve", "reasoning": "The purchase was made 12 days ago, which is
within the 30-day window. However, the item is an opened digital download..."
Enter fullscreen mode Exit fullscreen mode

Read that again. The reasoning found the exception. Too late. "approve" was sampled three tokens into the response, conditioned only on the prompt and the characters {"answer": ".

Is the reasoning field useless when it comes after the answer?

Mostly, yes, for accuracy. It becomes a rationalization. The model is now conditioned on its own answer, and the most likely continuation of "approve" is an argument for approving.

I went through the 39 tickets that flipped from correct to wrong. In the answer-first run, a chunk of the reasoning texts actually identified the disqualifying condition and then kept going anyway, ending with something like "the refund is approved." The text and the label disagreed, or the text bent the policy to fit the label. Either way, the field I was logging for audits was explaining a decision it didn't make.

That's the sneaky part. Answer-first doesn't produce obviously broken outputs. It produces confident, well-written justifications for wrong labels. If you only skim the reasoning field, you'll trust it more than you should.

Does this happen with reasoning models too?

Less, because models with a separate thinking phase do their working before the visible JSON starts. The hidden reasoning tokens come first in the sequence, so the answer field is conditioned on them regardless of schema order.

But "less" isn't "never." If you're on a non-reasoning model, a small model, or a reasoning model with the thinking budget turned down to save latency, the visible JSON is where the thinking happens. Field order matters again. And many production classifiers run on the cheapest fast model precisely because they handle volume.

Where does key order get scrambled without you noticing?

Anywhere a dict passes through code that normalizes it. These are the ones I've hit or checked:

  1. json.dumps(schema, sort_keys=True). Common in cache keys, hashing, and "canonical" config dumps. Sorts recursively.
  2. YAML or TOML schema files with a formatter. Some formatters and linters offer key sorting. Someone turns it on in a cleanup PR.
  3. Hand-written schemas. People write fields in the order they think about them. Humans think about the answer first.
  4. Schema merging helpers. Code that builds properties by merging a base dict with overrides ({**base, **extra}) puts the base keys first. If answer lives in the base, it leads.
  5. Pydantic model inheritance. Fields from the parent class come before fields from the child. A BaseDecision(answer) parent with a RefundDecision(BaseDecision) child adding reasoning gives you answer first.

Number 5 is worth seeing:

class BaseDecision(BaseModel):
    answer: Literal["approve", "deny", "escalate"]

class RefundDecision(BaseDecision):
    reasoning: str

print(list(RefundDecision.model_json_schema()["properties"]))
# ['answer', 'reasoning']
Enter fullscreen mode Exit fullscreen mode

Looks clean. Ships the wrong order.

How do I make sure reasoning is generated before the answer?

Put the reasoning field first in the schema, and enforce it with a test so nobody can quietly undo it.

The schema:

class RefundDecision(BaseModel):
    policy_checks: list[str]   # each condition, checked in order
    reasoning: str
    answer: Literal["approve", "deny", "escalate"]
Enter fullscreen mode Exit fullscreen mode

I also split out policy_checks as a list. It nudges the model to walk each condition before summarizing. Name your reasoning fields like what they are; a field called notes placed first gets filled with fluff.

The test, which is the part I actually care about:

def test_decision_fields_come_last():
    props = list(RefundDecision.model_json_schema()["properties"])
    assert props[-1] == "answer", props

def test_sent_schema_preserves_order():
    sent = build_request_schema(RefundDecision)  # whatever your code actually sends
    assert list(sent["properties"]) == list(
        RefundDecision.model_json_schema()["properties"]
    )
Enter fullscreen mode Exit fullscreen mode

The second test is the one that would have caught me. It checks the schema after your caching, merging, and serialization layers, not just the model class.

And the cache fix: hash the sorted form, store the original.

key = hashlib.sha256(json.dumps(schema, sort_keys=True).encode()).hexdigest()
_schema_cache[key] = schema  # not the sorted copy
Enter fullscreen mode Exit fullscreen mode

Python dicts keep insertion order, and json.dumps without sort_keys preserves it. You only lose order when something explicitly sorts or rebuilds the dict.

What does putting reasoning first cost?

Output tokens and latency. The reasoning field might be 60 to 200 tokens where the answer is 2. On a classifier doing tens of thousands of calls a day, that's real money and real time-to-label.

Two things helped me keep the gain without the full bill:

  • Cap the reasoning with a length instruction, not a schema maxLength. A hard length constraint can force the decoder to close the string mid-thought. A prompt instruction like "at most 3 short sentences" keeps it bounded without amputation.
  • Stream and parse incrementally if you need the label fast. You can't get the answer before the reasoning, by definition. But you can stop paying attention to the reasoning stream and act the instant the answer value closes.

If you truly don't need the reasoning, drop the field entirely rather than placing it after the answer. A trailing reasoning field costs tokens and buys you a misleading audit log.

So does structured outputs field order really matter?

Yes. Structured outputs field order is generation order: the decoder emits JSON keys in schema order, and an autoregressive model can only condition on tokens it has already produced. Put answer before reasoning and the model commits to a label before writing any reasoning, which turns the reasoning into after-the-fact justification. In my 500-ticket refund eval that cost 39 correct labels (90.2% down to 82.4%). Put reasoning fields first, keep the decision field last, and add a test that checks the order of properties in the schema you actually send, because sort_keys=True, schema merging, and Pydantic inheritance will all happily put answer first for you.


Written by the developer behind Preterview, an interview prep platform.

Top comments (0)