Zero Labs
Industry News / AI

How I Used a JSON Schema to Fix Hallucinations in a Fine-Tuned 7B Code Generator

Source · Towards AI By florinelchis

From the publisher’s feed, collected in the ZeroLabs newsroom.

A case study in structured input for domain-specific code generation on consumer hardwareI spent several months fine-tuning a 7B code model to generate Laravel PHP files on an Apple M2 Pro with 16GB RAM. The model produced syntactically correct code but kept inventing things that weren’t in my specification — relationships that didn’t exist, methods that aren’t part of the framework, patterns from older API versions.After eight rounds of training with 308 examples, I still had five bugs that no amount of additional training data could fix. They were all the same kind of error: the model was filling in gaps in my natural language prompts with its own assumptions from pretraining.I tried a different approach: instead of describing what I wanted in English, I described it in a structured JSON format. The model received the same information, but in a form that left nothing ambiguous. The hallucination-type errors disappeared.This article documents the approach, the results, and the limitations — including what didn’t work and where the comparison is imperfect.Background: The Problem with Natural Language Prompts for CodeWhen you prompt a language model with “create a Post model with an author relationship,” the model must make several decisions that aren’t specified:Is author a BelongsTo, HasOne, or MorphTo?What’s the foreign key? author_id? user_id?Should the model include HasFactory? SoftDeletes?What fields should be fillable?A larger model (70B+, or GPT-4 class) can often infer reasonable answers from context. A 7B model running locally on a laptop has less room for nuance. It falls back on statistical priors from pretraining: models usually have a user() relationship, validation sometimes uses patterns from older framework versions, etc.These aren’t random errors. They’re the model applying its best guess about your domain when your prompt doesn’t fully specify it. The research community calls this kind of error a “hallucination,” though the mechanism is closer to gap-filling from prior distribution than to fabrication.The question I wanted to answer was: if I remove the ambiguity from the input, does the hallucination problem go away?The Approach: Structured JSON SpecsI designed a JSON format called BuildSpec where each object describes a single Laravel artifact — one model, one controller, one form request, etc. Here’s a concrete example:{ "artifact": "model", "class": "Book", "namespace": "App\\Models", "table": "books", "has_factory": true, "soft_deletes": true, "fillable": ["title", "isbn", "year", "author_id"], "casts": {"year": "integer"}, "relationships": [ { "type": "BelongsTo", "model": "Author", "method": "author", "foreign_key": "author_id" } ], "scopes": [ {"name": "status", "column": "status", "value": null} ]}Notice what’s different from a natural language prompt:The relationship type, method name, and foreign key are all explicithas_factory and soft_deletes are boolean flags, not things the model decidesfillable lists exact field names — the model can't add extrasThere’s no room to “guess” that the model should have a user() relationshipI also built a small compiler (530 lines of Python) that validates each spec before the model sees it. For example, it rejects "required_on_post" inside a rules array (not valid Laravel) and suggests using a structured conditional_rules dict instead. This catches specification errors in under 1ms, before the 30-second generation step runs.The idea of using structured input for better LLM output isn’t new. OpenAI’s function calling [1], structured outputs [2], and libraries like Instructor [3] and DSPy [4] all use structured formats to constrain model behavior. My contribution is applying this specifically to domain-specific code generation with a fine-tuned small model on consumer hardware, where the gap between model capability and task complexity is largest.Experimental SetupModel: Qwen2.5-Coder-7B-Instruct [5], 4-bit quantized for Apple Silicon via MLX [6].Hardware: Apple M2 Pro, 16GB unified memory. All training and inference ran locally.Fine-tuning: LoRA [7] with rank 8, using mlx-lm. Two separate training runs:ConfigurationTraining examplesIterationsInput formatPipeline A (baseline)308300+ across 9 roundsNatural language promptsPipeline B (structured)54225 across 5 roundsBuildSpec JSONBenchmark: Three Laravel applications of increasing complexity:Subscriber API — single model CRUD (5 files)Book Library — one-to-many relationship, unique validation (9 files)Event Management — many-to-many with pivot, conditional validation (12 files)Total: 26 PHP files. Evaluated by: — php -l syntax check on all files - Automated pattern-matching bug detector (checks for common errors like missing imports, wrong patterns) - Pest feature tests (written independently of the generated code) - Manual inspection of all remaining bugsImportant caveat: I designed both the specs and the benchmark. This is a self-evaluation on a small dataset. The results should be interpreted as a case study, not a controlled experiment. The benchmark applications share structural patterns with the training data. A proper evaluation would use an independent benchmark designed by someone else, with multiple evaluators classifying the bugs.ResultsQuantitativeMetricNL Prompts (A)BuildSpec (B)PHP syntax valid26/2626/26Bug-free files (automated check)26/2626/26Pest tests pass52/58 (90%)20/20 (100%)Manual fixes to pass all tests53The Pest test suites are different sizes: Pipeline A was tested against 58 tests covering broader scenarios, Pipeline B against 20 focused CRUD tests. This makes the pass rates not directly comparable. The manual fix count is a fairer comparison, though still limited by the small sample.Bug ClassificationWhat’s more interesting than the count is the classification:Pipeline A — all 5 bugs were incorrect domain assumptions:Controller used closure-based eager loading instead of array formatController called ->load(['tags']) on a model with no tags relationshipController generated ->withHttpStatus() — not a real Laravel methodModel dropped a BelongsTo relationship despite it being in the promptResource missing JsonResource importEach of these required me to: run the application, hit the failing endpoint, read the stack trace, trace the issue through the generated code, understand what the model was trying to do, and write the fix. Average time per fix: roughly 15–30 minutes.Pipeline B — all 3 bugs were mechanical issues:One model entered a repetition loop (scope method name repeated infinitely) — regenerated with lower token limitOne model omitted SoftDeletes trait despite the spec saying soft_deletes: true— added one lineOne resource omitted the JsonResource base import — added one lineEach of these was visible immediately from reading the file. Average time per fix: under 2 minutes.The pattern: Pipeline A bugs required understanding the model’s intent and why it diverged from mine. Pipeline B bugs were visible typos/omissions with obvious fixes. The total count is similar (5 vs 3), but the debugging effort per bug is asymmetric.Why This HappenedMy interpretation — and I want to be clear this is interpretation, not proven mechanism — is that the structured format removes ambiguity that the model would otherwise fill with pretraining priors.When the spec says "relationships": [{"type": "BelongsTo", "model": "Author"}], the model generates exactly one relationship. It can't add a user() relationship because the spec doesn't include one. The ambiguity that enabled the hallucination in Pipeline A is simply absent in Pipeline B.This is similar in principle to how type systems work in programming languages: static types don’t eliminate all bugs, but they eliminate a class of bugs (type errors) that are disproportionately expensive to debug at runtime. A structured spec doesn’t eliminate all code generation errors, but it appears to eliminate the class of errors where the model substitutes its own assumptions for the developer’s intent.In the knowledge representation literature, this pattern is called making an ontology explicit [8] — defining the concepts, properties, and relationships in a domain so that all parties (in this case, the developer and the model) share the same understanding.Data EfficiencyPipeline B used 54 training examples vs Pipeline A’s 308. This is likely because the structured format constrains the model’s output space. With natural language, the model must learn both what to generate (the domain concepts) and how to generate it (the code patterns). With a structured spec, the “what” is given — the model only learns the “how.”I wouldn’t generalize this 6x ratio to other domains without more data. The efficiency gain depends on how much ambiguity the structured format removes, which varies by domain and task.What Didn’t WorkThe planner stage is unreliable. I built a few-shot planner that converts natural language to BuildSpec JSON using the same 7B model. For complex features (more than ~8 entities), it exceeds the token limit and produces truncated output. I added recovery logic to extract complete specs from partial output, but the planner remains the weakest link. For production use, I’d use a larger model or a rule-based decomposer for this stage.Training was memory-constrained. On 16GB, I had to reduce LoRA trainable layers from 8 to 4 for the latest round, which caused regressions (the SoftDeletes and JsonResource bugs). The model knew these patterns from earlier training but partially forgot them with reduced capacity.Repetition loops are stochastic. The 7B model occasionally enters degenerate repetition when generating longer outputs (~500+ tokens). This isn’t fixable through training alone — it’s a known limitation of autoregressive generation at this model size. I plan to add repetition penalty and automatic retry logic.The comparison isn’t fully controlled. Pipeline B benefited from all the lessons learned during Pipeline A’s development. I knew what bugs to watch for, what patterns to include in the system prompt, and what evaluation to run. A fairer comparison would train both pipelines from scratch with equal effort.How to Reproduce ThisEverything is open source:Code + Pipeline: github.com/florinel-chis/laravel-ai-genFine-tuned adapter: huggingface.co/fchis/Laravel-13x-Qwen2.5-Coder-7B-Instruct-LoRA-SpecTraining data: huggingface.co/datasets/fchis/laravel-buildspec-training (54 examples in OpenAI chat format)To run the full pipeline on a Mac with 16GB+ RAM:pip install mlx-lm# Generate from a natural language descriptionpython3 pipeline_spec.py "Create a REST API for a book library with authors"# Or from a spec file directlypython3 pipeline_spec.py --spec my_specs.json --output ./generated# Validate specs without generatingpython3 spec_compiler.py my_specs.jsonThe pipeline stages are: 1. planner.py — NL description to BuildSpec JSON (few-shot, same model) 2. spec_compiler.py — validates and normalizes specs (Practical TakeawaysFor anyone building domain-specific code generation, here’s what I’d suggest based on this experience:1. If your model keeps inventing things, the problem might be in the input format, not the model. Adding more training examples didn’t fix my hallucination bugs. Removing the ambiguity that allowed them did.2. Validate inputs, not just outputs. A spec compiler that catches errors in 3. Classify your bugs by type, not just count. Track whether each failure is “model assumed wrong domain knowledge” vs “model used wrong code pattern for the right concept.” If most failures are the first kind, structured input may help more than more training data.4. Start small. 54 examples on a 7B model running on a laptop produced usable results for a specific framework. You don’t need GPT-4 or 10,000 training examples for domain-specific code generation.LimitationsSingle framework (Laravel PHP), single model (7B), single hardware configSmall, self-designed benchmark (26 files, 3 apps)No comparison with frontier models (GPT-4, Claude) or larger open modelsThe structured format requires upfront design effort per frameworkThe spec compiler only validates individual specs; cross-file consistency checking is limitedResults are from a single developer’s evaluation — no inter-rater reliabilityRemaining bugs (3) show the approach doesn’t achieve zero-fix generationReferences[1] OpenAI. “Function Calling.” OpenAI API Documentation, 2024.[2] OpenAI. “Structured Outputs.” OpenAI API Documentation, 2024.[3] J. Liu. “Instructor: Structured Outputs for LLMs.” GitHub, 2024.[4] O. Khattab et al. “DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines.” ICLR, 2024.[5] B. Hui et al. “Qwen2.5-Coder: A Comprehensive Code-Specific Large Language Model.” arXiv:2409.12186, 2024.[6] Apple Machine Learning Research. “MLX: An Array Framework for Apple Silicon.” GitHub, 2023.[7] E. J. Hu et al. “LoRA: Low-Rank Adaptation of Large Language Models.” ICLR, 2022.[8] T. R. Gruber. “A Translation Approach to Portable Ontology Specifications.” Knowledge Acquisition, 5(2):199–220, 1993.This article documents an ongoing open-source project. The results are preliminary and based on a small benchmark. I welcome feedback on the methodology and suggestions for more rigorous evaluation.If you’re working on domain-specific code generation and want to compare approaches, I’d appreciate hearing about your experience — especially on different frameworks or model sizes.How I Used a JSON Schema to Fix Hallucinations in a Fine-Tuned 7B Code Generator was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.