HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 15“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Structured Outputs, JSON Mode and Function Calling
TechLearningPro's Explain draft was a paragraph again, and the player needed more than a paragraph.
Course progress0%
Focus
16 guided sections
Practice signal
Concept-first lesson
Career prep
Foundation builder
AI-Powered Full Stack Development · Lesson 15 · AI and LLM Application Fundamentals
Lesson Overview
TechLearningPro's Explain draft was a paragraph again, and the player needed more than a paragraph. The panel had to show whether the answer was grounded in the excerpt, which heading it used, and a short explanation. A teammate asked the model for JSON in the prompt. The model returned a fenced code block, then a sentence apologizing, then JSON with a passingScore field nobody had asked to render. Another build turned on a provider "JSON mode" and skipped validation, so a grounded flag of true shipped beside a heading that does not appear in the lesson. A third experiment exposed function calling and let the model request complete_lesson. The function ran. Monday's board moved. The quiz table did not.
Structured output is how the application stops reading prose with includes("yes"). JSON mode, when the provider offers it, is a switch that asks for a JSON value. It is not a schema, and it is not an authorization decision. Function calling, in the chat-completions style this lesson parses, is the model proposing a tool name and a JSON argument string. Your server decides whether that tool exists, whether this tenant may run it, and what it is allowed to touch. complete_lesson is not a tool. Quoting a section the learner can already read can be a tool, and only after the id is on the allow-list for this request.
This lesson builds an explanation card validated with Zod, a reconciliation step that clears grounded when the cited heading is not in the excerpt, and a tool dispatcher that executes quote_section and refuses everything else. The HTTP call remains the client from lesson 14. The wording remains explain-v3 plus a schema instruction. Progress remains the quiz write from lesson 12.
Planning assumptions, labeled so they are not a provider feature matrix:
The lab sends an optional response_format of { "type": "json_object" } only when you pass jsonObject: true. That field is chat-completions style. Confirm the current provider supports it for the model id. The Zod parse runs either way.
Tool calls are parsed from choices[0].message.tool_calls, a shape several providers document. If your provider nests tools differently, change the parser only.
One tool round. Agents that loop live in a later module. This lesson does not give the model a second turn in the tests.
No live key. Injected fetch and test-key-not-a-secret.
Learning Objectives
By the end of this lesson you will be able to:
Separate free text, schema-checked JSON, and tool proposals, and match each to a product decision in Explain.
Define an explanation card in Zod and reject extra policy fields such as a passing score.
Strip a single surrounding markdown fence before parsing, and still reject prose that is not JSON.
Treat provider JSON mode as an optional request flag that does not replace validation.
Downgrade grounded when citedHeading is not contained in the authorized excerpt.
Parse a chat-completions-style tool_calls array, then JSON-parse the argument string.
Execute only quote_section, and only for a section id that was pre-authorized for this learner.
Refuse complete_lesson, set_progress, and any unknown name without calling a side effect.
Keep self-reported confidence out of authorization and out of the progress source.
Test the success card, the fence, the grounding downgrade, the allowed tool, and the denied tool.
Prerequisites
Working with LLM APIs and Model Providers for the port, the ledger, and the status map. This lesson adds a body flag and a second schema; it does not add a second retry policy.
You do not need a provider account. If a doc you read uses different tool JSON, adapt ToolCallSchema and leave the dispatcher rules in place.
Detailed Core Concepts
Three outputs, three product uses
Free text is what lesson 12 displayed. It is appropriate when a human reads it and the application does not branch. The moment the UI hides the tutor unless grounded is true, or shows a citation chip, the application is branching. Branching on a substring is how "not grounded" containing "grounded" becomes a bug. Branching belongs on a value Zod accepted.
JSON mode is a provider hint. In the chat-completions style, the request may include response_format: { type: "json_object" }. Models that honor it return a JSON value. They can still return the wrong keys, a string where you wanted a boolean, an empty object, or a faithful JSON encoding of a lie. Some model ids reject the field. A 400 in that case is the lesson 14 invalid_request: fix the adapter, do not retry blindly. This lesson always parses with Zod after the body comes back. If you leave the flag off, the same parser accepts raw JSON and a single fenced block, because that is what prompted models often emit.
Function calling is a proposal to run code. The model does not run it. The chat message includes tool_calls with a name and an arguments string. Your dispatcher looks up the name. Unknown names, and known-dangerous names, return refused_tool and execute nothing. The allowed tool in this lesson reads a section from a map the request already filtered. It does not open a database connection with the model's credentials, because the model has none.
A later module lets a model request tools in a loop with human approval for side effects. If you build that loop here, you will re-create the Monday incident with more steps. One read-only tool is the whole scope.
The explanation card
The card has four fields:
explanation: the sentence the panel shows, length-capped.
citedHeading: a heading copied from the excerpt, or an empty string when the model should decline.
grounded: the model's claim that the excerpt supports the explanation. The server may set this to false. The server does not set it to true if the model said false.
selfReportedConfidence: low, medium, or high. This is a label the model emits. It is not a calibrated probability and it is not an ACL.
.strict() on the Zod object rejects passingScore, completed, and any other key. Rejection is invalid_card. The UI shows the lesson without a card. It does not display the raw JSON. A model that "helpfully" adds completion advice fails the schema, which is the point of the strict object.
Reconciliation is the check the model cannot skip
After Zod succeeds, reconcileCard looks for citedHeading inside the excerpt. An empty heading with grounded: true is downgraded to grounded: false. A heading that does not occur in the excerpt is cleared and grounded becomes false. A heading that occurs and grounded: false stays false. You do not "fix" a cautious model into a citation.
This check is shallow. A heading can appear in the excerpt while the explanation talks about a passing score the excerpt never states. The check stops the specific incident of a citation chip pointing at a heading you do not have. It does not replace an eval set. Add a case when a new failure mode shows up. Do not tell learners the badge means "proven true." The badge means "the heading string occurs in the excerpt and the model set grounded."
Tools and authority
quote_section arguments are { "sectionId": "sec_..." }. The dispatcher holds allowedSectionIds for this request, built from the ACL, not from the model. If the id is allowed, it returns the quote already loaded for that id. If the id is well-formed but not allowed, it returns not_found without echoing other ids. If the name is complete_lesson or anything else, it returns refused_tool and does not import the progress service.
Argument strings are untrusted JSON. JSON.parse can throw. A throw is invalid_arguments, not a cue to eval the string. Do not pass tool arguments to a SQL template. Do not pass them to eval. The quote lookup uses a Map.
Tool choice belongs in the request only as documentation of the provider field you confirmed. This lesson's dispatcher does not need the model to be forced onto one tool for the card path. The card path sends no tools. The quote path sends one tool definition. Mixing "answer as JSON" and "maybe call a tool" in one prompt makes both parsers ambiguous. Two routes: POST /explain/card and POST /explain/quote. The player calls the card route for the panel. It calls the quote route when the learner clicks a section chip you rendered from real headings, and even then the server checks the id.
Version the schema with the prompt
explain-card-v1 names both the prompt and the schema. If you add a field, bump the version. Stored cards from v1 stay readable because you kept the old Zod object under the old id. Parsing v1 cards with the v2 schema is how a deploy breaks history. The client from lesson 14 already returns promptVersion from server config. Set that config to explain-card-v1 on the card route.
Self-reported confidence must not enter the progress source union. If a future chart wants it, store it on the draft row as a label, beside the prompt version, and keep it out of completed_at logic.
What JSON mode does not mean
It does not mean the provider validated your schema. It does not mean every model supports the flag. It does not mean fences are impossible if you forget the flag. It does not mean a second system of record. The Monday incident survived a perfectly valid JSON object { "tool": "complete_lesson" } because validity and permission were confused. Permission is the dispatcher and the quiz function. Validity is Zod.
Architecture and Request Flow
flowchart TB
subgraph browser [Browser]
Player[Lesson player]
end
subgraph api [TechLearningPro API]
Auth[Session tenant and lesson ACL]
CardRoute[Card route]
QuoteRoute[Quote route]
ZodCard[Explain card schema]
Reconcile[Heading reconciliation]
Dispatch[Tool dispatcher]
Progress[Progress service]
end
subgraph data [System of record]
DB[(PostgreSQL)]
end
subgraph provider [Provider]
Http[Chat completions style HTTP]
end
Player -->|card| Auth
Player -->|quote| Auth
Player -->|quiz| Auth
Auth --> CardRoute
Auth --> QuoteRoute
Auth --> Progress
CardRoute --> Http
Http -->|content string| ZodCard
ZodCard --> Reconcile
Reconcile -->|card or invalid_card| Player
QuoteRoute --> Http
Http -->|tool_calls| Dispatch
Dispatch -->|quote or refused_tool| Player
Progress --> DB
There is no edge from Dispatch to Progress. complete_lesson ends inside Dispatch.
Step-by-step Implementation
Package: packages/structured/. The HTTP helper is local and small so this lesson stands alone; production should call lesson 14's client and pass the extra body fields through the adapter. Tests inject fetch.
strict() drops the temptation to ignore unknown keys. A passingScore property fails the parse. JSON.parse of non-JSON throws into invalid_card. A fence with leading prose fails the anchored regex and then fails JSON.parse, which is what you want: do not scrape the first {...} out of a paragraph. Scraping is how a quoted example inside an explanation becomes the card.
Both unknown names and the explicit deny-list return refused_tool. The set documents the names that showed up in the incident review so a log can be grouped later if you split the reason. Behavior stays "do not run." allowed is built by the route from sections the ACL returned. A section that exists in PostgreSQL and is not in the map is not_found here, even if the model guessed a real id.
Step 3: Request bodies
The card request may set JSON object mode. The quote request sends one tool and does not set a card schema. Definitions are data the provider reads. They are not the dispatcher. If the definition and the dispatcher disagree, the dispatcher wins, and the disagreement is a bug to fix in the same pull request.
description:"Return a section the learner is already allowed to read.",
parameters:{
type:"object",
additionalProperties:false,
properties:{ sectionId:{ type:"string"}},
required:["sectionId"],
},
},
},
],
};
}
tools and response_format are labeled chat-completions style. Some providers use a different container. Keep that container in bodies.ts. temperature: 0 on the quote path is a request for a stable tool choice, not a guarantee. The dispatcher does not become optional when temperature is 0.
The card system instruction lives next to the schema version:
packages/structured/src/messages.ts
typescript
import{PROMPT_VERSION}from"./card.js";
exportinterfaceChatMessage{
role:"system"|"user";
content:string;
}
export{PROMPT_VERSION};
constCARD_SYSTEM=[
"Return a single JSON object with keys explanation, citedHeading, grounded, selfReportedConfidence.",
"citedHeading must be a heading that appears in the excerpt, or an empty string.",
"grounded is true only when the excerpt supports the explanation.",
"Do not add keys. Do not include quiz scores or completion.",
`promptVersion is ${PROMPT_VERSION} and is not one of your keys.`,
explainCard never reads tool_calls. If a model returns a tool call on the card route, content is empty or non-JSON and the result is invalid_card or invalid_body. That is acceptable. Do not "helpfully" dispatch tools from the card route. quoteSection never constructs a progress write.
Lesson 14's retry and ledger should wrap postJson when you assemble the real service. This file keeps the parse path readable. Do not copy a second, looser retry loop into the card route.
No network. If LLM_JSON_OBJECT is unset, jsonObject is false and the parser still accepts raw JSON. Turn the flag on only after the provider doc says the model accepts response_format.
Security and Privacy
The card schema is strict so a completion field cannot ride along as an ignored extra key. Ignored keys become displayed keys the day someone logs the raw object.
Reconciliation uses the excerpt the ACL already approved. It does not fetch a broader chapter if the heading is missing.
quote_section reads a map passed into the request. Building that map is the route's job: query sections with the tenant and the enrollment, then construct the map. A model-supplied id that misses the map returns not_found with no neighbor ids in the payload.
complete_lesson and set_progress do not call progressFromQuiz. They do not dynamic-import it. A unit test imports the dispatcher and asserts the outcome without a database.
Tool argument strings are parsed as data. They are not code.
selfReportedConfidence is not an authorization score. A high label with grounded: false still hides the citation chip.
The provider key stays in process.env.LLM_API_KEY via routeConfigFromEnv. Logs for this route use lesson 14's allow-list and add promptVersion plus invalid_card or refused_tool. They do not include the argument string if that string might echo a question; log the tool name and the reason.
JSON mode is not a privacy feature. The excerpt still leaves the server for the provider. Send the same bounded excerpt as lesson 12.
Error Handling
Reason
Who produces it
Learner sees
unauthorized
Route, before fetch
Lesson, no card
invalid_card
Zod, fences with prose, extra keys
Lesson, no raw JSON
truncated
finish_reason length
Lesson, no partial card
invalid_body
Completion schema
Lesson, tutor unavailable
refused_tool
Dispatcher
Quote panel hidden
not_found
Dispatcher
"That section is not available"
invalid_arguments
JSON parse or Zod on args
Quote panel hidden
no_tool_call
Quote route
Quote panel hidden
timeout, http_error, missing_config
HTTP helper
Lesson stays up
A reconciled card with grounded: false is a success. Show the explanation as an uncited note, or show the decline copy if explanation is the decline sentence. Do not show a citation chip. Do not offer "mark complete."
Provider 400 because response_format is unsupported should turn the flag off for that model id and try the prompt-only path in a later deploy, not in an automatic second request that you have not budgeted. Lesson 14 already refuses to retry 400. Honor that.
const excerpt ="Heading: Checkpoints\nThe server stores the checkpoint.";
test("parses a fenced card and rejects a passingScore key",()=>{
const fence ="`".repeat(3);
const fenced =parseExplainCard(
`${fence}json\n{"explanation":"The server stores the checkpoint.","citedHeading":"Checkpoints","grounded":true,"selfReportedConfidence":"medium"}\n${fence}`,
Add three more cases before you call the lab done: a cross-tenant card request that does not call fetch; a tool id of sec_other that returns not_found; a tool_calls entry whose arguments is not JSON. Eval for the card is a set of fixture completions plus, later, a budgeted live run that must produce strict JSON and survive reconciliation. A live run that returns grounded: true with a heading absent from the excerpt is a prompt defect only if reconciliation is broken. If reconciliation downgrades it, record the downgrade rate. A rising downgrade rate means the model is citing headings you do not have, which is the quality signal.
Do not eval selfReportedConfidence against reality. You have no calibration set. You may eval that the field is one of the three enums, which Zod already enforces.
Performance and Cost
The card and the quote are two calls when the player needs both. Do not nest them in one prompt to save a round trip if that reintroduces ambiguous parses. Two bounded calls are easier to time out and easier to ledger.
max_tokens of 500 on the card is enough for the JSON object. A larger cap invites the model to add a second object or a commentary that fails the anchored fence regex. Failures still cost the tokens already generated. Lesson 14 records that on truncation; do the same when you wrap postJson.
JSON mode can be slightly more reliable and does not remove the Zod cost, which is negligible next to the provider. The flag is not a latency feature.
Tool definitions add input tokens on the quote route. One small tool is cheap. A catalog of twenty tools on every Explain click is not, and it tempts the model to pick complete_lesson if you were unwise enough to list it. Do not list it "so we can refuse it in the model." Refuse it by absence from the request and by the dispatcher.
Caching a reconciled card uses the lesson 14 cache key plus explain-card-v1. Do not cache tool results under the section id alone across tenants.
Illustrative ratio: a strict schema failure after a full generation still spends output tokens. A pre-call that skips the provider when the question is empty, which lesson 12 already does, remains the cheapest failure. Reconciliation is free and should run on every success, including cache hits, in case the excerpt version changed and the cache key was wrong. If the cache key includes the lesson version, reconciliation on a hit is redundant and still cheap. Keep it.
Streaming a JSON card is awkward because the UI cannot trust a half object. Lesson 16 streams prose. Leave the card on a buffered response until the schema passes.
Knowledge Check
1. What problem does this capability solve?
It lets the Explain panel branch on a validated card, and lets a quote button run a read-only tool, without letting a JSON object or a tool name change lesson_progress. Extra keys and unknown tools fail closed.
2. What alternatives exist, and when would you choose each?
Free text fits a human-only note. A Zod card fits citation UI. Provider JSON mode fits when the current model card supports it, always with Zod behind it. Function calling fits a read the model must request by id. A hand-written parser fits a prototype you are about to delete. An agent loop fits the later module, with approval for side effects, not this button.
3. Which data, identity, and trust boundaries matter?
The excerpt and the allowed section map come from the ACL. The model proposes a card or a tool call. Zod and the dispatcher accept or refuse. promptVersion is the server constant explain-card-v1. The provider key stays in the server environment. Confidence labels do not authorize.
4. What can fail, and how should the system respond?
Invalid JSON, extra keys, truncation, and bad completion bodies yield no card. A heading that is not in the excerpt yields a card with grounded: false. complete_lesson yields refused_tool and no write. A section id outside the map yields not_found. Timeouts leave the lesson in place.
5. How would you test quality, security, performance, and cost?
Fixture tests cover fences, passingScore, reconciliation, the happy card, the refused tool, and the authorized quote. A cross-tenant test proves fetch is skipped. Cost review checks that denied tools are absent from the request body, not merely rejected after a large tool catalog. Quality review tracks downgrade rate by prompt version. Progress tests still show a quiz gate with no tool path into it.
Hands-on Assignment
Lab note. Inject fetch. Fixture key only. Do not register complete_lesson to "see the refusal in the provider."
Problem. Ship the card route and the quote route for Explain, with reconciliation and a dispatcher that cannot complete a lesson.
Tasks.
Implement the schema, reconciler, dispatcher, bodies, and routes.
Add tests for cross-tenant unauthorized, not_found, and non-JSON tool arguments.
Show the request body for the quote route contains quote_section and does not contain complete_lesson.
Write six control rows: strict schema, reconciliation, tool allow-list, ACL map, prompt version, progress isolation.
Describe what the player renders for grounded: false after reconciliation.
State when you would set LLM_JSON_OBJECT=true, and what you still parse with Zod.
Deliverable. Source, tests, control table, and the UI note for an ungrounded card.
Challenge. A product manager wants complete_lesson available when selfReportedConfidence is high. Write the refusal. Include the quiz function as the only writer, and describe the audit row you would require before any future tool could request a completion that a human still has to confirm. Do not implement that tool.
Rubric. Conceptual accuracy and architecture 20%. Working implementation 25%. Security and privacy 20%. Tests and evaluation 20%. Documentation of trade-offs 15%.
Common Mistakes
Skipping Zod because JSON mode is on. Symptom: extra keys or the wrong types reach the player. Cause: the flag was treated as a schema. Fix: parse with ExplainCardSchema on every response, flag or not.
Scraping the first object out of prose. Symptom: a quoted example becomes the card and the real answer is discarded. Cause: a greedy regex. Fix: accept raw JSON or one surrounding fence, and fail otherwise.
Listing complete_lesson so the model can be refused in natural language. Symptom: the model calls it and a loose dispatcher runs it. Cause: the tool catalog was the product surface. Fix: omit the tool, and keep the dispatcher refusal as defense in depth.
Trusting grounded: true. Symptom: a citation chip for a heading the lesson does not contain. Cause: the model field was displayed directly. Fix: reconcileCard against the authorized excerpt.
Using confidence as an ACL. Symptom: a high score completes the lesson or reveals a locked section. Cause: a probability-shaped string was treated as evidence. Fix: keep confidence on the draft. Keep ACL and quiz scores in their own code.
One prompt that both returns a card and calls tools. Symptom: empty content, or JSON inside a tool argument, and both parsers fail open. Cause: two contracts in one response. Fix: separate routes.
Parsing tool arguments with eval or interpolating them into SQL. Symptom: a section id that changes more than the quote. Cause: the argument string was treated as code. Fix: JSON.parse, Zod, and a Map lookup.
Summary
Explain's panel branches on an explain-card-v1 object that Zod accepts and that reconciliation can downgrade. Optional JSON object mode is a provider hint in the chat-completions-style body, not a validator. Function calling is a proposal: quote_section may run against a pre-authorized map, and complete_lesson may not run at all. The provider key stays in the server environment. The quiz remains the only progress writer.
Next Lesson Preview
Streaming AI Responses with Server-Sent Events streams a prose explanation as tokens arrive, using the same server boundary. The card route you built here stays buffered until JSON validates. Streaming a half-parsed card is the bug that lesson should help you avoid. /learn/genai and /learn/prompt remain the primers. The course map lives on the course home.
Your provider's current document for JSON response formatting and tool calls, read before you enable response_format or rename tool_calls. The shapes in this lesson are a labeled chat-completions style.