Chapter 2. Structured output and tool calling

Learning objectives

  • Explain the scope of guarantees provided by instructions, JSON mode, and schema-based structured output, respectively, and select the appropriate method.
  • Derive schemas from business concepts and adapt them to vendor-specific strict rules.
  • Design code that validates results across three stages: syntax, schema, and semantics.
  • Define tools, implement tool calling loops as budgeted state machines, and return results to the conversation in the exact format.
  • Combine parallel calling, tool choice options, and execution permissions to design a secure tool loop.

Introduction

A tax accounting app built a feature to extract expense line items from receipt photos and enter them into a ledger. Relying solely on the instruction "Respond in JSON" worked without issue during demonstrations. In the first week of production, three incidents occurred. In one instance, the sentence "Here is the result:" was prepended to the response, breaking parsing; in another, an amount arrived as the string "12,000원", causing the sum calculation to halt; and in the final instance, the format was perfect, but the total did not match the sum of the line item amounts. The first was caused by not enforcing the format, the second by failing to design the schema to fit the business requirements, and the third by assuming that if the format is correct, the content must also be correct.

This chapter covers two features that make model responses reliable for programmatic consumption. Structured output fixes the shape of the response, and tool calling allows the model to request application capabilities. The first part examines schema design and validation, and the second part sequentially covers tool definition, call loops, returning results, parallel calling, and execution permissions.

Key concepts

Structured output is a mold

When kneading dough by hand, the shape varies slightly each time, but pouring it into a mold determines its shape. If the instruction "Respond in JSON" is shaping by hand, structured output is a mold. The provider compiles the JSON schema into a grammar, constraining the generation process to conform to that grammar. This approach is commonly called constrained decoding.

Method What is guaranteed What is not guaranteed
Instruction None (generally follows) Format, fields, types
JSON mode Valid JSON Schema compliance
Structured output (strict) Compliance with the specified schema Format during refusal or truncation, value accuracy, business rules

OpenAI documentation makes it clear that JSON mode (json_object) guarantees only valid JSON and does not guarantee schema compliance. When using JSON mode, the word "JSON" must appear somewhere in the messages, and it also warns that if you do not instruct the model to produce JSON, it may continuously output whitespace until it hits the limit.

How to enable by vendor and selection criteria

Vendor Structuring the response itself Structuring tool arguments
OpenAI Responses API In text.format: type: "json_schema", name, schema, strict: true In the function definition: strict: true (The Responses API attempts normalization to strict even if omitted, so specify strict: false to disable it)
Anthropic Messages API In output_config.format: type: "json_schema", schema In the tool definition: strict: true
Gemini Interactions API In response_format: type: "text", mime_type: "application/json", schema (The generateContent API uses response_json_schema in the SDK or responseFormat.text.schema in REST. The legacy responseSchema is a subset of the OpenAPI 3.0 schema) parameters schema of the function declaration

Which to use is determined by the purpose of the result. OpenAI documentation guides that if you are connecting the model to system tools, functions, or data, use function calling; if you want to define the shape of the response returned to the user, use text.format. Gemini documentation similarly distinguishes that structured output is for the format of the final response, while function calling is for actions during the conversation.

Requests using a schema for the first time have higher latency because of grammar compilation (Anthropic caches compiled grammars for 24 hours after their last use). OpenAI and Anthropic SDKs generate schemas from Python Pydantic models and TypeScript Zod schemas and parse responses, reducing discrepancies between hand-written schemas and code types.

Strict schema rules and vendor differences

Strict mode accepts only a subset of JSON Schema, not the entire specification. The pitfall is that the subset differs across providers.

Rule OpenAI Anthropic
additionalProperties false required on all objects false required on all objects
Optional fields Place all fields in required and represent them as nullable types Allows fields not in required (limit on the number of optional fields)
Number and string constraints Supports minimum, maximum, multipleOf, pattern, format (not supported on fine-tuned models) Does not support numeric constraints like minimum and maximum, nor minLength and maxLength
Recursive schemas Supported via $ref Not supported
Top-level (root) Must be an object, and anyOf at the root is not allowed (allowed for child properties) —
Output key order Schema order Required fields first, followed by optional fields
Complexity limits 5,000 properties, 10 nesting levels, 1,000 enum values, etc. 20 strict tools, 24 optional parameters, 16 union-type parameters

In OpenAI strict mode, optional values are written as nullable types instead of omitting fields.

{
  "type": "object",
  "properties": {
    "order_id": { "type": "string" },
    "memo": { "type": ["string", "null"] }
  },
  "required": ["order_id", "memo"],
  "additionalProperties": false
}

Using unsupported features in Anthropic results in a 400 error. Anthropic SDK helpers strip unsupported constraints from the schema and move them into field descriptions, and Pydantic-based messages.parse() or TypeScript zodOutputFormat() re-validates responses against the original constraints. When using jsonSchemaOutputFormat() without Zod or making direct calls without an SDK, the application must perform the same validation. Gemini also accepts only a subset, and very large or deeply nested schemas may be rejected.

Deriving schemas from business concepts

A schema is not merely the shape of a response, but a contract between the application and the model. When designing it, establish four things.

  1. The meaning of absent values. "Field absent", null, empty string, and empty array must carry distinct meanings. If a receipt where the total is not printed and one where it is printed but illegibly blurred are both collapsed into the same null, downstream processing loses its direction. Include an enum field that captures the reason.
  2. Units and representations. Define amounts as integer units of KRW, dates as ISO 8601 (2026-10-20), and ratios as floats between 0 and 1. If the verbatim text representation is needed, collect it in a separate field (raw_date).
  3. Values the model generates versus values the server assigns. Do not have the model generate values known by the system, such as order numbers, creation timestamps, and user IDs.
  4. Versioning. Changing fields in production affects UI screens, storage, and batch jobs alike. Not only deletions and semantic changes, but also adding fields is incompatible with consumers that validate with additionalProperties: false. Provide a schema_version, have consumers branch their processing by version, and update them in lockstep.
{
  "type": "object",
  "properties": {
    "schema_version": { "type": "string", "enum": ["2"] },
    "total_krw": { "type": ["integer", "null"] },
    "total_status": { "type": "string", "enum": ["read", "not_printed", "illegible"] },
    "purchased_on": { "type": ["string", "null"], "format": "date" },
    "category": { "type": "string", "enum": ["meal", "supplies", "transport", "other"] }
  },
  "required": ["schema_version", "total_krw", "total_status", "purchased_on", "category"],
  "additionalProperties": false
}

Validating in three stages

Even when using structured output, validation is not complete. Dividing validation into three stages clarifies the causes of failure and the corresponding responses.

Stage Question If it fails
0. Response status Is it not a refusal or truncation? Do not parse. Proceed to stop reason handling from Chapter 1
1. Syntax Does it parse as JSON? Rare in structured output. Suspect truncation or refusal
2. Schema Do fields, types, and enum values match? Code bug or schema mismatch. Log and retry once
3. Semantics Does it conform to business rules? Human review queue, clarification question to user, or hold

Stage 0 is easy to overlook. Anthropic documentation notes that refusal (refusal) and token ceiling reach (max_tokens) responses may not conform to the schema, and OpenAI likewise instructs checking status: "incomplete" first. Examples of Stage 3 include relational checks such as "sum of line item amounts = total", "refund amount ≤ payment amount", and "end date ≥ start date". As the Gemini documentation puts it, even if the output is syntactically valid JSON, the application must always validate the values.

There are subtle pitfalls as well. Anthropic documentation states that structured output does not guarantee the case of enum values, recommending case-insensitive comparisons and advising against creating enum values that differ only by case. It also notes that because compiled schemas are cached separately from message content for up to 24 hours after their last use, sensitive information such as customer names should not be included in field names, descriptions, or enum values.

A tool definition is an execution contract

Tool calling (function calling) is a feature that informs the model that "these capabilities exist" and allows the model to propose names and arguments when needed. The model does not directly execute the tools we define. Execution is handled by the application (server tools executed by the provider on your behalf, such as web search, are an exception). A tool definition consists of a name, a description, and an input schema; for the model, the description is its entire user manual.

Anthropic documentation identifies detailed descriptions as the single factor with the greatest impact on tool performance, recommending at least 3–4 sentences per tool describing what it does, when to use it and when not to use it, the meaning of each parameter, and limitations such as information it does not return.

Before After
"description": "Look up reservation" "description": "Looks up a customer's existing repair reservation by reservation number. Do not use when finding new available reservation slots (use find_slots). The reservation number is 10 characters starting with 'R-'. Return values are status, visit date and time, and assigned technician name; payment information is not returned."

Other design principles are as follows:

  • Provide examples for format-sensitive arguments. Anthropic provides an input_examples field for including examples that pass schema validation.
  • Combine interrelated operations into a single tool with an action parameter, and prefix names (billing_, calendar_) if they span multiple services.
  • Include only information needed for the next decision and stable identifiers in results, and do not have the model fill in values that are already known (such as user IDs) (OpenAI).
  • Keep the number of tools small. OpenAI recommends fewer than 20 functions at the start of a turn, and Gemini recommends 10–20 or fewer active tools.

Turning the tool calling loop into a state machine

Tool calling does not end with a single request; it runs in a loop.

  1. Send a request along with tool definitions.
  2. Extract tool calls (name, arguments, call ID) from the response.
  3. Validate arguments and permissions, and execute them in the application.
  4. Pair results with call IDs, append them to the conversation, and request again.
  5. Finish when a final answer arrives, or return to step 3 if another tool call arrives.

Starting with a simple while statement leads to infinite calls, erroneous termination, and runaway costs. Thinking in terms of a state machine reveals missing paths. States cycle through "generating → call requested → validation → execution → returning results → generating" before terminating in "completed" or "budget exceeded". Set budgets across three dimensions: step count, elapsed time, and token cost.

const budget = { maxSteps: 6, deadlineMs: Date.now() + 30_000, maxTokens: 60_000 };
let usedTokens = 0;
for (let step = 0; ; step++) {
  if (step >= budget.maxSteps || Date.now() > budget.deadlineMs || usedTokens > budget.maxTokens) {
    return handOff("budget_exceeded"); // Hand off to human agent, preserve partial results
  }
  const res = await callModel(messages, tools);
  usedTokens += totalTokens(res.usage); // Sum up including cached tokens
  const outcome = classify(res.stop_reason); // Classifier from Chapter 1
  if (outcome !== "needs_tool") return finish(res, outcome);
  const results = await runTools(res); // Validation → execution → result envelope
  messages.push(assistantTurn(res), toolResultTurn(results));
}

You do not necessarily have to write the loop manually. Helpers like the Anthropic SDK's Tool Runner automatically handle the loop of tool execution and returning results. However, budgets, permission checks, and audit logging remain the responsibility of the application in all cases.

Returning results to the conversation

The model's call and its result are paired by call ID. The format varies across vendors.

Vendor Model's call Returning results
OpenAI function_call item: call_id, name, JSON string arguments function_call_output item: identical call_id, output (usually a string)
Anthropic tool_use block: id, name, object input tool_result block in the next user message: tool_use_id, content, optionally is_error
Gemini Function call step: name, arguments, call ID function_result: name, call_id, result

Anthropic has strict placement rules. The tool_result must appear in the user message immediately following the corresponding tool_use, no other messages may be placed in between, and it must precede text within the content array. Appending text directly after a result can also cause empty responses. OpenAI's arguments is a JSON string requiring parsing, and functions without return values return a string indicating success or failure.

Failure is also a result. In Anthropic, write what went wrong and what to try next along with is_error: true. Stating "Inventory system unresponsive. Retry in 60 seconds or query a different branch" is better than simply "failed", and when an error result is returned for a call with invalid arguments, Claude typically corrects and retries two to three times. Because differing result shapes across tools complicate interpretation, define a common envelope.

{ "status": "needs_info", "data": null, "error": null, "hint": "The building and unit number of the visit address are required" }

status values like ok, error, and needs_info are generally sufficient. Place an upper limit on result size, and omit personal information that the model does not need to know before sending the result.

Parallel tool calling

The model can request multiple tools simultaneously in a single response. Anthropic documentation notes that the API does not prescribe an execution order, advising that independent read operations be executed concurrently, while operations with side effects, shared state, or order sensitivity be executed sequentially. Regardless of the execution method, there are rules that must be followed:

  • Return a result for every call. For calls decided not to be executed, still send a result containing is_error: true and a brief explanation such as "Not executed because a preceding call failed".
  • In Anthropic, place all results in a single user message. The documentation warns that splitting results across multiple messages causes the model to "learn" to avoid parallel calls, diminishing parallel usage.
  • Parallel calling can be disabled. Anthropic uses disable_parallel_tool_use: true inside tool_choice (not a top-level parameter) to ensure at most one tool is called per response under auto. OpenAI uses parallel_tool_calls: false to allow only zero or one call.

Gemini documentation distinguishes between independent parallel calls and compositional calls where an earlier result serves as the input to a subsequent call. If dependencies exist, the application must enforce the order.

tool_choice and forced calling

tool_choice determines whether the model uses a tool and which tool it uses.

Intent OpenAI Anthropic Gemini
Model decides auto (default) auto (default when tools exist) auto (default)
Must use tool required or specific function any or tool any
Prohibit use none none none
Restrict to allowlist allowed_tools — allowed_tools

Support for forced calling varies by model. According to Anthropic documentation, Claude Opus 5.5, Sonnet 5.5, Fable 5.1, and Mythos 5.1 reject any and tool with a 400 error; therefore, use auto with strict tools, or use structured output if a predetermined JSON response is required. Even on supported models, forcing a call omits the thought process and explanatory text preceding the tool call. In Anthropic, changing tool_choice invalidates cached message portions, whereas OpenAI explains that allowed_tools, which restricts the call scope while leaving the tool list intact, helps preserve cache savings.

Reasoning models and tool loops

Reasoning models return reasoning information alongside tool calls. This information must be sent back in the subsequent request exactly as received.

  • OpenAI: Send back the reasoning item received with the tool call together with the function result. Use previous_response_id or pass the previous output items directly into the input. When operating statelessly, pass the encrypted_content of the reasoning item.
  • Anthropic: When returning tool results, send back the thinking and redacted_thinking (thought blocks partially obscured for safety) blocks from the latest assistant message without modification, down to the signature. Editing, reordering, or omitting these blocks causes a 400 error, and blocks with empty content are no exception.
  • Gemini: If managing history statelessly, send back the model-generated steps without modification, as the steps contain the required signatures. When using the SDK, this is handled automatically.

Problems usually arise in middleware that filters out blocks or re-serializes history in an attempt to save tokens. The principle is: "history is append-only".

The server holds execution permissions

Strict mode guarantees only the shape of the arguments. Whether it is permissible to execute with those arguments is a separate question. The OWASP Top 10 for LLM Applications 2025 identifies the risk of model output leading to harmful actions due to excessive functionality, permissions, or autonomy as Excessive Agency (LLM06), and the risk of passing model output to other systems without sufficient validation and sanitization as Improper Output Handling (LLM05).

  1. User and organization identifiers are injected by the server from the session. Do not let the model choose customer IDs as arguments.
  2. Re-verify permissions and business rules (state, limits, ownership) immediately before execution. Gemini documentation also recommends validating function calls before executing them.
  3. Separate read tools from write tools, and allow write tools only to the minimum extent necessary.
  4. Route irreversible operations through human approval. Store the pending approval state, and return the approval result as a tool result to continue the conversation.
  5. Do not trust external text mixed into tool results (Chapter 1 trust boundaries).

Encountering unsupported constraints

Different engines handle the same schema differently. The divergence is greatest when encountering unsupported features.

Engine Where schema is placed Features outside supported scope
Anthropic output_config.format (type: "json_schema") 400 error
llama.cpp json_schema field of llama-server (converted to GBNF grammar) Silently skipped
vLLM structured_outputs.json XGrammar backend rejects multipleOf on integer and number
Ollama format in the Chat API (json or JSON schema) Ollama Cloud does not support structured output at all

Engines that do not throw errors are more dangerous. llama.cpp converts only a subset of JSON Schema into GBNF and silently discards the rest without warning. Because the request succeeds and the response is valid JSON, noticing the missing constraint is difficult.

Suppose an in-house settlement team applied multipleOf: 10 to an amount field. Thanks to vLLM using the XGrammar backend rejecting the request at the validation stage, the team fixed the schema that day. If the llama.cpp converter did not support this constraint, values such as KRW 1,235 arrived in responses without any warning. Configurations that ran properly on local Ollama became unusable the moment they were migrated to Ollama Cloud.

When adopting a new engine, verify its behavior first using a schema intentionally containing constraints outside its supported scope. Even for constraints accepted by the engine, inspect them again in the application's schema validation. Changes have also occurred on the hosted API side. As of 2026-11-01, Anthropic structured output is a generally available feature used without beta headers. The legacy output_format parameter has been moved to output_config.format.

Programmatic tool calling: leaving repetition to code

In a standard loop, the model receives results one by one and decides the next call. If aggregating and summing inventory across 50 stores, all 50 intermediate results accumulate in the conversation. In programmatic tool calling, the model writes code that calls tools like functions, leaving repetition and summation to that code.

Item Anthropic OpenAI
Code written by model Python JavaScript
Execution environment Code execution container Isolated V8 runtime created fresh for each program

In Anthropic, look at the version first. What the code execution tool code_execution_20250825 supports is Bash commands and file operations. Because REPL state persistence and programmatic calling were introduced in code_execution_20260120, specify this version or a later version (there is also code_execution_20260521). Configurations pinned to legacy versions cannot use this feature. The way state is handled also differs. OpenAI runs generated programs in a new runtime every time, so a subsequent program cannot inherit variables from a preceding program.

The heaviest decision is strict mode. In Anthropic, tools with strict: true cannot be included in programmatic calling. To call an inventory lookup tool from code, strict must be omitted, meaning the shape of arguments is not guaranteed at the generation stage. This is why the server re-validates arguments against the schema immediately before execution. Separate tools by keeping irreversible tools like refunds as standard calls with strict enabled, while passing only lookup tools to code. Even when called by code, application tools are executed on our server, so permission checks and budget rules apply unchanged.

Check the executing entity first

Even if tools appear similar in a tool list, the entity that actually runs the tool differs. Once the executing entity is determined, who handles isolation, time limits, and audit logging is also established.

Tool Executing entity Conditions to know
OpenAI File Search Hosted tool managed by OpenAI Does not require implementing separate execution handling code
Anthropic code execution Anthropic's sandbox container Runs Python and Bash
Gemini code execution Gemini built-in tool Runs Python only, execution environment capped at 30 seconds
Anthropic computer use Application (client tool) You prepare the environment to handle screen and input yourself

A tool often confused because of its name is computer use. Anthropic does not spin up a desktop on your behalf. Because the clicks and keystrokes requested by the model are executed in an environment we prepare, run them in an isolated virtual machine and apply the execution permission principles discussed earlier without modification.

Hosted tools eliminate implementation overhead but adhere strictly to the provider's limits. Suppose an analytics team delegated merging dozens of monthly sales files to Gemini code execution. If processing took longer than 30 seconds, there was no way to finish in that environment, requiring the task to be split into smaller pieces or moved to a self-hosted execution environment.

Look at feature stages separately from model stages. While Gemini 3.6 Flash was generally released on 2026-07-21, using structured output together with built-in tools is available only in the Gemini 3 family and remains in preview. Do not deploy that combination to production simply because the model itself is generally available.

Going deeper

When tools multiply

As systems are attached one by one, tools increase to dozens or hundreds. Cost and accuracy degrade together. Tool definitions are billed as input tokens (explicitly stated by both OpenAI and Anthropic), and Anthropic also adds a separate tool-use system prompt when tools are used. When there are many similar tools, the model also chooses the wrong tool more often.

Strategy Method Trade-off
Consolidation Group related operations with an action parameter The description of a single tool becomes longer
Step-by-step subset Include only the tools needed for each conversation step If the tool list changes, the cache is broken
Allowlist Keep the list as is and restrict only the callable scope (allowed_tools) Definition tokens are still consumed
Tool search Defer loading definitions (defer_loading) so the model searches and loads only what is needed A search step is added, and supported models are limited

Anthropic supports a tool search tool that keeps up to 10,000 tools marked with defer_loading: true per request and searches and loads them when needed, while OpenAI supports tool_search in the Responses API (introduced on March 5, 2026). OpenAI tool search works only on gpt-5.4 and later models. In Anthropic, changing tool definitions invalidates the entire cache, so rebuilding the list at each step can offset cost savings. Whichever strategy is used, measure tool selection accuracy with an evaluation set.

Structured results during streaming

Structured outputs and tool arguments can also be received via streaming. While they can be displayed quickly on screen, execution must wait until the end.

  • Anthropic sends tool input as partial JSON strings in input_json_delta. You collect the fragments and parse them at content_block_stop. If you want to receive large parameter values in smaller increments, granular streaming is available by enabling eager_input_streaming per tool.
  • OpenAI sends fragments with response.function_call_arguments.delta and completed arguments with .done.
  • Gemini explains that streamed fragments are partial JSON strings that form the final object when concatenated.

The rule is simple. Render previews with partial results, but perform tool execution and storage only after the completed arguments have passed three-stage verification. If a stream is interrupted midway, tool-use blocks cannot be partially recovered, as Anthropic documentation states, so do not concatenate the received fragments and execute them; make a new request instead (Chapter 4).

At work

Sandgrain Accounting: Redesigning the receipt extraction schema

Sandgrain Accounting, a bookkeeping app for self-employed individuals, extracted expense items from the OCR text of receipt photos. After receiving JSON via instructions resulted in dozens of parsing failures and type errors a day, developer Assistant Manager Seong redesigned the schema.

The first draft made the total an optional field and omitted it if unreadable. However, in OpenAI strict mode, all fields had to be required, and above all, it was necessary to distinguish between "not printed" and "unreadable due to blurriness." This was because the former could be substituted with the sum of items, whereas the latter required requesting the user to retake the photo. Therefore, total_krw was received as a nullable integer, and the status was received as a total_status enum. Amounts were fixed as integers in KRW units, dates were fixed in ISO format, and the original date string was received separately as raw_date. The server attached the ledger entry ID and registration timestamp.

When testing the same feature with Claude, another issue arose. The minimum: 0 constraint, requiring that the amount be greater than or equal to 0, was not supported in Anthropic structured outputs. The team moved the constraint into the field description and rechecked it in the application after receiving the response. For semantic verification, they added a rule directing the entry to a user confirmation screen if the difference between the sum of items and the total exceeded KRW 10.

The proposal to add more examples to JSON mode failed to prevent schema mismatches, and the proposal to insert 0 when unreadable was rejected because it could not be distinguished from actual KRW 0 receipts. One month after deployment, parsing failures disappeared, and 1.2% of the total fell into the confirmation screen due to total mismatches and were corrected directly by users.

Fingertip Repair Center: Drawing the line for a repair reception agent

Home appliance repair company Fingertip Repair Center built an agent that received repair requests through chat. There were three tools: warranty lookup (lookup_warranty), available visit time slot lookup (find_slots), and ticket creation (create_repair_ticket). During pilot operation, three incidents occurred. When a user stated another person's product serial number, that warranty history was retrieved; the model requested time slot lookup and ticket creation simultaneously in a single response, creating a ticket before checking available slots; and for a single ambiguous request, the loop ran for nine turns, racking up costs.

Lead Engineer Senior Manager Do made structural changes before modifying prompts.

  1. The customer ID was removed from the tool arguments. The server injected it from the login session and verified whether the serial number belonged to that customer's registered product before execution.
  2. create_repair_ticket was required to take slot_hold_id returned by find_slots as a required argument. Holds had an expiration time, so if a hold was missing or expired, the server did not execute it and returned a needs_info result instructing to query again. Even when parallel requests arrived, the server enforced dependencies so that the order did not get tangled.
  3. Parallel execution was allowed for the two read tools, and if a write tool was mixed into the same response, the reads were executed first before validating the write. For unexecuted calls, an error result containing the reason was returned.
  4. The loop budget was set to six steps and 30 seconds, and if exceeded, it was escalated to a customer representative along with a conversation summary.

The proposal to merely include an instruction such as "Do not look up another person's product" had no safeguard if the model failed to follow it, so it was decided to use it only in conjunction with server-side checks. The proposal to lock ticket creation to forced calling was rejected because the intended model did not support it and it eliminated the opportunity to ask questions when information was insufficient. Afterwards, reception errors disappeared, and the representative escalation rate remained at 7%.

Common mistakes

  • JSON mode also guarantees the schema. JSON mode guarantees only syntax. Fields and types are guaranteed by schema-based structured outputs.
  • If it passes the schema, the content is also correct. Results that have the correct format but incorrect values are possible. Relationships such as totals, dates, and statuses are verified in semantic verification.
  • Optional fields can simply be omitted from required. In OpenAI strict mode, all fields must be placed in required and represented as nullable types.
  • Providers enforce all constraints written in the schema. Supported scopes differ. Anthropic does not accept numeric or string length constraints, so they must be verified in the application.
  • Results for unexecuted calls can be omitted. Every call must have a result. If a call was not executed, communicate that fact as an error result.
  • Since strict is enabled, it is safe to execute with those arguments. strict guarantees only the shape. Permissions, ownership, and business rules are inspected by the server immediately before execution.
  • Parallel call results can be sent across separate messages. In Anthropic, they must be gathered into a single user message; sending them separately reduces parallel calls.

Summary at a glance

Topic What to remember
Scope of guarantee Instructions < JSON mode (syntax) < Structured outputs (schema). Value accuracy is outside the guarantee
strict rules additionalProperties: false. OpenAI requires all fields in required + null. Anthropic does not support numeric/length constraints or recursion
Schema design Distinguish the meaning of absence, fix units, let the server handle values known to the server, version field
Verification Status → Syntax → Schema → Semantics
Tool definitions and loops Descriptions are everything. Loops are state machines + step, time, and token budgets
Returning results Paired by call ID. A result for every call. Anthropic requires a single message, results first
Forced calling and reasoning items Forced calling has limited model support (alternatives: auto + strict, structured outputs). Return reasoning items exactly as received
Permissions Identifiers are injected by the server and rechecked immediately before execution

Check the official docs

Self-check

2-1. List four things to determine when deriving a schema from business concepts, and provide an example showing how to distinguish and represent 'Value unreadable' and 'Value originally absent'.

2-2. State two differences between the strict schema rules of OpenAI and Anthropic, and write what a service using both providers should be mindful of when managing schemas.

2-3. Define syntax validation, schema validation, and semantic validation each in one sentence, and state what must be checked before these three steps.

2-4. Define the fields of a common envelope format to use when returning tool results, and explain the reason for stating what to try next in a failure result.

2-5. List the states required when modeling a tool-calling loop as a state machine, and describe three budgets to place on the loop along with the handling when a budget is exceeded.

2-6. Give three examples of values that the server must inject directly rather than letting the model choose them as arguments, and explain the reasons by connecting them to risk items in the OWASP Top 10 for LLM Applications.

2-7. Design an internal meeting room reservation assistant. Organize into a table the tool list, the details that must be included in each tool's description, the values that the server must inject directly, and the pre-execution check items.

Hands-on tasks

Exercise

Schema and three-stage validator (45 minutes)

  1. Choose one among receipts, purchase orders, or inquiry emails, and derive a schema from business concepts. Include an enum distinguishing the meanings of absence, units, values to be assigned by the server, and schema_version.
  2. Adapt it to the strict rules of the provider being used, and move unsupported constraints into descriptions and application checks.
  3. Create a function that validates in the order of response status → syntax → schema → semantics, and route failures at each stage to different paths (retry, clarification question, hold).
  4. Run 20 inputs. Among them, create 5 inputs with missing values or mutually contradictory values.

Done when: A table shows at which stage all 20 cases passed or failed, and the 5 contradictory inputs were filtered out in semantic validation.

Exercise

State-machine tool loop with budgets (60 minutes)

  1. Define two query tools and one mutation tool, and enable strict mode. The server injects the user ID.
  2. Ensure that the mutation tool executes only when it has an identifier received from query results, and check permissions and state immediately before execution.
  3. Place step-count and time budgets on the loop, and if exceeded, hand off to a human along with partial results.
  4. Inject a fault so that the mutation tool fails once every three times, and return failures as error results in the common envelope format. Send results even for unexecuted calls.
  5. Run ten conversations and check the logs.

Done when: Every tool call has a matching result, calls caught by checks were not executed, and conversations exceeding budget were handed off to a human.