Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Appendix: YAML Serializer Variance and Token Economics

Problem Statement

The Format as Architecture handbook and its companion Token Economics of Prompt Delivery treat format as the sole variable in prompt token cost: “YAML Literal is the most expensive format,” “Standard YAML is ~N% cheaper than JSON.” Session measurements revealed this framing is incomplete.

Two tools — PyYAML and yq — producing valid, semantically equivalent YAML from the same JSON source yield token counts differing by 100+ tokens, and the relative ranking of YAML Literal vs Pretty JSON flips depending on the tool. The token cost of a prompt format is a function of three variables:

token_cost=f(format, serializer, tokenizer)\text{token\_cost} = f(\text{format},\ \text{serializer},\ \text{tokenizer})

This appendix verifies the finding across 5 prompt files, isolates each serializer variable independently, confirms semantic fidelity, and derives a concrete stack recommendation. For a concise summary see A-26017.

Setup

File                                          Size (bytes)
-----------------------------------------------------------
handbook_consultant.json                             5,434
ai_brainstorming_colleague.json                      6,079
devops_consultant.json                              12,199
ai_systems_consultant_hybrid.json                   12,944
local_ai_systems_consultant.json                    13,301

A. Baseline: Token Counts Across All Prompt Files

We measure all seven variants on every production prompt file, then compute median deltas relative to Minified JSON. Using the median across 5 files makes the finding robust — not an artifact of one prompt’s structure.

Loading...
Loading...
Loading...

Visual summary of median Δ% values. Minified JSON is the baseline (0%) and omitted. Striped bars distinguish yq variants from PyYAML variants within each format family.

<Figure size 1300x500 with 1 Axes>

B. Isolation Experiments

Each experiment isolates one serializer variable on the largest prompt file to quantify its independent contribution.

Representative file: local_ai_systems_consultant.json (13,301 bytes)

B1. Line wrapping — width=80 vs width=∞

Minified JSON:			  2676 tokens  (baseline)
Standard YAML width=80:		  2985 tokens  (241 lines)  [+11.5% vs min JSON]
Standard YAML width=∞:		  2858 tokens  (170 lines)  [+6.8% vs min JSON]
Pretty JSON:			  3123 tokens  [+16.7% vs min JSON]

Wrapping overhead:		  +127 tokens  (4.4%)
YAML w=∞ vs Pretty JSON:	  -265 tokens  (cheaper)

B2. Quote style — single quotes vs double quotes

PyYAML’s default style leaves most strings unquoted and single-quotes values that look like dates ('2026-01-07') or contain YAML-special characters. Forcing default_style='"' double-quotes every scalar key and value. This experiment measures the token cost of that difference in isolation (both use w=∞ to exclude line-wrapping effects).

Default style (w=∞):         2858 tokens
Double-quote style (w=∞):    3069 tokens
Delta:                       +211 tokens

Date quoting — default:
    birth: '2025-11-28'
    last_modified: '2026-03-02'
Date quoting — double-quote:
    "birth": "2025-11-28"
    "last_modified": "2026-03-02"

B3. Literal block terminator and boolean coercion

PyYAML’s literal representer applies | (clip — keep one trailing newline) to strings only; booleans and numbers stay inline. yq’s ..style="literal" applies |- (strip — no trailing newline) to all scalars, including booleans and numbers. This creates two compounding cost sources:

  1. Every string scalar pays for the extra - character in the indicator (|- vs |).

  2. Non-string scalars (booleans, numbers) are moved from an inline value to a separate indented line, adding newline and indentation tokens.

The cell below decomposes the total delta by progressively transforming the PyYAML output toward yq’s: first changing all | indicators to |- (Source 1), then attributing the remainder to structural differences (Source 2). The verification line confirms the two sources sum to the actual delta exactly.

Pretty JSON:             3123 tokens  (reference)
PyYAML literal (`|`):    3058 tokens  [-65 vs Pretty JSON]  ← cheaper
yq literal (`|-`):       3183 tokens  [+60 vs Pretty JSON]  ← more expensive

PyYAML vs yq literal delta: -125 tokens  (negative = PyYAML cheaper)

Delta breakdown (yq literal − PyYAML literal = +125 tokens):

  Source 1 — `|-` vs `|` indicator on 54 string scalars:
    Measured on actual document (all `|` → `|-`): +54 tokens
    Per-indicator cost: +1.0 tokens

  Source 2 — structural differences beyond indicators:
    yq `|-` blocks (total): 59  (PyYAML `|`: 54)
    Non-string scalars coerced to `|-`: 4  ['true', 'true', 'true', 'true']
    Extra lines in yq: 5
    Measured cost (actual yq − step-1 document): +71 tokens

  Verification: +54 + +71 = +125 tokens  (actual: +125)

B4. Structural diff

Visual confirmation of the serializer differences measured in B1–B3. The standard YAML diff shows PyYAML’s line-wrapping (B1) and quote-style differences (B2). The literal YAML diff shows the | vs |- indicator divergence (B3) and boolean coercion on the last lines.

=== Standard YAML: PyYAML vs yq ===
Line counts: PyYAML=241, yq=165
  [3] PyYAML:	"  birth: '2025-11-28'"
       yq:	'  birth: "2025-11-28"'
  [4] PyYAML:	"  last_modified: '2026-03-02'"
       yq:	'  last_modified: "2026-03-02"'
  [5] PyYAML:	'  purpose: Peer review and critique of architectural and software engineering concepts'
       yq:	'  purpose: Peer review and critique of architectural and software engineering concepts for industrial applications of AI powered systems, featuring internal WRC calculation and self-critique logic.'
  [6] PyYAML:	'    for industrial applications of AI powered systems, featuring internal WRC calculation'
       yq:	'  owner: lefthand67'
  [7] PyYAML:	'    and self-critique logic.'
       yq:	'input_protocol:'
  [8] PyYAML:	'  owner: lefthand67'
       yq:	'  expected_input: Architectural and methodological questions on AI systems.'
  [9] PyYAML:	'input_protocol:'
       yq:	'  input_check:'
  [10] PyYAML:	'  expected_input: Architectural and methodological questions on AI systems.'
       yq:	'    require_USER_INPUT_field: true'
  ... (stopped at 8)

=== YAML Literal: PyYAML vs yq ===
Line counts: PyYAML=275, yq=280
  [1] PyYAML:	'  id: |'
       yq:	'  id: |-'
  [3] PyYAML:	'  version: |'
       yq:	'  version: |-'
  [5] PyYAML:	'  birth: |'
       yq:	'  birth: |-'
  [7] PyYAML:	'  last_modified: |'
       yq:	'  last_modified: |-'
  [9] PyYAML:	'  purpose: |'
       yq:	'  purpose: |-'
  [11] PyYAML:	'  owner: |'
       yq:	'  owner: |-'
  [14] PyYAML:	'  expected_input: |'
       yq:	'  expected_input: |-'
  [17] PyYAML:	'    require_USER_INPUT_field: true'
       yq:	'    require_USER_INPUT_field: |-'
  ... (stopped at 8)

C. Semantic Fidelity

A serializer that changes values is disqualified for prompt delivery regardless of token efficiency. We test round-trip fidelity: JSON → YAML (serializer) → JSON and assert the result equals the original. Any coercion (e.g., string "true" → boolean true, or date strings losing their type) would surface as a failure here.

The first cell tests all 5 prompt files with both PyYAML (w=∞) and yq. The second cell tests edge-case scalars that are known to trigger type coercion in YAML parsers: boolean strings ("true", "false"), date-like strings, null, and numeric values.

File                                            PyYAML       yq
---------------------------------------------------------------
handbook_consultant.json                             ✓        ✓
ai_brainstorming_colleague.json                      ✓        ✓
devops_consultant.json                               ✓        ✓
ai_systems_consultant_hybrid.json                    ✓        ✓
local_ai_systems_consultant.json                     ✓        ✓
Scalar type       PyYAML w=∞       yq
-------------------------------------
booleans                   ✓        ✓
numbers                    ✓        ✓
null                       ✓        ✓
date string                ✓        ✓
bool string                ✓        ✓
yaml11 strings             ✓        ✓

D. Ranking Stability Across Tokenizers

The serializer variance documented in A. Baseline: Token Counts Across All Prompt Files and B. Isolation Experiments was measured with cl100k_base (GPT-4, 100k vocab). A natural question: do the findings hold for other tokenizers, or are they an artifact of one vocabulary?

We test tokenizers across a wide range of vocabulary sizes and training distributions. Larger vocabularies generally compress more character sequences into single tokens, so absolute counts differ — but the question is whether the relative ordering between formats and serializers is preserved.

  ✓ GPT-2 (50k)
  ✓ Llama 3 (128k)
  ✓ Qwen3 (151k)
  ✓ Gemma 2 (256k)
Loading...

E. Assessment

The experiments above establish three findings that hold across all 5 production prompt files, one representative file for isolation, and all tokenizers tested (cl100k_base in sections A–C, plus GPT-2 50k, Llama 3 128k, Qwen3 151k, and Gemma 2 256k in section D).

Finding 1 — The serializer is a hidden variable. Minified JSON and Pretty JSON are serializer-stable: json.dumps() parameters fully determine their output regardless of tool. Standard YAML and YAML Literal are serializer-unstable: their token counts depend on the tool’s line-width policy, quoting style, and scalar coercion rules.

Finding 2 — Line wrapping (PyYAML width=80) is the dominant overhead. PyYAML’s default wraps long strings at 80 characters, adding newline tokens. Setting width=float('inf') eliminates this overhead with no semantic change (confirmed in C. Semantic Fidelity). The exact savings scale with the number of long string values in the prompt. Run cell B1 to measure on any prompt version.

Finding 3 — yq’s literal coercion inflates YAML Literal on documents with boolean or numeric fields. yq -oy '..style="literal"' applies literal block style to all scalars, including booleans and numbers. This has two compounding effects: every string scalar gets a |- indicator instead of |, and non-string scalars are moved from an inline value to their own indented line. The exact token cost of each effect is measured in B3. Literal block terminator and boolean coercion. On prompt files with many boolean flags this pushes YAML Literal (yq) above Pretty JSON. PyYAML’s literal representer applies only to strings. Whether the flip occurs depends on the file — compute it below.

Loading...

Files where Lit YAML (yq)     > Pretty JSON: 4/5
Files where Lit YAML (PyYAML) > Pretty JSON: 0/5

F. Stack Recommendation

Given the findings above, the cheapest semantically lossless YAML configuration is PyYAML with width=float('inf') (Standard YAML, no line-wrapping). This section quantifies the savings per file and confirms round-trip fidelity on the full corpus.

F1. Optimal PyYAML configuration

Loading...

F2. Fidelity check on the optimal configuration

Before adopting width=float('inf') in prepare_prompt.py, we verify that every prompt file round-trips losslessly: JSON → yaml.dump(width=∞) → yaml.safe_load → compare with original JSON. A failure here would indicate that yaml.safe_load coerces a value on parse (e.g., a bare date string becoming a datetime object).

Round-trip fidelity with width=∞ — all prompt files:

  handbook_consultant.json                      ✓
  ai_brainstorming_colleague.json               ✓
  devops_consultant.json                        ✓
  ai_systems_consultant_hybrid.json             ✓
  local_ai_systems_consultant.json              ✓

All files pass: True

Recommended configuration for prepare_prompt.py:

    yaml.dump(data, allow_unicode=True, default_flow_style=False,
              sort_keys=False, width=float('inf'))