LLM Structured Generation: Constraint-Following Evaluation and Engineering Practices

    When an LLM must produce several deliverables under strict constraints, the hard part is usually not writing quality but whether the output forms up to contract at all. This article breaks down why generative systems turn deliverables into drafts, the four overlapping root causes behind it, a four-dimension evaluation framework that treats compliance as a hard gate, and a three-layer engineering defense — separating reasoning from delivery, using structured output with per-slot budgets, and pairing deterministic validation with targeted repair loops. It also covers building regression evaluation sets.

    1. Failure in the wild: the deliverable becomes scratch paper

    Consider a common industry task: generate a social-media crisis-response package for a brand, consisting of four deliverables —

    1. Short post: no more than 140 characters;
    2. Long post with follow-up: 300–450 characters;
    3. Employee share message: no more than 40 characters;
    4. Pinned reply: no more than 80 characters.

    On top of that, three implicit requirements apply: the facts must match the supplied material (you cannot invent recall batch numbers on your own); the tone must strike the measured register of brand PR; and the output form must fit the conventions of a short-form social platform (line breaks allowed, hashtags allowed, content can be pinned).

    Three typical failure modes show up.

    Mode 1: The reasoning chain runs naked, and the answer region is empty. The output starts with a stretch of English self-narration — roughly “I need to carefully analyze this task; this is a social-media response about a brand’s product recall; I need to satisfy each requirement in turn…” — and then gets cut off by the length limit. None of the four deliverables materialize. Compliance scores come out very low; the persona and platform dimensions are near zero.

    Mode 2: The reasoning chain leaks anyway (in the output language). The output isn’t in English, but it still opens with “we need to answer in the required language, we need to output the four deliverables in the required structure, we must obey the hard constraints, we need to first sort out the facts, and weigh the three opinions.” This is internal planning written straight into the answer region. Format compliance barely passes (around 0.7), but persona tone, platform fit, and value orientation all land in the 0.2–0.5 range — because the four deliverables never actually take the required shape, and the restraint that brand PR demands has no way to show.

    Mode 3: It delivers — but it’s only a draft. All four sections are present, but each is prefixed with “My analysis:” or “Here is candidate option A,” the candidates argue with each other, and every length limit is blown.

    All three modes point to one conclusion: in a generative system, “how good the writing is” is a downstream problem, while “whether the deliverable forms up to contract” is an upstream problem. Once the upstream gives way, every downstream score is meaningless.

    2. Why it fails: four overlapping causes

    2.1 Reasoning and delivery share one output channel

    When the model’s intermediate reasoning and its final deliverable live in the same autoregressive sequence, they compete for the same token budget. This isn’t a matter of “stylistic preference” but a structural risk of channel reuse: any overly long stretch of self-narration linearly drives up cost and latency, and directly compresses the probability that the trailing content exists at all.

    2.2 Tail omission from budget exhaustion

    The four deliverables are generated in sequence. The short post comes first, the long post in the middle, the pinned reply last. If the leading content balloons, the final segment is the first to be sacrificed. This is why, in practice, a missing pinned reply tends to appear more often than a missing short post — the position of the omission correlates strongly with generation order; it is not randomly distributed.

    2.3 Language anchor drift

    When the input material is in one language but the system prompt is laced with templates and terminology from another, and the model chooses to do its planning in that other language, its control over the output language drops sharply — and that drags the tone dimension down with it. The restraint and empathy that a PR context calls for in the target language are hard to recover by translating back from a draft written in another one. In testing, samples that contained an off-language planning segment scored almost uniformly low on the persona and platform dimensions.

    2.4 Constraint stacking and position effects

    Four character limits, four fact-consistency requirements, three tone requirements, and a set of banned phrasings (for example, do not imply that other batches are also defective, and do not shift blame to the contract manufacturer). When constraints pile up, the model tends to satisfy them partially — grabbing the first few and dropping the later ones. Constraint-following degrades roughly monotonically with the number of constraints, not linearly.

    3. Evaluation framework: four-dimension scoring with a hard gate

    Don’t hide the problem behind a single weighted total. Instead, make compliance a gating metric, and report pass rate and quality scores separately.

    Dimension What it captures Suggested weight
    Compliance Deliverable count, field structure, min/max length, banned-phrase hits Hard gate; fail any and the score is 0
    Persona consistency Whether the brand-PR identity stays stable, and whether any “as an AI I…” self-narration appears 0.25
    Platform fit Whether it matches the expression form of a short-form social platform and the pinned/share-message scenarios 0.20
    Value orientation Whether it over-promises, shifts blame, or offers a realistic next step 0.25
    Factuality Whether batches, quantities, dates, and channels correspond strictly to the input material 0.30

    Three key design principles:

    • Compliance multiplies; it does not add. If any one of the four deliverables is non-compliant, the whole thing is unpublishable and the total drops straight to zero — this prevents “three strong items averaging out one missing item.”
    • Factuality gets the highest priority. In crisis response, inventing a recall batch is an error a whole order of magnitude more serious than getting the tone wrong.
    • Human review is double-blind. Automatic metrics decide “did it form up,” humans decide “is it appropriate.” Record inter-annotator agreement, and send disagreement samples to a third-party arbiter.

    4. Engineering it: three lines of defense

    Line 1: Physically isolate reasoning from the delivery channel

    A two-stage call is the lowest-cost way to fix this at the root.

    Stage 1 (plan, produce no copy): Allow only a structured “fact card” — confirmed facts, the resolution of the three opinions, and a list of banned phrasings. This stage is not bound by length and does not feed the final delivery.

    Stage 2 (write, produce only copy): Accept only the fact card, allow no further planning text, and output directly to contract.

    This way, even if Stage 1 goes completely off the rails, the contamination never reaches the deliverables. It also happens to solve the “planning leaked into the answer region” problem — the planning is moved to where it belongs.

    Make the language anchor in the system prompt explicit, and give a positive example:

    1. You are the PR lead for a consumer brand.
    2. All output must be in English. Do not output any other language, any analysis, or any plan.
    3. Facts may come only from the <facts> block; do not add any quantity, batch, or date information.
    4. Output JSON directly, with no explanation.

    Line 2: Structured output and per-slot budgets

    Have the model return a constrained structured format instead of free text that you then slice with regex. Two common approaches: require output that strictly conforms to a JSON Schema; or use grammar-constrained decoding so that structurally invalid outputs cannot be produced in the first place. The two can be combined.

    On top of this, apply per-slot budgets: give each deliverable its own length cap and generation budget so the long post cannot crowd out the pinned reply.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Slot:
    4. key: str
    5. label: str
    6. min_len: int = 1
    7. max_len: int = 10**9
    8. banned: tuple = ()
    9. must_have: tuple = ()
    10. # length = effective character count after stripping whitespace
    11. SLOTS = (
    12. Slot("short_post", "Short post", max_len=140),
    13. Slot("long_post", "Long post", min_len=300, max_len=450,
    14. must_have=("free replacement", "delisted")),
    15. Slot("staff_msg", "Staff message", max_len=40),
    16. Slot("pinned", "Pinned reply", max_len=80),
    17. )
    18. def effective_len(text: str) -> int:
    19. return len("".join(text.split()))
    20. def validate(payload: dict) -> list[str]:
    21. errors = []
    22. for s in SLOTS:
    23. text = (payload.get(s.key) or "").strip()
    24. if not text:
    25. errors.append(f"{s.label}: missing")
    26. continue
    27. n = effective_len(text)
    28. if not (s.min_len <= n <= s.max_len):
    29. errors.append(f"{s.label}: length {n} out of range [{s.min_len}, {s.max_len}]")
    30. for w in s.banned:
    31. if w in text:
    32. errors.append(f"{s.label}: banned phrase hit {w}")
    33. for w in s.must_have:
    34. if w not in text:
    35. errors.append(f"{s.label}: missing required element {w}")
    36. return errors

    Line 3: Deterministic validation plus a targeted repair loop

    What the validator returns should not just be “failed” but an executable repair instruction. Feed the error list back to the model so it only rewrites the flagged spots instead of starting the whole thing over.

    1. def generate_with_repair(client, prompt: str, facts: dict, max_turns: int = 3):
    2. feedback = ""
    3. for turn in range(max_turns):
    4. raw = client.complete(prompt if not feedback else
    5. f"{prompt}\n\n[Previous round failed validation. Fix only the issues below and keep everything else unchanged.]\n{feedback}")
    6. payload = client.parse_json(raw) # a parse failure is handled as one of the errors
    7. errors = validate(payload)
    8. if not errors:
    9. return payload, turn + 1
    10. feedback = "\n".join(f"- {e}" for e in errors)
    11. raise DeliveryError(f"Failed validation for {max_turns} consecutive rounds: {feedback}")

    Two more engineering points:

    • Fallback trimming for over-length content. For segments that run long, trim by “keep the tail, drop the middle” — preserve the commitment, the timeline, and the call to action; drop the decorative clauses — rather than truncating bluntly.
    • Best-of-N candidate sampling. For tone-related dimensions, sample several candidates and pick the best against the rubric. Note that this raises cost and latency, so enable it only on low-confidence samples.

    5. Building the evaluation set and regression

    Turning this class of task into a repeatable, regression-ready evaluation set is the prerequisite for avoiding the “passed once by luck, broke in production” cycle.

    • Scenario layering: product recall, quality complaints, delivery delays, data compliance, employee statements — several cases per layer, with difficulty ranging from “complete information” to “information gaps that must be explicitly left blank.”
    • Constraint perturbation: derive variants of the same scenario with different character caps, different banned-phrase lists, and whether hashtags are required — used to measure the robustness of constraint-following.
    • Repeatable parameters: fix the sampling parameters and random seed, repeat each sample 3 times, and report the median and variance. Variance is itself an important metric — crisis response cannot accept “right two out of three times.”
    • Metrics dashboard: pass rate, per-dimension mean, average repair rounds, first-pass rate, and tail-omission rate. First-pass rate usually reflects the model’s true constraint-following ability better than final pass rate.

    On the deployment side, the evaluation pipeline and online calls typically run on cloud platforms, stitched together from general-purpose capabilities: LLM services, object storage (to snapshot every input/output), logging services (to retain call and scoring details), and monitoring with alerts (notify when pass rate drops below a threshold). For example, Baidu AI Cloud’s model service combined with these general cloud products can form a closed “call — snapshot — score — alert” loop, which makes it easier to trace problem samples and compare across versions.

    6. Conclusion

    Back to that opening scene: what the model handed over wasn’t a social-media reply but its scratch paper. This isn’t that the model “can’t write PR copy” — it’s that three things — the generation channel, budget allocation, and the output contract — weren’t brought under engineering control.

    Three actionable recommendations for teams:

    1. Fix the channel before you talk about quality. Separating planning from delivery is the top-priority change for any multi-deliverable task.
    2. Make compliance a hard gate, not a term in a weighted average. A missing deliverable isn’t “a few points off” — it’s “unpublishable as a whole.”
    3. Make validation deterministic code, and leave tone judgment to humans. Length, structure, and banned phrases are judged by code — zero cost and stable; appropriateness is judged by double-blind human review and accumulated into a regression-ready rubric.

    Do these three things, and “constraint-following” stops being a mystical metric and becomes an engineering property you can measure and optimize continuously.