Skip to content
Blog

Structured JSON vs Markdown vs Tool Calls: Evaluating Extraction Reliability

A head-to-head comparison of three ways to get structured data out of a model — response schema, markdown-embedded JSON, and native function calling — with the failure modes of each and an eval harness to measure extraction accuracy.

Published on • November 27, 2026

AI Assistant

Every agent eventually needs to turn free text into data: an order, a classification, a plan, a row in a table. There are three mainstream ways to do it, and teams routinely pick one by habit — markdown JSON because it “always works”, schema because it’s official, tool calls because the SDK does it for you.

They fail differently. This comparison lays out what each approach actually guarantees, how each breaks, and gives you a small eval harness so the choice is a measurement rather than an opinion.

The three contenders

1. Response schema (constrained structured output)

The model is required to emit JSON matching a schema — in the Gen AI SDK, Pydantic models or raw JSON Schema:

from pydantic import BaseModel
from google.genai import types

class ExtractedTicket(BaseModel):
    intent: str
    order_id: str | None
    urgency: int          # 1-5
    summary: str

response = client.models.generate_content(
    model='gemini-3.8-flash',
    contents=customer_message,
    config=types.GenerateContentConfig(
        response_mime_type='application/json',
        response_schema=ExtractedTicket,
    ),
)
ticket = response.parsed          # an ExtractedTicket instance, or None on failure

The API constrains decoding to grammar-valid output, so JSON syntax errors essentially disappear. A known sharp edge, straight from the SDK docs: do not also paste the schema or example JSON into the prompt — duplicating it can lower output quality.

2. Markdown-embedded JSON

You ask for a JSON object inside the response, parse the fenced block:

Reply with a JSON object: {"intent": "...", "order_id": "...", "urgency": 1, "summary": "..."}
Wrap it in ```json fences.
import json, re

def extract_block(text: str) -> dict:
    m = re.search(r'```json\s*(\{.*?\})\s*```', text, re.S)
    return json.loads(m.group(1) if m else text[text.index('{'):text.rindex('}') + 1])

Universal, model-agnostic, easy to inspect — and every bit of validation is your problem.

3. Native function/tool calling

Declare the shape as a tool and let the framework constrain the call:

def create_ticket(intent: str, order_id: str | None, urgency: int, summary: str) -> dict:
    """Create a support ticket from an extracted request.

    Args:
        intent (str): One of 'refund', 'shipping', 'defect', 'question'.
        order_id (str, optional): Related order ID if the user mentioned one.
        urgency (int): 1 (low) to 5 (urgent).
        summary (str): One-sentence customer summary.
    """
    ...

In ADK this becomes a FunctionTool whose schema travels with the request; the model emits a FunctionCall and the framework parses arguments into typed values (including nested Pydantic models).

Failure modes, side by side

DimensionResponse schemaMarkdown JSONTool calling
JSON syntax errorsRare (constrained decoding)Common: trailing commas, prose, nested fencesRare (framework-validated)
Semantic violations (wrong enum, out-of-range)Possible if not enforcedFrequent — nothing checksUsually caught by types/validators
Requires special model supportYesNoYes (function-calling support)
Extra prompt tokensLowest — schema isn’t repeated in proseHighest — schema written out, plus examplesModerate — tool declarations per request
Works for chained extraction (model must call several times)No — one shotYesYes
Model stops midway / partial outputRetry at API levelYou detect and repairModel re-invoked automatically
Inspection & debuggingResponse objectReadable textEvents in the session
Model-agnostic portabilityLow (vendor-specific)HighMedium (spec-based)

Two subtleties worth calling out:

  • Syntax vs semantics. Constrained decoding guarantees well-formed JSON, not correct JSON — "urgency": 9 parses fine. Field-level validation (Pydantic constraints, enums, refusals) is a separate layer you must add.
  • Any-of vs all-of. Tool calling naturally supports the model choosing which tool and how many times; a response schema gives you exactly one object per request. Multi-entity extraction fits tools better.

Building the eval

Extraction reliability is a measurable property. Label 100–300 inputs with the expected object and score:

def score(pred: dict, gold: dict) -> dict:
    return {
        'parsed':        pred is not None,
        'field_exact':   sum(pred.get(k) == v for k, v in gold.items()) / len(gold),
        'schema_valid':  schema_validator(pred) if pred else False,
    }

Report four numbers per approach:

  1. Parse rate — how often you got an object at all.
  2. Field-level accuracy — partial credit; a wrong urgency is less catastrophic than a wrong intent.
  3. Strict accuracy — all fields correct. This is the number that matters downstream.
  4. Tokens and latency — schema approaches are usually cheapest; markdown-with-examples is the most expensive.

Run the same labelled set through all three with identical model, temperature (keep it low), and content. Include adversarial inputs: mixed-language text, numbers formatted oddly, missing fields, inputs that contain brace characters.

Typical outcome on a well-supported structured-output model: response schema wins on parse rate and cost; tool calling wins when extraction must interleave with action (“extract then immediately act”); markdown wins only when you must run across heterogeneous models — and even then, constrained JSON modes are increasingly portable.

Choosing: a decision matrix

SituationUse
Single object per turn, model supports schemaResponse schema + field validation
Extraction must trigger/interleave with actionsTool calling
Multi-entity or variable-shape extractionTool calling (or schema with arrays)
Heterogeneous/unknown model behind a routerMarkdown JSON, minimal schema text
Model outputs depend on tool resultsTool calling — schema can’t span turns
You need a human-readable audit trailEither — events and responses are inspectable

And the hybrid that usually wins in production: schema for the final contract, tools for the process. Let the agent work with tools, then force the handoff out of the agent into a validated Pydantic model — a final response_schema call that normalises whatever the conversation produced.

final = client.models.generate_content(
    model='gemini-3.8-flash',
    contents=transcript_summary,
    config=types.GenerateContentConfig(
        response_mime_type='application/json',
        response_schema=ExtractedTicket,
        temperature=0.0,
    ),
).parsed
assert final is not None, 'extraction failed schema validation'

Takeaways

  • All three approaches differ mainly in who validates: constrained decoding, your regex and json.loads, or the framework.
  • Parse-rate success is not correctness — score field-level and strict accuracy separately.
  • Don’t duplicate the schema in the prompt when using response_schema; it measurably hurts.
  • Tool calling is the right shape when extraction is interleaved with action or spans multiple turns.
  • Measure tokens and latency alongside accuracy; markdown-with-examples is the most expensive habit.
  • In production, combine: tools for the process, a schema-validated final contract for the handoff.

Further reading