Engineering LLMs for Production: Handling Complex Instructions and Multimodal Understanding

    This article explains how to move large language models from generating plausible answers to delivering reliable, production-ready outputs. It covers three recurring engineering challenges—missed multi-condition instructions, detail errors in image and document understanding, and context pressure in long-chain code tasks—and presents practical methods for each: turning natural-language requirements into verifiable contracts with structured schemas, numbered constraints, and programmatic validation with retries; decomposing visual inputs into checkable intermediate artifacts; and applying layered context, minimal changes, and automated verification. It also describes building an internal evaluation loop with automatic metrics and regression testing, noting that vendor benchmarks are only directional references.

    1. The Starting Point: From “Can Answer” to “Can Deliver”

    Over the past two years, the criteria teams use to evaluate large language models have shifted. Early on, we only cared whether a model could produce an answer that looked reasonable. In real projects, the standard has become whether the output can go directly into a downstream workflow—whether it can be parsed by a program, pass business-rule validation, and produce similar results repeatedly without human intervention. The direct consequence of this shift is that a model’s weaknesses no longer show up as “it can’t answer,” but as “it can’t answer consistently enough.”

    Three types of problems recur in engineering practice and are worth abstracting into general technical topics:

    1. Missing multi-condition instructions. When a single request contains format constraints, filtering conditions, sorting rules, and output-structure requirements at the same time, the model tends to satisfy only some of them. The more constraints there are, the higher the probability of omission, and the omission often happens on the least conspicuous condition.
    2. Detail-level misunderstanding of images and documents. Users upload error screenshots, photos of tables, product images, or scanned documents and expect the model to read specific fields and values from them, but the model may reach a conclusion that is directionally correct yet wrong in detail.
    3. Context pressure in long-chain engineering tasks. Asking a model to locate a defect in a code base with months of history, modify it across multiple files, and keep existing behavior unchanged is an entirely different order of problem from asking it to write an isolated function.

    2. Complex Instruction Following: Turning “Natural-Language Requirements” into a “Verifiable Contract”

    The core idea for improving instruction-following stability is not to repeatedly tell the model to “be careful,” but to translate vague requirements into contracts that a machine can decide.

    Layer 1: Structured constraints. Describe the output format with an explicit schema so that the format itself becomes part of the constraint. An illustrative schema fragment:

    1. {
    2. "type": "object",
    3. "required": ["title", "rows", "total"],
    4. "properties": {
    5. "title": { "type": "string" },
    6. "rows": {
    7. "type": "array",
    8. "items": {
    9. "type": "object",
    10. "required": ["id", "name", "score"],
    11. "properties": {
    12. "id": { "type": "integer" },
    13. "name": { "type": "string" },
    14. "score": { "type": "number" }
    15. }
    16. }
    17. },
    18. "total": { "type": "integer" }
    19. }
    20. }

    Layer 2: Explicitly numbered constraints. Break compound requirements such as “keep the original format, filter by condition, and convert the result into a table” into a numbered list, and ask the model at the end of the prompt to self-check item by item. In practice, numbering significantly reduces the omission rate because the model’s self-check has a clear anchor.

    Layer 3: Programmatic validation and fallback. Output must be validated before it enters the business flow; if validation fails, retry with the error information attached, forming a closed loop:

    1. def generate_with_contract(prompt, schema, model, max_retry=3):
    2. for attempt in range(max_retry):
    3. raw = model(prompt)
    4. try:
    5. data = json.loads(raw)
    6. validate(data, schema) # validate both structure and business rules
    7. return data
    8. except (JSONDecodeError, ValidationError) as e:
    9. prompt = base_prompt + f"\nLast output was invalid: {e}\nFix only the problems and output the complete JSON again."
    10. raise ContractError("Output contract still not satisfied after multiple retries")

    It is important to emphasize that retries are not a cure-all. If constraints conflict with each other (for example, requiring “preserve the original layout” while also requiring “compress to under 200 words”), no amount of retrying will converge. In that case, the conflict should be clarified during the requirements stage rather than handed to the model to resolve.

    3. Image and Document Understanding: Decomposing Visual Input into Checkable Intermediate Artifacts

    The root of detail-level misunderstanding is that the model tends to output an overall impression rather than field-by-field facts. The engineering response is to break a one-shot judgment into multiple verification steps.

    • Segment regions first, then read item by item. For tables and screenshots, first identify the structure (headers, rows, columns, merged cells), then read values cell by cell, and finally aggregate. Stepwise processing makes it easier to detect misaligned values than holistic recognition.
    • Require localization evidence. Have the model attach the source text fragment or coordinate region it relied on when giving a conclusion, so that both humans and programs can verify it. A conclusion without evidence should be treated as low confidence.
    • Validate numbers and units separately. Fields involving amounts, ratios, and timestamps should be rechecked by deterministic rules or calculation logic; do not make the model responsible for precise arithmetic.
    • Assess clarity up front. When image resolution is insufficient or the image is skewed or has glare, run preprocessing first (correction, enhancement, upscaling) or ask the user to re-upload, avoiding repeated calls on unusable input.

    4. Long-Chain Engineering Tasks: Layered Context and Controlled Changes

    When working in an existing code base, the key capabilities are context organization and change control, which can be abstracted into a general method:

    1. Supply context in layers. Provide it in the order of “global structure overview → module responsibilities → target files → relevant call sites,” avoiding dumping everything at once, which dilutes key information.
    2. Locate before modifying. Require an impact analysis and modification plan first, and execute changes only after confirmation, reducing ineffective spread.
    3. Minimize changes. State explicitly that “only necessary lines may be changed,” and require a list of interfaces that were not modified but are affected, so regression testing can be focused.
    4. Automate verification. Changes must come with runnable verification (unit tests, static checks, log and monitoring/alert observation), turning “looks correct” into “verified correct.”

    It is worth noting that the model updated at a chat entry point is not necessarily in sync with the model used by the engineering-side toolchain. Teams should choose models and parameters separately for specific tasks rather than assuming that an upgrade at one entry point automatically gives every workflow the same capabilities.

    5. The Evaluation Loop: Official Metrics Are Only a Directional Reference

    Vendor-published benchmark scores reflect relative changes on a specific test set and often differ from the real distribution of your own business. A more reliable approach is to build an internal evaluation set:

    • Sample real requests, covering both high-frequency and long-tail scenarios; the set does not need to be large but must be representative;
    • Define automatically decidable metrics, such as format compliance rate, field accuracy, number of conditions satisfied, and first-pass task rate;
    • Run fixed-version regression, executing the full set on every model or prompt change to see whether it improves or regresses;
    • Keep manual spot checks to catch experience issues that automatic metrics do not cover.

    In terms of deployment, the loop above can typically be implemented with a few general cloud capabilities: object storage to hold evaluation samples and archived outputs, a message queue to smooth peaks and chain asynchronous validation, a container platform to host inference and validation services, and logging plus monitoring and alerting to track failure rates and latency. Baidu AI Cloud offers corresponding capabilities in these general categories and can serve as a reference option for teams building evaluation and inference pipelines.

    6. Conclusion

    The threshold for putting large language models into production has moved from “generation capability” to “constraint capability” and “verification capability.” Turning instructions into contracts, breaking visual judgment into checkable steps, bringing code changes under minimal-change and automated verification, and consolidating effectiveness evaluation into an internal loop—these four things determine whether model capability can be reliably converted into business value. Metric improvements are worth watching, but what is truly reusable is the engineering system built around the model.