Treat the output of your local model as a candidate JSON record. Parse it with strict rules, check every required field against the data contract, and create a new file only after those checks pass. Keep rejected replies outside the folder the rest of your app trusts.

Establish the record your program needs

Use a small example involving a fictional workshop inventory. The program needs an item code, an integer count, and an availability status. It should never set an unknown quantity to zero merely to fill a field. Zero explicitly says that no items were counted. Null means the number is missing. Write those definitions down before asking a model for JSON. A valid JSON value can still be wrong for your application.

Use three field requirements. The item code is a string in the pattern AB-123 with two letters and three digits. The count is an integer from 0 through 999 or null. The status can be counted when an integer exists or unverified when count is null. These rules are synthetic for the exercise. Adapt values and compatibility decisions to your application’s contract. The distinction between type and meaning matters in any record you may store automatically.

For this workflow, supply the whole assistant message to the validator. A reply wrapped in a Markdown code fence needs separate handling. Decide whether your application deliberately unwraps that with a documented parser or rejects it. The example rejects wrapping because it expects a complete JSON object. This gives testing a clear pass condition. A human can save the original reply for inspection in a separate location.

Produce a first candidate locally

Use a local app with an already working text model or a client whose local endpoint you already verified. Pair the allowed values and null rule with a short inventory note. Ask for a single JSON object using the requested fields. If your endpoint supports constrained structured output, you can separately send a schema to guide generation. LM Studio documents a structured-output option for its API. Still apply your own checks before storing the model’s response, including semantic combinations your app cares about. LM Studio’s structured-output documentation

Begin with synthetic examples unrelated to your actual stock. Give the model Workshop shelf contains 12 clips recorded under AB-103 and expect the code AB-103, count 12, and status counted. Then give it The shelf AB-104 has yet to be counted. Expect null and unverified. A response that gives zero in the second case can appear orderly but loses the meaning of the source. Compare the candidate record with the note during manual testing.

Check syntax, duplicate keys and the allowed record

Save the following small validator locally. It reads model output from standard input and takes a new destination file as its only argument. Stage your real app’s generated reply as UTF-8 text. Check failures with a test copy before processing an actual file.

import json
import re
import sys
from pathlib import Path


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"Repeated field: {key}")
        result[key] = value
    return result


def reject_constant(value):
    raise ValueError(f"Unsupported number: {value}")


def validated_record(raw):
    item = json.loads(
        raw, object_pairs_hook=unique_object, parse_constant=reject_constant
    )
    if type(item) is not dict or set(item) != {"code", "count", "status"}:
        raise ValueError("Expected exactly code, count and status")
    code = item["code"]
    count = item["count"]
    status = item["status"]
    if type(code) is not str or re.fullmatch(r"[A-Z]{2}-[0-9]{3}", code) is None:
        raise ValueError("Invalid item code")
    if count is None and status == "unverified":
        return item
    if type(count) is int and 0 <= count <= 999 and status == "counted":
        return item
    raise ValueError("Count and status are incompatible")


def main():
    if len(sys.argv) != 2:
        print("Usage: python3 accept_record.py NEW_FILE.json", file=sys.stderr)
        return 2
    try:
        raw = sys.stdin.read(100_001)
        if len(raw) > 100_000:
            raise ValueError("Reply exceeds the input limit")
        item = validated_record(raw)
        payload = json.dumps(item, ensure_ascii=False, allow_nan=False) + "\n"
        destination = Path(sys.argv[1])
        with destination.open("x", encoding="utf-8") as out:
            out.write(payload)
    except (OSError, ValueError, RecursionError) as error:
        print(f"Rejected or could not save: {error}", file=sys.stderr)
        return 1
    print("Saved a validated record:", destination)
    return 0


if __name__ == "__main__":
    sys.exit(main())

Choose an existing writable folder for the destination. The input cap limits how many characters the reader accepts, and the exclusive file mode avoids overwriting a file already present under that name. The parser raises an error on duplicate field names rather than allowing a later field to replace an earlier one. It also rejects non-standard numeric constants. Ordinary code often permits defaults that are convenient for trusted data. Here you need to choose how to treat those defaults explicitly. Python’s JSON decoding options

The type check uses an integer test that does not accept booleans. In Python, a true value can behave like the integer one in some expressions. A literal JSON true is still a different kind of quantity in this contract. Null has a separate allowed state. Check both the field value and its status before returning. If your downstream record changes, update the validation alongside its tests so the rules stay aligned.

Exercise good and bad cases before automating

Make a fresh output folder and run one visible good result. Feed an object with code AB-103, count 12 and status counted. Expect the program to produce one new file. Open it and verify that the count stayed a number and that all three keys are present. Run a second good result with AB-104, null and unverified under a new filename. Open that copy and see that the missing count remains null. These are fixtures for your application and do not claim that a particular model generated those exact results.

Make a list of bad cases with different failure reasons. Send the same field twice with different values. Give count as the string 12, then as true. Try a negative number, an unexpected field, or a code containing zero where the pattern permits only a letter. Test a null count combined with counted. Each case should return a failure and leave its requested new filename absent. Test a valid record against an already existing destination and confirm that its contents stay the same after the save fails.

For production use, also decide what an interrupted file write means to the reader. This simple example reserves a new path and writes a small record. An operating-system write failure can still leave an incomplete new file. Have the consumer validate its input or use a temporary file followed by an atomic publication protocol suitable for your app. Keep producer and consumer checks separate. Validation before writing protects the format and contract. Completing a write and observing the expected version on disk are additional checks.

Check source facts before trusting a validated result

A program can reject a negative or mismatched count and still accept a correct-looking invented value. Try a note that does not name an item code at all. If the model invents a valid AB-103 record, the validator has no ability to know that it came from nowhere. Put that case in your manual review and decide whether the application should require exact source references or an explicit unverified status. Structural validation gives a predictable check. Evidence from the input gives a different one.

Create a file acceptance note for a real pipeline

Document which application writes the untrusted response, where the validator reads it, and which folder is trusted by the consuming process. Use one synthetic source record to follow that route from beginning to end. The input might be called AB-103 prompt, while the accepted record receives its own reviewed and versioned filename. Check that a malformed reply remains in your review folder when it fails, and that the downstream job cannot read it simply because its name ends in JSON.

Decide how to log a failure without copying an entire prompt into a shared log. One dry run can log an ID, a category, and the destination path, while preserving the raw reply in a local review location if you need it. The script prints only the acceptance or exception category and some input error details. Review how your app reports failures before using actual source data. If the underlying error gives part of a path or message you want to keep private, return a smaller diagnostic for the consuming UI and hold the full details in the appropriate local location.

Add a check for a shape that passes a permissive parser. For example, a repeated capacity field can look valid if a later value replaces an earlier one. Read both source values and decide which is real before producing an accepted file. A duplicate-key failure is valuable because it prevents an unnoticed choice from becoming a fact. Test with different orders so you see that the validator rejects both variants.

Preserve the rule set as output formats change

When a new required field is added, give the record contract its own version. Prepare one valid and one invalid example for every changed requirement. If the accepted file now needs a location as well as the count, avoid setting the location from a guessed code unless the data source actually supplies that mapping. Rerun the earlier tests unchanged and note which should pass under the old contract and which require the new value. Keep older files readable under their approved rules when people still need them.

If a particular generation mode always emits more fields, decide whether the app contract should expand or whether the generator should output fewer. A validator with exact keys can reject a harmless-looking extra, and that can be the right behavior when a downstream process depends on a stable record. Allowing extra keys is also possible after reviewing the consumer’s behavior. Document the chosen policy and include a test where an unknown key would otherwise collide with a later schema addition.

Verify failure recovery with a new clean destination. Run a corrected sample after a rejected response and confirm that it can save once. Run the same corrected response again to the existing destination and confirm that any stored record remains intact. This prepares you to handle a retry that follows an invalid model response without confusing it with permission or filesystem errors.

Make the acceptance fixtures describe one boundary at a time

Build a fixture table in your review notes. Give each input a short ID, an expected outcome, and a reason. For example, quantity-zero holds code AB-105, count zero, and status counted. This should pass because zero is an observed amount in the contract. A fixture called quantity-null-observed pairs a null count with status counted, so it should fail. Change only one part of the accepted object at a time when diagnosing a rule. That makes it possible to tell whether you exercised the intended boundary.

Add a fixture with a quantity of 999 and another with 1000. Verify both at distinct paths. The first sits on the allowed upper edge while the second exceeds it. A candidate with a quantity of 12.0 is a different question. JSON can encode the number and Python may decode it differently from the integer representation your contract expects. Document whether the actual application accepts values represented as decimal numbers. In this example, it expects a plain integer. Preserve a test at the upper boundary even when the task usually handles small counts.

Build key-order cases as well. Reordering the three distinct JSON keys should work because object fields are identified by name. Inserting the same key twice should fail regardless of order. A useful negative response can include the same value both times, so the test does not depend on a conflict between values. The rule concerns duplicate fields themselves. If you later parse nested objects too, decide whether the same policy continues inside them. The parser utility in the example receives key pairs as each object is decoded.

Keep some real model behavior out of the strict parser. For instance, a synthetic candidate might say “Here is the JSON” followed by an otherwise correct object. This should fail under the plain JSON contract. Find the failure before trying to strip extra text. If you intentionally support fences for a chat app, document exact patterns for extracting the one allowed block and make sure a second object or trailing text causes a visible failure. The smaller your accepted grammar, the easier it is to verify which bytes your app uses. A quick test should include two JSON objects separated by a newline.

Decide what the consumer can trust when a file appears

The example protects existing destination names by opening the path exclusively. That gives a simple acceptance check. A second run aimed at the same file cannot replace it. It does not automatically prevent a consumer from seeing the new filename while the producer is still writing. If a watcher reacts to new files, use your application’s supported way of writing and committing an item when its contents are complete. A common design is to write a temporary file in the same filesystem, finish the write, and move it into the accepting location under a policy that protects earlier records. Discuss what happens if several writers target the same name. The program should handle that outcome explicitly rather than silently replacing one accepted record with another.

Test this property with a controlled consumer. Point a test watcher at a temporary directory and give it one example record to read. Verify what event it responds to. If you cannot guarantee that the watcher reads only completed files, make the watcher validate the file’s structure and handle partial data without treating it as an accepted inventory change. Use distinct IDs so you can review which attempted write produced a record. An interrupted producer, a duplicate destination and invalid JSON have different reasons. Make sure you can distinguish them in both the producer log and the consumer state.

Do not derive a disk path directly from generated values. The caller supplies the intended filename in the simple script. If your application wants output named for the item code, map the validated code into a naming rule you control and determine the correct directory separately. Keep the source or test files outside that output path. A fixture with unusual punctuation in the item code is a useful rejection test, even when filesystem naming itself is handled by the caller. The path identifies where the application should look. The JSON record identifies the source item and can be inspected without relying on its filename.

Check facts with an independent source before using the accepted record

Try a second source statement that covers a past and current count: AB-103 had 9 clips on Monday; the current confirmed count is 12. A syntactically and structurally correct record with count nine should fail factual review. Record the exact supporting phrase beside the candidate so a human can see which value belongs to the current state. If your workflow needs both values, use explicitly named fields under a revised contract rather than passing unlabeled numbers downstream. Keep the accepted output’s scope narrow enough to check.

An equivalent issue occurs with unknown input. If a note says “the AB-104 count will be reviewed Friday,” the operational conclusion is an unverified count, even though there is a date. A model can select a nearby number from another context, so review unusual candidates against the original passage. If source review cannot establish the fact, hold the record and preserve the missing fields explicitly. An output with good syntax and acceptable types can still be missing its main purpose. This is a useful distinction to state in your app’s acceptance note.

When you add source references, verify that a supplied line is present in the file and supports the decision. A guessed line number or a sentence attached to a different record should fail the external check, even if the data shape passes. For repeated use, record which input and model generated the raw reply, and which review turned it into an accepted record. Keep a small fixture set without private details so validation changes can be checked in a local development environment.

Decide how to retry without changing the contract

If a local model regularly returns valid JSON with a trailing sentence, run two small trials before building a cleanup step. First ask it to return only the object with explicit fields and no other prose. Then, if your endpoint can constrain structured output, supply a schema rather than adding a fragile text search around braces. Apply the same validator to both trial results. Keep one case that fails because it contains extra text and another that passes with a sparse unknown quantity. This reveals whether a change improved usability without obscuring exceptions.

Use a bounded retry for application failures. A first failure category can determine whether to ask the model again, route the source to a reviewer, or report a write problem. A permission error on the destination will not be fixed by generating a different quantity. A parse failure may benefit from a clearer prompt or a manual edit. A model reply with an unsupported source fact needs source review even when the parser is satisfied. Keep a retry policy that prevents the application from repeatedly preparing a different version of the same record under an existing name.

If the model omits a value in every retry, inspect whether the source supplied it at all. For example, “AB-106 is awaiting the receiving list” contains a code and no count. An accepted record can identify the code, use null, and set the status to unverified. Choosing zero just to get a valid file would change the source meaning. When another system needs a numerical total, let it treat this case as incomplete. Preserve the output that the validation path actually accepted so you can show the difference to a reviewer.

Finish with an acceptance fixture that opens the exact file produced by the validator and verifies the downstream reader’s view. The expected code and count should have the same type and value after parsing a second time. Check that the reader handles the legitimate null by displaying a review state. An application that shows every null as zero can undo the integrity you established at the output boundary. Add that consumer check whenever parsed records flow into a report people will rely on.

Keep rejected responses and source notes outside the accepted output folder if you retain them for troubleshooting. Use synthetic examples when sharing those logs. A follow-up prompt can ask the local model to produce a smaller record, but retry under the same validator. Save which input eventually passed so a reviewer can trace the result. If a common failure comes from an unclear contract, change the prompt or the contract carefully and rerun the known valid and invalid cases before adopting it.

Use the validator at the boundary where generated output enters your program, even if you also use structured output upstream. The integration passes when valid examples save as new files, invalid cases leave no accepted records, and any claims about actual inventory have independently reviewed evidence.