CCDV-F Prep unofficial
← All skills

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, type json_schema) constrain the response text. Strict tool use (strict: true on 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. refusal arrives as HTTP 200 and may not match the schema. max_tokens may leave the output incomplete: retry with a higher limit.
  • Compare enums case-insensitively. Capitalization of enum and const strings 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_choice any or tool) returns a 400 on some current models, including Claude Opus 5.5 and Sonnet 5.5. Use auto with strict tools, or JSON outputs.
  • Agent SDK: pass outputFormat / output_format and read structured_output from the result message. A success subtype is not enough: is_error must be false and the output present. error_max_structured_output_retries means 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 text blocks, and treat a max_tokens stop 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.format to 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/value objects.
  • Relying on property order with optional fields: required properties are emitted first.
  • Putting PHI in property names, enum, const or pattern.

Decide quickly

SituationChoiceWhy
Response must be a fixed JSON objectoutput_config.formatConstrained decoding on the response
Tool receives wrong types or misses fieldsstrict: trueTool inputs follow the schema
Numeric range or business ruleValidate in codeNot expressible in the supported subset
stop_reason: "max_tokens"Fail, retry with more tokensOutput may be incomplete
stop_reason: "refusal"Separate branchRefusal overrides the schema
"Schema is too complex"Fewer strict tools and optional fieldsShrinks the compiled grammar
Keys unknown in advanceArray of key/value itemsExtra keys are not allowed
Data may be absent (agent task)Make the field optionalRequired fields it cannot fill cause failures

Sources