---
title: "Structured JSON vs Markdown vs Tool Calls: Evaluating Extraction Reliability"
date: "2026-11-27T08:14:00+07:00"
description: "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."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/structured-json-vs-markdown-vs-tool-calls.jpg"
alt: "Three conveyor belts delivering differently packaged boxes to a sorting machine"
tags: ['google-adk', 'structured-output', 'function-calling', 'evaluation', 'json']
---

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:

```python
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:

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

```python
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:

```python
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

| Dimension | Response schema | Markdown JSON | Tool calling |
|---|---|---|---|
| JSON syntax errors | Rare (constrained decoding) | Common: trailing commas, prose, nested fences | Rare (framework-validated) |
| Semantic violations (wrong enum, out-of-range) | Possible if not enforced | Frequent — nothing checks | Usually caught by types/validators |
| Requires special model support | Yes | No | Yes (function-calling support) |
| Extra prompt tokens | Lowest — schema isn't repeated in prose | Highest — schema written out, plus examples | Moderate — tool declarations per request |
| Works for *chained* extraction (model must call several times) | No — one shot | Yes | Yes |
| Model stops midway / partial output | Retry at API level | You detect and repair | Model re-invoked automatically |
| Inspection & debugging | Response object | Readable text | Events in the session |
| Model-agnostic portability | Low (vendor-specific) | High | Medium (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:

```python
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

| Situation | Use |
|---|---|
| Single object per turn, model supports schema | **Response schema** + field validation |
| Extraction must trigger/interleave with actions | **Tool calling** |
| Multi-entity or variable-shape extraction | **Tool calling** (or schema with arrays) |
| Heterogeneous/unknown model behind a router | **Markdown JSON**, minimal schema text |
| Model outputs depend on tool results | **Tool calling** — schema can't span turns |
| You need a human-readable audit trail | Either — 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.

```python
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

- [Enforcing structured outputs with Pydantic response_schema](/blog/adk-pydantic-response-schema-structured-outputs)
- [Defining function tools: type hints, docstrings, and validation](/blog/adk-function-tools-type-hints-docstrings)
- [System instruction optimization for tool calling](/blog/system-instruction-meta-prompting-deterministic-tool-calling)
- [Customizing agent output serialization: markdown to raw JSON](/blog/adk-output-serialization-markdown-json)
