Defending AI Agents
עברית Join waitlist
Menu

E3 · Lesson 07

An answer a program can read: schemas and one repair

When a person reads the answer, "The total is about half a million euros" is fine. When a program reads it, the program needs {"total_eur": 508900}, and "about half a million" is a failure that looks like a success. The loop's last job is to turn the model's final text into a value the caller can trust, or to say that it could not.

Ask, extract, check, repair once

  1. Ask. With an answer_schema, the system prompt gains one instruction: reply with only a JSON value matching this schema, followed by the schema itself (loop/structured.py, instruction).
  2. Extract. Models wrap JSON in prose and code fences: "Sure! Here it is:" and three backticks. extract_json takes the contents of the first fence if there is one, otherwise the first { or [ from which a complete JSON value decodes. That is what a person would take.
  3. Check. The value goes through the same check_arguments as tool arguments (lesson 2). A schema for a final answer and a schema for a tool call are the same kind of contract.
  4. Repair once. If the check fails, the loop appends a user message listing the errors and asks again. It is a user message, not a tool result, because a tool message must answer a call's id, and a final answer made no call. The complaint comes from the caller, and the caller speaks in the user's role. If the second reply also fails, the run stops with stop == "schema" and the errors.
>>> extract_json('Sure! Here it is:\n```json\n{"a": [1, 2]}\n```\nAnything else?')
{'a': [1, 2]}
>>> parse_final('{"total": "5"}', {"type": "object", "properties": {"total": {"type": "integer"}}})
(None, ["'total' must be integer, got string"])

Why one repair, not a loop

A repair is a conditional retry, and its value is an empirical question. If the first reply fails because of a slip (a trailing sentence, a string where a number belongs), the error list fixes it. If it fails because the model cannot produce the schema, more attempts produce more of the same at full price. The study measures this on four fact tasks and one CRM task, twice each, with a two-field schema. On qwen3:4b all ten replies conformed at the first attempt and six were correct (the build), so on this model the repair is untested insurance, and the dangerous cell below held four answers. The stopping rule should come from that data on your model: if the second attempt rarely rescues anything, drop it, and if a third would, the data will show that too.

Format can cost accuracy

Asking for JSON is not free. Tam et al. (2024) found a significant decline in reasoning when models were held to strict formats, and a larger one for stricter constraints. The cheap mitigation is structural: let the model reason in the run, through its tool calls and any thinking, and constrain only the final answer, which is what this loop does. Constrained decoding (E2 lesson 4; Willard and Louf, 2023) goes further and makes invalid output impossible to generate, so step 4 never fires. It constrains shape only. A schema-valid {"total_eur": 500000} is still wrong.

Correct and conforming are different measurements

Conformance is checkable without labels. Correctness needs the grader. Report both, because they fail independently:

correct wrong
conforms the goal the dangerous cell: a program will act on it
does not conform a parser problem an honest failure

A pipeline that reports only "valid JSON 98%" has measured the top row's total and called it accuracy. E9 builds graders for both columns. Module 8 makes the same point for detectors: a number travels with its population and its definition, or not at all.

Check yourself

  1. The reply is I found {"total": 5} but double-check {"total": 6}. What does extract_json return, and is that the right choice?
  2. Why is the repair message sent as a user turn and not as a tool result?
  3. Suppose a run of 12 gives 9 that conform at the first attempt and 11 of 12 after the repair. What has the repair bought, and what would you need to know before keeping it?
Answers
  1. {"total": 5}: the first complete JSON value. It is the defensible choice for a parser, but the reply contradicts itself, and no parser can resolve that. A schema with a single required field cannot detect it. A stricter rule (exactly one JSON value, nothing else) would reject the reply and send it to repair.
  2. There is no outstanding tool call to answer. The model's last turn had no tool calls, so a tool message would reply to nothing, and most servers reject that. The repair is new input from the caller, which is what a user turn is.
  3. Two runs, at the cost of one extra model call each in the three failed runs. With n = 12 the difference is not established by itself: the two rates' Wilson intervals overlap widely. Before keeping the repair, you want a larger sample, the paired counts (how many first-attempt failures the repair fixed), and the correctness of the repaired answers. A repair that produces conforming wrong answers has made things worse.