Lab 25: code reads the answer
- Approved by
- Panaversity ·
You fix the one case that Lab 24 left red, and prove the fix broke nothing. Then you give the reading of every extracted invoice to code. The code has a schema that the API holds, a check on each value, and three gates. The gates send every answer the code will not accept to Ana Morales. The lab takes 2 sittings, and a free plan can spread them over days.
| Sitting | Do it after | Tasks |
|---|---|---|
| Sitting 1 | 25.1 to 25.6 | Setup, Tasks 1 and 2 |
| Sitting 2 | 25.7 to 25.11 | Tasks 3 to 5 |
Before you start
Important
The lab's files are not published yet. The download link for brightline-lab-ch25.zip and the answer keys below will work once they are. Until then, read the tasks with the chapter.
The download. Everything starts from brightline-lab-ch25.zip (download it here). It holds the brightline-ap repository at its tag ch24, with this lab's files added, so you can do this lab without having done Lab 24.
What you need. Node, Python with uv, git, the GitHub CLI, and Claude Code, Codex and OpenCode, each signed in. Your staging key for the Claude API goes in .secrets/anthropic.env. Task 5 needs an OpenAI project key with a hard spending limit, in .secrets/openai.env. No key passes through a chat.
The job. It is Monday, April 19, 2027. This morning's check in code refused INV-8340, from Midwest Packaging Co., because its terms came back as "Net 30 days". One extraction case in the suite has been red since Lab 24, and the threshold of 40 of 41 allows it.
How a task works. Start a fresh session with the named coding agent in brightline-ap/, and give it the task's prompt in plan mode. Make your prediction before the agent shows the result. Check the evidence against What good looks like, then download the task's answer key. End with a line in ports/ch25.md. docs/chapter-25/ holds the concepts as text for your agents.
Set up (Claude Code). Unzip the folder, then give the agent this prompt.
Read
README.mdandAGENTS.md. Put this folder under git with a main branch, in one first commit, "Start from the end of Chapter 24", and tag itlab25-start. Install the packages for both languages, asREADME.mdsays. Run the suite from its recorded answers, with no key and no network. Show me the report: how many cases pass, the threshold, and the one case it allows to fail. Finish by showing me that git tracks nothing in.secrets/.
What good looks like: one commit at the tag lab25-start. The suite reports 40 of 41 cases passing, which meets the threshold, and it names one extraction case as the known failure.
Sitting 1: one change, the whole suite
Before you start, answer in a line each: Who re-reads the answers after a prompt changes (25.1)? What are the six steps of a revision (25.6)? After this sitting, you can: trace a failing case to one part of a prompt, change only that part, and prove with the whole suite that nothing else broke.
New words in this sitting's prompts.
| Word in a prompt | What it means |
|---|---|
| Red case, green case | A case the suite fails, and a case it passes |
| Label | The value Ana wrote down for a field, which the suite compares with the worker's answer (Chapter 24) |
| Diff | The lines a change removes and adds, shown side by side |
| Owned file | A file only you may change. The agent proposes a change and waits. The golden set, the labels and the threshold are owned files |
| Replay | Run the suite on answers that were recorded earlier, with no request to the model |
| CI | The checks GitHub runs on every pull request (Chapter 15) |
Task 1. The red case, and the part that causes it (Claude Code)
Goal: the red case is stopped by a check in code, then fixed by one change to one part of the extraction prompt, and the failure has a name.
Predict: you will see the invoice, Ana's labels and the worker's answer side by side. Which part of the prompt causes the wrong field? Choose one: the line that says who the model is, the list of fields, the line that asks for JSON, or nothing the prompt says at all.
In plain words. You read one failing case as a test, find the piece the prompt is missing, and change that piece only.
Read 25.6 in
docs/chapter-25/. Run the suite from its recorded answers, and show me the one red case: the invoice's text, Ana's label for each field, and the worker's answer, side by side, with the field that differs marked. Stop there and wait for my prediction. Then:
- Say whether the answer is valid JSON, and whether the extraction step's check in code passed it. Name the failure with one of the six names 25.6 lists if one fits, and say so if none does. Then name what the prompt is missing, with the four kinds in 25.6's table, and say whether an example is the fix, by 25.4's test.
- Before any change to the prompt, write the check that would have stopped this answer live. It is plain code in
src/extract/validate.ts, with no model call. It refuses an answer whose total is not its subtotal plus tax, to the cent, and returnsneeds_reviewwith the reason in plain words. Add a test that feeds it the red case's recorded answer, and show me the test passing.- Show me the extraction prompt. For each field in the answer, quote the sentence of the prompt that tells the model what belongs in it, or say "no sentence".
- Propose one change, to that part only, as a diff. Change no other line. Wait for my approval.
- Save the revised prompt as a new file, with the next version in its name, as 25.1 does. Leave the old file as it is. Point the extraction step at the new version in the one place that names it.
- Run the red case alone, live. That is one request. Show me the new answer beside Ana's labels.
- Add a line to
ports/ch25.md: the case, the name of the failure, the piece that was missing, and the one sentence that changed.
What good looks like: the red case's answer is valid JSON with every field in place, and the check in code passed its shape. Its total is the invoice's subtotal. None of the six names fits well, because they say what went wrong in an answer. The table in 25.6 says what the prompt was missing, in its last row: a constraint that names the variant, here which amount is the total. The exam guide calls the fix instruction clarity. An example is not the fix, because the structure of the answer was not invented. The new check stops the recorded answer, with a reason that names the total. The prompt has no sentence that says which amount is the total. The change is four words in one sentence: the total, including tax. After it, the red case matches Ana's labels on every field. Your prediction: the list of fields, which names the total and never says which amount it is.
Checkpoint: the red case is green in a live run, and the diff is one sentence.
Saves: src/extract/validate.ts with its first check and test, the new version of the extraction prompt in prompts/, and your first line in ports/ch25.md.
Check it now. Download Task 1's answer key.
Task 2. The whole suite (Claude Code)
Goal: proof that the fix broke no other case, and a threshold with no known failure left in it.
Predict: you changed one sentence about the total. Can a case whose total was already right turn red because of it? Say yes or no, and why.
In plain words. You run the suite. Then you look at a second revision that the lab recorded for you. It is a larger rewrite of the same prompt, which fixes the red case and breaks others.
Read 25.1 and 25.6.
- Run the whole suite on the new prompt version. The 15 extraction cases run live, which is 15 requests. The 26 question cases replay their recorded answers, because the worker's own prompt did not change. Show me a table with one row for each extraction case: its result before my change, and its result after.
- If any case that was green is now red, stop and show me its answer beside Ana's labels. Do not fix it with a second edit. Undo my change, and propose a narrower one.
- Replay the recorded run in
tests/fixtures/revisions/broad-rewrite/. It is a larger rewrite of the same prompt. Show me its diff against the old prompt, and the same before and after table. For each case it turned red, quote the old sentence that case rested on.- The threshold file is an owned file. Propose a change to it: every case must pass, and no case is named as a known failure. Wait for my approval.
- Open a pull request with the new prompt version and the threshold, with the suite's report in its description. Wait for the suite's check in CI, and show me its result. I will merge.
What good looks like: on your prompt, 41 of 41 cases pass, and no row went from green to red. The broad rewrite turns the red case green and turns two other cases red. Each of the two rested on a sentence that the rewrite reworded while it fixed something else. Without the full run, that rewrite would have looked like a fix. The threshold now asks for every case, the check in CI is green, and you merged. Your prediction: yes. The model reads the whole prompt each time, so a change in one sentence can change an answer that has nothing to do with it.
Checkpoint: the pull request is merged, the suite passes 41 of 41, and the threshold names no known failure.
Saves: the threshold file, the pull request, and the before and after table in ports/ch25.md.
Check it now. Download Task 2's answer key.
Checkpoint 1: a prompt changed like code. Before Sitting 2, check that you can do these without looking back.
- Say why you change one thing at a time, and what the suite does that a person no longer does (25.1, 25.6).
- Say what the broad rewrite fixed, what it broke, and what caught it.
- Say why the red case passed Lab 24's check in code, although its total was wrong.
Sitting 2: the schema, the gates and the port
Before you start, answer in a line each: What does a schema that the API holds check, and what does it never check (25.7)? What does the code read before it parses anything (25.10)? After this sitting, you can: move an extraction to a schema the API enforces, and check each value in code. You can also prove with three recorded answers that no answer the code will not accept reaches the due-date code.
New words in this sitting's prompts.
| Word in a prompt | What it means |
|---|---|
| Enum | A fixed list of allowed values. Brightline's five terms are one (14.5) |
| Nullable | A field that may be empty, written null. It lets the model say "not on the invoice" |
| Range | A rule on a number's size, such as "zero or more". In a JSON schema it is written minimum or maximum |
| Fixture | A saved answer that a test feeds to the code, so the test needs no key and gives the same result every time |
| Gate | A check that an answer must pass before the next step sees it. An answer that fails a gate goes to needs_review, with the gate's name and the reason |
stop_reason | The field of a response that says why the model stopped (21.3) |
Task 3. A schema the API holds, and the value checks (Claude Code)
Goal: the invoice extraction runs under a schema that the API enforces, with the five terms and "other" as an enum. The invoice's text reaches the model as a tool result. Code checks the ranges and each value. INV-8340 is a case in the suite, and it passes.
Predict: 14.5's schema says the amount must be zero or more. If you send that schema to the API as it is, what happens: the API enforces the range, ignores it, or refuses the request?
In plain words. Now the API holds the shape, so "Net 30 days" cannot be written at all. You send 14.5's ranges to the API once, to see what it does with them, and your code checks the ranges itself. And the schema checks only the shape, never the truth, so your code checks each value against the invoice's own numbers and Brightline's records.
Read 25.7 and 25.9.
- Add INV-8340 to the golden set, and Ana's labels for it to the labels file, from the files in
data/invoices/new/. These are owned files, so show me the change and wait. Then replay this morning's recorded answer for it, and show me why the check in code refused it.- Write
schemas/invoice-extraction.schema.jsonwith the eight fields 25.7 shows.termsis an enum of Brightline's five terms and "other".poNumberis nullable. Every object refuses fields the schema does not name. Keep 14.5's ranges in this file: it is the full schema that your code checks against.- Send one live request with the full schema as it is, ranges included. That is one request. Show me the status code and the error's text.
- Write
src/extract/api-schema.ts, which builds what is sent to the API from the full schema, with every range and length rule stripped. Write a test that fails if anything it builds still holdsminimum,maximum,multipleOf,minLengthormaxLength.- Read 25.2, 25.5 and 25.8. Show me the request the extraction step sends, part by part: which text is in the system prompt, which is in the user turn, and where the invoice's text is. Move the invoice's text into the result of a strict tool,
get_invoice, that the portal's code serves, JSON-encoded, as 25.5 shows. Leave tool choice onauto. Add a check that refuses an answer with noget_invoicecall before it. It returnsneeds_review, with the gatestop reasonand the reason in plain words. Add a test for it.- Change the extraction call to send the stripped schema in
output_config.format, with the typejson_schema. Save the prompt as its next version. It no longer needs to ask for JSON. It must still say what each field holds, to writenullwhen the invoice does not carry a value, and to choose "other" when the terms are not one of the five.- Extend
src/extract/validate.tsfrom Task 1. It stays plain code with no model call. It takes a parsed answer and the tables it needs, and it returns eitherokorneeds_reviewwith the gatevaluesand a reason in plain words. It makes 25.9's five checks, in 25.9's order. First, each range that step 4 stripped. Second, the total equals the subtotal plus tax, to the cent. Third, the vendor exists in Brightline's tables. Fourth, the purchase order exists there when the answer names one. Fifth,termsis not "other". Write a test for each check.- Run the whole suite, with the 16 extraction cases live. Each case now takes two requests, one that asks for the invoice and one that answers, so that is 32 requests. The 26 question cases replay, because the worker's prompt did not change. Show me INV-8340's row and the totals. Do the same in the Python twin, and run its tests.
Check before you approve. Predict first: an invoice's terms are not one of the five, and the model chooses "other". Does the API accept the answer, and does the due-date code ever see it? Then ask the agent to show the lines of validate.ts that handle "other", and the test that proves it.
What good looks like: this morning's answer for INV-8340 holds "Net 30 days", and the check refused it, with no retry. The request with ranges comes back as a 400 error, because the API rejects a schema that holds minimum.1 In the new request, the rules are in the system prompt and the task is in the user turn. The invoice's text is one JSON string in the result of get_invoice. An answer with no get_invoice call before it ends at needs_review, with the gate stop reason. With the stripped schema, INV-8340's terms come back as "Net 30" and the case passes. The suite passes 42 of 42. Every test of validate.ts passes in both languages. For "other", the API accepts the answer, because the shape is right. The value check stops it, and it goes to needs_review. Your prediction: the API refuses the request.
Checkpoint: 42 of 42 cases pass under the enforced schema, and no range is left in what is sent.
Saves: schemas/invoice-extraction.schema.json, src/extract/api-schema.ts, the get_invoice tool and its check, src/extract/validate.ts with their tests and Python twins, the next version of the extraction prompt, and the changed golden set and labels.
Check it now. Download Task 3's answer key.
Task 4. Three gates, three fixtures (Claude Code)
Goal: every answer passes three gates in order before the due-date code sees it. The gates are the stop reason, then the schema, then the values. Three tests prove each gate from a fixture.
Predict: the fixture max-tokens.json holds an answer that was cut at the token limit. Its text still parses as complete JSON, with every field. Should the worker use it?
In plain words. When the model declines, nothing looks like an error (25.10). You put the gates in one place, in order, and you feed each one a recorded answer that it must stop.
Read 25.9 and 25.10.
- Write
src/extract/gates.ts. It is the only way an extracted invoice reaches the due-date code. It reads the response's stop reason first, before it parses anything:
end_turn: run Task 3's check that aget_invoicecall came before this answer. If none did, mark the invoiceneeds_review, with the gatestop reason. If one did, go on to the next gate.refusal: the model declined. Never parse the content, and never send the same request again. Mark the invoiceneeds_review, with the gatestop reason.tool_use: the model is asking forget_invoice. Run it, return its result and call again. This is not an answer yet.max_tokens: the answer was cut. Treat it as failed, even if its text parses. Send the request once more with a higher token limit. If the second answer is cut too, mark the invoiceneeds_review, with the gatestop reason.model_context_window_exceeded: the answer was cut, and a higher limit cannot help. Mark the invoiceneeds_review, with the gatestop reason, and send nothing again.- Any other value: mark the invoice
needs_review, with the gatestop reason.- The second gate parses the text. It matches each enum value to the schema's list ignoring upper and lower case, and passes on the list's own spelling. Then it checks the answer against the full schema, ranges excluded, because the ranges are the third gate's first check. A failure is
needs_review, with the gateschema. Text with no JSON value in it fails here too.- The third gate is
validate.ts. When a value check fails on something the invoice can settle (the total, or a purchase order or vendor that is not in the tables), send the failure back as a new message, at most twice. For a purchase order or a vendor, stop as soon as the same value comes back. Never send back terms of "other". After the second failed round, mark the invoiceneeds_review, with the gatevalues.- Write three tests in
tests/output-gates.spec.ts, each from one fixture intests/fixtures/output/:
refusal.jsonexpectsneeds_reviewat the gatestop reason, no parse, and no second request.max-tokens.jsonexpects exactly one more request, with a higher token limit, and thenneeds_reviewat the gatestop reason. The test answers the second request with the same cut answer.wrong-total.jsonis valid against the schema, and its total is its subtotal. It expectsneeds_reviewat the gatevalues, with a reason that names the total. The test answers each retry with the same wrong total.- In every test, assert that the due-date code was never called.
- Add a count by gate to the morning report: how many answers passed all three gates, and how many each gate stopped, with each stopped invoice's reason beside it for Ana. Count each stopped invoice once, at the first gate that stopped it.
- Run the three tests, then the whole suite from recorded answers. Write the Python twin, and run its tests.
Check before you approve. Predict first: which line would you delete to make the worker accept the refusal fixture as an empty invoice? Then ask the agent to show where gates.ts reads the stop reason, and confirm that no parse comes before that line.
What good looks like: three tests pass in each language, and none reaches the due-date code. The refusal is stopped before any parse, and it is sent once only, because a decline is never retried unchanged (21.3). The cut answer is sent once more with a higher limit, then handed to Ana. A stop of model_context_window_exceeded is treated as cut too, as Anthropic's guide says. But it is not sent again, because a higher output limit does not make the window larger.2 The wrong total passes the first two gates, since its shape is right, and the third gate stops it. The report's count by gate shows every invoice in exactly one row: passed, or the first gate that stopped it. Your prediction: no. Anthropic's guide says to treat any answer that stopped at the token limit as failed, even if its text holds valid JSON.3
Checkpoint: each of the three fixtures ends in needs_review with its own gate and reason, and the suite still passes 42 of 42.
Saves: src/extract/gates.ts, tests/output-gates.spec.ts, the three fixtures' tests in both languages, and the report's count by gate.
Check it now. Download Task 4's answer key.
Task 5. The port (Codex. The open-weight part is advanced, OpenCode)
By hand first. In the OpenAI dashboard, check that your project has a hard spending limit. Paste its key into .secrets/openai.env with your editor.
Goal: the same extraction on OpenAI's Structured Outputs, through the same validator, with a decline mapped to the same gate. A record of what moved unchanged and what did not.
Predict: which of your files will have no diff after the port? Choose from the prompt, the schema that is sent, the gates and the validator.
In plain words. You move the same extraction to a second AI vendor, which enforces a schema too. Then you record which of your files changed, and which moved unchanged.
Read 25.11. Work in
ports/openai/extract/.
- Run the recorded tests in
tests/fixtures/openai/first. They need no key.- Write the same extraction on OpenAI's Responses API, with the schema in
text.format, the typejson_schemaandstricton. Build what is sent from the same full schema. In strict mode every field is required, so write a field that may be empty as a union withnull.- Map OpenAI's answer onto the same three gates. A
refusalitem in the content is the model declining:needs_reviewat the gatestop reason, never parsed and never sent again unchanged. A response whose status isincomplete, with the reasonmax_output_tokens, is a cut answer: one more request with a higher limit, thenneeds_review. Everything else goes to the schema gate, and then tovalidate.ts, unchanged.- Make the refusal test and the cut-answer test pass from the OpenAI fixtures, and run the wrong-total fixture through the same validator.
- Run the 16 extraction cases live on the staging OpenAI project. Tell me how many requests that is before you send them. Show me a table of each case's result on both vendors.
- Write the port's section in
ports/ch25.md: what carried over unchanged, what changed, and why.
What good looks like: the validator, the golden set and the labels have no diff. The gates gained one small mapping. Your notes name at least these differences. OpenAI reports a decline as a refusal item in the content, and a cut answer as a status of incomplete, where Claude reports both in the stop reason.4 In OpenAI's strict mode every field is required, and an empty field is a union with null.4 OpenAI's schema accepts minimum and maximum, so a range could stay in what is sent, and your code checks it all the same.4 The wrong total is stopped at the gate values on both AI vendors, because no schema checks the truth. Your prediction: the validator. The prompt needed no change either, if it named no AI vendor.
The open-weight part (advanced, OpenCode). A reader on the main path can skip it.
Read the open-source part of 25.11. Run the same 16 extraction cases on an open-weight model behind a local server that takes a JSON schema. I will choose the server and the model. Pass the stripped schema in the server's own parameter, and send every answer through the same gates and the same validator. Count how many answers each gate stopped, and compare the counts with the two hosted runs. Then find out whether this server enforced the schema, or accepted it and did nothing: send one request with a field the schema refuses, and show me what came back. Record all of it in
ports/ch25.md.
What good looks like: a count by gate for the local run, beside the two hosted runs. Your notes say whether the server enforced the schema. Some local servers do. Others drop a rule they do not support and report no error, as llama.cpp's guide says: "Unsupported features are skipped silently."5 Where the schema is only requested, the schema gate catches more, and the same validator still decides.
Finish: the pull request and the tag.
Update
README.mdanddocs/deploy.mdwith the extraction's gates and the report's count by gate. Run/code-reviewand/security-reviewon the branch, and fix or answer every finding. Open the pull request, wait for its checks, and show me both reviews. I will merge. Then tag the mergech25, push the tag, and from a clean clone of the tag run every test that needs no key.
Checkpoint: the tag ch25 passes from a clean clone, and ports/ch25.md has a section for each port you ran.
Saves: ports/openai/extract/, the port's tests, ports/ch25.md, and the tag ch25.
Check it now. Download Task 5's answer key.
Checkpoint 2: code reads the answer. Check that you can do these without looking back.
- Name the three gates in order, and one fault that each one catches.
- Say why the wrong total passed the schema, and what stopped it.
- Say what happens to a decline, and to a cut answer, and why the two are handled differently.
- Say which of your files moved to a second AI vendor unchanged.
Required and optional
Required: the setup and Tasks 1 to 5, with the OpenAI part of Task 5. Advanced: the open-weight part of Task 5.
Apply it to your vertical (optional)
Pick one document your own business reads every day, such as an order, a claim or a lab result. List its fields. Mark each one as free text, one of a fixed set, or a number. Then write three value checks that a schema could never make, each against a record your business already keeps.
If something goes wrong
| What you see | Why | What to do |
|---|---|---|
A 400 error that names minimum or maxLength | A range or length rule is still in the schema that is sent | Strip it in api-schema.ts, and check it in validate.ts (Task 3) |
| A case that was green is red after your change | The change altered an answer it was not meant to change | Undo it, and propose a narrower one. Never add a second edit to the same change (Task 2) |
| The refusal test parses an empty answer | The code parsed before it read the stop reason | Move the stop reason to the first line of gates.ts (Task 4) |
| The cut-answer test loops | The retry has no limit | Allow exactly one retry, with a higher token limit (Task 4) |
| A live run differs from the recorded one | A model's wording changes from run to run | Compare the fields with Ana's labels, not the text. Record the difference in ports/ch25.md |
Artifact checklist
- The extraction prompt's new versions in
prompts/, each reviewed in a pull request - The threshold file with no known failure, and INV-8340 in the golden set with Ana's labels
-
schemas/invoice-extraction.schema.json, andsrc/extract/api-schema.tswith its test -
src/extract/validate.tsandsrc/extract/gates.ts, with their Python twins -
tests/output-gates.spec.ts, withrefusal.json,max-tokens.jsonandwrong-total.jsoneach ending inneeds_review - The morning report's count by gate
-
ports/openai/extract/, andports/ch25.mdwith every prediction and each port's notes - The tag
ch25
Exam notes
Sources
- Owner
- Panaversity