Structured output with a retry budget
When the model's JSON fails validation, hand the error back and let it correct, with a cap on attempts and characters.
validate(value) is already written: it returns the list of errors of a { cliente, total, moneda } object, empty when it is valid. scriptedModel(replies) builds a stand-in model that returns those replies in order and records in model.calls the messages it was sent each time.
Write askStructured(model, prompt, { maxAttempts, maxChars }), defaulting to 3 and 2000:
- Start with
messages = [{ role: 'user', content: prompt }]. - Ask for a reply with
await model(messages). Count the attempt and add the length of the reply to the characters spent. - Try
JSON.parse. If it fails, the error list is['no es JSON']; otherwise it isvalidate(value). - With no errors, return
{ ok: true, value, attempts, spent }. - With errors, append to
messagesthe model's reply (role: 'assistant') and ausermessage withREPAIR + errors.join('; '), and go back to step 2.
Before each request check the budget: if you have already made maxAttempts attempts, or spent maxChars characters or more, return { ok: false, errors, attempts, spent } with the errors of the last attempt. The function never throws because of a bad reply.
Challenges 0/6
- A valid reply first time: one attempt and one request
- A wrong type goes back to the model with the validator's error
- A reply that is not JSON breaks nothing: it is asked again
- Several errors travel together, separated by "; "
- Out of attempts, it returns ok: false with the last errors
- The character budget cuts in before the attempt budget
async function askStructured(model, prompt, { maxAttempts = 3, maxChars = 2000 } = {}) {
const messages = [{ role: 'user', content: prompt }];
// loop while attempts < maxAttempts and spent < maxChars:
// reply = await model(messages); count the attempt and reply.length
// errors = ['no es JSON'] when JSON.parse throws, else validate(value)
// no errors: return { ok: true, value, attempts, spent }
// errors: push the reply as assistant and REPAIR + errors.join('; ') as user
// budget spent: return { ok: false, errors, attempts, spent }
const reply = await model(messages);
return { ok: true, value: JSON.parse(reply), attempts: 1, spent: reply.length };
}
askStructured(scriptedModel([BAD_TYPE, GOOD]), PROMPT).then((r) => console.log(r), (e) => console.log('threw:', e.message));Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.
Why this matters
Handing the model its own error is the most effective repair there is: "total: must be a number" fixes more than repeating the prompt in capitals. The risk is in the loop. A small model that cannot produce the format will try as many times as you let it, and every attempt carries the whole conversation so far, so the cost grows with each turn. A cap on attempts and another on size turn that case into a clean failure you can log and pass to a person. How many replies arrive right first time with an enforced schema is measured in Ollama structured output with a JSON schema: 40 invoices.
Go deeper: the Ollama reference →
This in production, with your data? Let's talk for 15 minutes →