Prompt and Context Engineering
Structured Output and Defensive Parsing
Exam objective: Applying structured outputs with strict schema validation, response validation, and defensive parsing of free-text fallbacks to protect downstream code from malformed or unexpected model output.
What the exam tests
You get code that consumes Claude's output and breaks: invalid JSON, a missing field, a wrong type, an unexpected value, a truncated object, or a rejected schema. Pick the mechanism that actually guarantees the property, then add the checks that the guarantee does not cover.
Key rules
- Two features, two targets. JSON outputs (
output_config.format, typejson_schema) constrain the response text. Strict tool use (strict: trueon a tool) constrains tool names and inputs. Both can be used in one request. - Prompting is not a guarantee. Format instructions and examples improve consistency. When code needs a fixed shape, use structured outputs.
- Supported schema subset. Objects need
additionalProperties: false. Recursive schemas,oneOf,not, numeric limits and string-length limits are not supported and return a 400. SDK helpers can strip unsupported constraints and move them into descriptions; a helper that validates responses still enforces them in your code. - Check how generation ended.
refusalarrives as HTTP 200 and may not match the schema.max_tokensmay leave the output incomplete: retry with a higher limit. - Compare enums case-insensitively. Capitalization of
enumandconststrings is not guaranteed, in either feature. - Complexity limits apply across the request: 20 strict tools, 24 optional parameters, 16 union-typed parameters, plus internal grammar-size limits. First remedy: make only critical tools strict, then reduce optional parameters, flatten, or split requests.
- Forced tool use (
tool_choiceanyortool) returns a 400 on some current models, including Claude Opus 5.5 and Sonnet 5.5. Useautowith strict tools, or JSON outputs. - Agent SDK: pass
outputFormat/output_formatand readstructured_outputfrom the result message. Asuccesssubtype is not enough:is_errormust be false and the output present.error_max_structured_output_retriesmeans no valid output remained.
if response.stop_reason in ("refusal", "max_tokens"):
return handle_incomplete(response) # do not parse as a result
text = next(b.text for b in response.content if b.type == "text")
data = json.loads(text)
if not 0 <= data["score"] <= 100: # rule the API schema cannot express
raise ValueError(f"score out of range: {data['score']}")
Defensive parsing of free text
When structured outputs are not available:
- Read only
textblocks, and treat amax_tokensstop as failure. - If the reply may contain working or a draft, parse complete JSON values from each
{or[and keep the last one. Slicing from the first brace to the last brace can swallow both draft and answer. - Check for the expected fields and retry a bounded number of times.
With fine-grained tool streaming (eager_input_streaming), tool input is not validated by the API. If it does not parse, do not run the tool: return a tool_result with is_error: true that wraps the raw string, for example under an INVALID_JSON key.
Traps
- Assuming a 200 response means schema-valid output.
- "Repairing" truncated JSON: it parses, but data is silently gone.
- Using
output_config.formatto fix bad tool arguments (that is strict mode's job). - Using prefill to force JSON: it is incompatible with JSON outputs, and Claude 4.6 and later reject it.
- Enabling citations together with
output_config.format(400). - Expecting an open-ended map: only listed keys can be returned. Use an array of
key/valueobjects. - Relying on property order with optional fields: required properties are emitted first.
- Putting PHI in property names,
enum,constorpattern.
Decide quickly
| Situation | Choice | Why |
|---|---|---|
| Response must be a fixed JSON object | output_config.format | Constrained decoding on the response |
| Tool receives wrong types or misses fields | strict: true | Tool inputs follow the schema |
| Numeric range or business rule | Validate in code | Not expressible in the supported subset |
stop_reason: "max_tokens" | Fail, retry with more tokens | Output may be incomplete |
stop_reason: "refusal" | Separate branch | Refusal overrides the schema |
| "Schema is too complex" | Fewer strict tools and optional fields | Shrinks the compiled grammar |
| Keys unknown in advance | Array of key/value items | Extra keys are not allowed |
| Data may be absent (agent task) | Make the field optional | Required fields it cannot fill cause failures |