Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 5: Prompt Engineering and APIs

Week 05 / Lesson 2

Checking structured answers and proposed tool calls

Separate a valid data format from a correct answer or an authorized action.

Section 2.1 1 of 7

Overview

Focus

Separate a valid data format from a correct answer or an authorized action.

Your route through the lesson

  • 2.2 Objects, schemas, and local validation
  • 2.3 Grounding fields in the supplied source
  • 2.4 Tool-call requests and execution boundaries
  • 2.5 Put it into practice
  • 2.6 Guided comparison
  • 2.7 Valid structured data with invented values

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 2.2 2 of 7

Objects, schemas, and local validation

Focus

Parse objects and validate shape, field names, and exact value types.

Structured output represents an answer in a predictable data format. JavaScript Object Notation, written JSON, uses objects with named fields, arrays, strings, numbers, booleans, and null. Python's standard library json converts between that text format and Python dictionaries, lists, and values. Parsing establishes that the text follows JSON syntax; it does not establish the expected schema.

A schema is a contract for fields and types. The invoice answer requires exactly invoice_id and total_cents. The identifier may be a string or null; the total may be an integer or null. Extra fields can be rejected to prevent hidden action instructions from being smuggled into an otherwise accepted object.

The fixture validates exact Python types. This matters because bool is related to int in Python's type system: a broad isinstance(value, int) accepts True, but a financial amount should not accept a boolean. type(value) is int requires the exact integer type. Deliberately handling this edge case teaches why a format-valid and even loosely type-valid answer can violate the actual response contract. Validation errors should be explicit rather than silently coercing unsupported values.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Valid JSON contains total_cents as the string "375". Does the integer-or-null schema pass?
2. Why use an exact integer check for a financial total in this Python fixture?
3. An object has all required fields plus execute_shell. Under an exact-field schema?

Section 2.3 3 of 7

Grounding fields in the supplied source

Focus

Check every extracted value against source evidence after structural validation.

A correctly shaped object can contain invented data. Grounding means the answer's fields are supported by the supplied source under the task's rules. For invoice extraction, a reported amount must match the source amount, and an absent source field must remain null rather than becoming a plausible guess.

Take source invoice K with total 375 cents. The object with invoice_id K and integer total 900 passes syntax and field types but fails grounding. The validator compares it with the expected source-field projection and rejects it. A model explanation saying tax was probably added does not repair the mismatch because the task did not authorize calculating tax or inventing a total.

Grounding rules should match task semantics. Direct extraction can compare literal fields; a calculated answer needs a defined calculation and evidence for its inputs. A cited source identifier is useful only if the cited source actually supports the value. Keep structure, grounding, and authorization as separate results so diagnostics identify the mechanism. Automatically converting an unsupported amount to the expected answer would hide model error unless the product explicitly defines and reports that repair step.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Source K total is 375; answer K total is integer 900. Which check fails?
2. The model says it probably added tax, but extraction requires source totals only. Accept?
3. A source identifier is cited beside a total. What must still be checked?

Section 2.4 4 of 7

Tool-call requests and execution boundaries

Focus

Treat tool-call objects as proposals and authorize exact effects separately.

A tool-call format usually names an operation and supplies arguments. It tells the application what the model proposes; it is not an operating-system command that should execute automatically. Validate the operation name, argument types, permitted resources, actor, project, and destination before any effect.

For this invoice task, write_local_preview may be permitted in a disposable workspace, while send_invoice is not. A valid proposal with name send_invoice and destination unapproved remains unauthorized even if every field is well formed. A proposed read of another project's data also needs a permission check, not merely a matching schema.

Use an allowlist of supported operations and fail closed on unknown names or missing required arguments. An allowlist enumerates what is permitted rather than trying to list every forbidden command. Keep the execution function outside untrusted text interpretation. The core lab only checks proposal admission and executes no tool. That is honest decision-logic evidence. A future executor must enforce the same policy at the actual effect boundary and record outcomes, including uncertain or failed effects after an allowed decision.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A valid send_invoice proposal targets an unapproved recipient. What should happen first?
2. What is an allowlist?
3. A fixture checks a proposal but invokes no tool. What is demonstrated?

Section 2.5 5 of 7

Put it into practice

Focus

Run malformed, wrong-type, invented-value, and unauthorized-proposal checks.

Download week05.py, save it in an exercise folder, and run python week05.py --lesson 2. This single practice uses fixed objects and makes no model or tool call. It requires standard-library Python, a small processor, and seconds of runtime. The expected PASS names distinct rejection mechanisms.

json.loads parses text; malformed text raises json.JSONDecodeError. try and except let the fixture verify that expected failure. The focused valid example is:

import json
answer = json.loads('{"invoice_id":"K","total_cents":375}')
assert type(answer['total_cents']) is int
assert answer['total_cents'] == 375

The script accepts that source-supported answer, rejects string '375', rejects invented 900, and rejects True as an amount. It separately rejects malformed JSON and a send_invoice proposal absent from the allowed-tool set. Assertions raise a traceback if a boundary fails. These checks do not repair answers silently or execute proposed actions. They create a deterministic contract against which later model outputs can be compared without confusing successful parsing with successful extraction or actual permission.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. What exception is expected for the malformed string {not valid}?
2. Why test invented 900 separately from string "375"?
3. An assertion fails during the validator lab. What should the learner inspect?

Section 2.6 6 of 7

Guided comparison

Focus

Explain why syntax, schema, grounding, and permission produce different outcomes.

The worked valid answer parses into a dictionary with exactly two fields. Its identifier is K, its total is integer 375, and both match the source. It therefore passes syntax, schema, and grounding. No tool permission is needed because the answer is data and no effect is requested.

The malformed string fails before a dictionary exists. The string-valued total parses but fails the schema. Integer 900 parses and satisfies the type requirement but fails source comparison. True is rejected by the exact integer rule. Finally, the tool proposal can be structurally plausible while its operation is absent from the allowlist, so it fails authorization.

Keeping these outcomes separate improves correction. A syntax repair may fix quoting while leaving an invented total untouched. A grounding repair may correct the total while an extra send proposal still violates authority. Report each stage and retain raw outputs for diagnosis in a controlled environment, avoiding real secrets. A response should be accepted only when every applicable condition holds; majority success across validation layers is not meaningful because each layer protects a different required property.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A syntax repair fixes quotes but leaves invented total 900. Is extraction accepted?
2. Which failure occurs before a dictionary is available?
3. Can validation layers be combined by majority vote?

Section 2.7 7 of 7

Valid structured data with invented values

Focus

Reject valid structured data that invents an invoice value.

A source invoice has invoice_id M2 and no stated due date. A model returns a beautifully formatted object containing M2 and due_date '2027-01-15'. The date looks plausible and conforms to a date-shaped string, but no source evidence supports it. The answer fails the extraction contract even if a general schema permits dates.

The worked repair changes the contract to specify missing due_date as null and includes a missing-date fixture before comparing requests. The validator checks source support independently of formatting. If the product instead needs an estimated date, that becomes a different field with an explicit estimation rule and uncertainty status; it must not be presented as extracted fact.

This transfer applies to tool results, database records, and reports. Well-formed data is convenient to consume and therefore can make unsupported claims travel farther. Downstream systems may trust a typed field more readily than prose. Grounding checks at the boundary prevent that convenience from converting plausible fabrication into operational truth. A structured answer is a representation; its correctness still depends on the task, evidence, and authorization for any resulting action.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Source M2 has no due date; output invents a valid-looking date. What is wrong?
2. If estimated due dates are genuinely needed, how should they be represented?
3. Why can structured fabrication be especially consequential?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Connecting a local model through a reliable client →