Getting schema-compliant JSON from Claude for invoice extraction

CCAR-F Prompt Engineering & Structured Output Medium Question 18 of 59

You are building an automated invoice extraction pipeline using the Claude API to extract supplier metadata, line items, and totals from unstructured PDF text. Your downstream billing system requires strictly formatted JSON conforming to a defined schema. In testing with natural language prompts, Claude frequently includes conversational preambles and occasionally generates syntax errors when formatting nested arrays.

How should you configure the API request to guarantee schema-compliant structured data without conversational text?

Show answer and explanation

CDefine an extraction tool with the JSON schema in its parameters and configure tool_choice to force tool use.

Defining an extraction tool with a JSON schema and configuring tool_choice to force tool use is the documented, reliable approach for guaranteed schema compliance. When tool use is forced, the API eliminates conversational preambles and enforces strict parameter adherence, preventing syntax errors. Prefilling assistant turns with opening braces is a fragile technique that is rejected on modern Claude models. Instructing the model to emit raw JSON in the system prompt cannot eliminate occasional syntax errors or markdown wrapping. Markdown code fences still produce unvalidated strings that downstream parsers must manually validate.

Source: platform.claude.com/docs/en/agents-and-tools/tool-use/defin…

Anonymous, no account needed. Your tally stays in this browser.

Next question Start 5 timed questions Browse all 59 original CCAR-F practice questions