A base model keeps generating forever, drifts off your format after two or three examples, and never stops where you want. If you tried pulling JSON out of Prelude 9B after my earlier post on using base models, you already know the raw output needs work before any parser will accept it.
By the end of this article you'll have a prompt pattern, stop-token setup, and validation loop that turns a base model into a dependable JSON extractor.
Stop the model at the right place
A base model has no idea your task ends. If you ask for JSON and then cut it off, it happily continues into a second example, a comment, or a repetition of your own prompt. The fix is explicit stop sequences.
from transformers import pipeline pipe = pipeline( "text-generation", model="prelude-9b", ) def extract(prompt: str) -> str: out = pipe( prompt, max_new_tokens=200, do_sample=False, stop=["\n\n", "</json>"], return_full_text=False, ) return out[0]["generated_text"] Two things matter here. First, return_full_text=False keeps the prompt out of your output, which matters more with base models because the prompt is long and easy to confuse with the completion. Second, "\n\n" as a stop works because in-context examples teach the model that a blank line means "next record". Structure your prompt so a blank line really does mean that.
If you use vLLM instead, the same idea lives in SamplingParams(stop=["\n\n"]). The principle transfers; the flag name doesn't.
Teach the format, don't request it
Instruction-style prompts like "Return valid JSON" barely work on base models. These models are pattern completers. Show three or four complete input/output pairs, end with a partial example, and let the model finish it.
Extract the name and city from each message as JSON. Message: Hi, I'm Marta from Lisbon. {"name": "Marta", "city": "Lisbon"} Message: This is Dev here, calling from Toronto. {"name": "Dev", "city": "Toronto"} Message: Hey, Lena checking in from Berlin. {"name": "Lena", "city": "Berlin"} Message: Carlos here, based in Bogotá. {"name": "Carlos", "city": "Bogotá"} Message: Pat from Seattle. {"name": "Pat", "city": "Seattle Note the last line is deliberately incomplete. The model completes the pattern instead of inventing a new format. Ending on a partial output is the most effective single trick for base models, and it costs nothing.
Keep examples short and on the same shape. A fourth example with an extra key will teach the model to sometimes emit extra keys.
Validate, trim, and retry on failure
Even with good prompting, JSON breaks: trailing commas, unescaped quotes in the input, a city name the model completes into prose. Parse defensively. On failure, first try trimming to the last closing brace; if that fails, retry the generation.
import json def safe_extract(message: str, prompt_template: str, max_retries: int = 2): for attempt in range(max_retries + 1): raw = extract(prompt_template + f"\n\nMessage: {message}\n").strip() try: return json.loads(raw) except json.JSONDecodeError: pass # Common failure: max_new_tokens cut the object off mid-way. # Everything up to the last closing brace is usually valid. if raw.startswith("{"): end = raw.rfind("}") if end != -1: try: return json.loads(raw[: end + 1]) except json.JSONDecodeError: pass # Full retry: sampling variation often fixes a malformed attempt. return None The rfind("}") recovery handles the most common real failure: truncation. When max_new_tokens cuts the model off mid-object, everything up to the last closing brace is usually valid. Log how often the recovery path fires. If it fires more than a few percent of the time, your max_new_tokens is too low or your examples have drifted in size.
Here are the failure modes you'll actually see, and what each one tells you:
| Symptom | Likely cause | Fix |
|---|---|---|
| Output continues past the JSON | Missing stop sequence | Add "\n\n" or a sentinel token to stop |
| Extra keys appear sometimes | Inconsistent examples | Make every example identical in shape |
Output starts with prose, not { | Prompt doesn't end mid-JSON | End your prompt inside the last example |
| Truncated objects | max_new_tokens too low | Raise it or trim input text |
| Model echoes the whole prompt | You returned the full text | Set return_full_text=False |
Handle missing fields explicitly
Few-shot examples quietly encode assumptions. If your examples all contain a city and a real message has none, the model will invent one rather than emit null. That invented value looks confident and passes validation.
Add at least one example in your prompt where a field is missing, and show exactly how you want that handled:
Message: Anonymous tip, no name given. {"name": null, "city": null} Without that example, null behavior is undefined. With it, the model treats absence as a pattern like any other.
Know when to switch approaches
If your extraction task needs deep nesting, conditional schemas, or output longer than a couple hundred tokens, few-shot prompting a base model fights the model's nature. At that point your two practical options are a chat-tuned model of similar size, or constrained decoding. Libraries like Outlines and llama.cpp grammars let you pass a JSON schema and get structurally valid output guaranteed, working with base models rather than against them.
I'd draw the line at nesting depth two. Flat key-value extraction is where few-shot base models work well; beyond that, you spend more effort on the retry loop than on the task itself.
Key takeaways
- Base models complete patterns, so end your prompt inside an unfinished example instead of issuing instructions.
- Set explicit stop sequences and
return_full_text=False, or your parser will choke on the model's continuation. - Include an example showing missing-field behavior, or the model will invent values for absent data.
- Recover truncated JSON by cutting at the last closing brace, and track how often you need to.
- Past shallow, flat schemas, switch to a chat-tuned model or constrained decoding with a JSON schema.
Source
Prelude 9B Won't Answer Your Questions (Yet) — this follow-up adds the structured-output layer: prompt patterns, stop sequences, validation, and when to switch tools.
Support this work
These write-ups are researched and published with no paywall, sponsor, or tracking. If one saved you an afternoon, a small tip keeps them coming.
USDT, USDC or USDD · TRC-20 (Tron)
TFTNsfyomKrnUutRjBTGVULp19ByW29KbY