<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Praharsh Dev Blog]]></title><description><![CDATA[A space where I write about Web Development, AI, and Software Engineering.]]></description><link>https://aihistorybypraharsh.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1593680282896/kNC7E8IR4.png</url><title>Praharsh Dev Blog</title><link>https://aihistorybypraharsh.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sun, 20 Sep 2026 04:43:26 GMT</lastBuildDate><atom:link href="https://aihistorybypraharsh.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Slash Your LLM Token Costs: Introducing TOON]]></title><description><![CDATA[Token-Oriented Object Notation (TOON) is a new, highly efficient way to send structured information to Large Language Models (LLMs) that cuts down significantly on cost and increases the amount of dat]]></description><link>https://aihistorybypraharsh.hashnode.dev/slash-your-llm-token-costs-introducing-toon</link><guid isPermaLink="true">https://aihistorybypraharsh.hashnode.dev/slash-your-llm-token-costs-introducing-toon</guid><category><![CDATA[AI]]></category><category><![CDATA[#ai-tools]]></category><category><![CDATA[llm]]></category><category><![CDATA[LLM's ]]></category><category><![CDATA[#RAG  #RetrievalAugmentedGeneration  #LLMApplications  #TechnicalDocs  #SensorEngineering  #MultimodalAI  #GraphRAG  #HyDEPrompting  #AIForEngineers  #KnowledgeGraphs  #MachineLearning  #LangChain  #LlamaIndex  #OCR  #Mechatronics  #IndustrialAI  #SmartManufacturing  #AIKnowledgeManagement  #SemanticSearch  #AIInfrastructure]]></category><category><![CDATA[json]]></category><category><![CDATA[toon]]></category><category><![CDATA[AI Development Services]]></category><dc:creator><![CDATA[Praharsh Singh]]></dc:creator><pubDate>Mon, 20 Jul 2026 16:24:06 GMT</pubDate><content:encoded><![CDATA[<p><strong>Token-Oriented Object Notation (TOON)</strong> is a new, highly efficient way to send structured information to Large Language Models (LLMs) that cuts down significantly on cost and increases the amount of data you can send. It was specifically created to be a <strong>lossless, drop-in replacement for JSON</strong> when used as input for an LLM. TOON achieves this token efficiency by borrowing the <strong>tabular format</strong> of a CSV (like a spreadsheet) for data where every item has the same structure—what it calls its "sweet spot," such as a uniform list of products or user profiles. For more complex structures, it uses an <strong>indentation-based structure</strong> similar to YAML to handle nested data. In essence, TOON strips away the repetitive, token-wasting symbols of JSON (like quotes, brackets, and commas) and is therefore perfect for <strong>uniform arrays of objects</strong> (multiple fields per row, same structure), but for highly unusual, deeply nested, or non-uniform data, standard JSON might still be the better or more efficient choice.</p>
<img src="https://cdn.hashnode.com/uploads/covers/64907f53a264d397cc4765ad/b8eff683-67e8-43b4-902e-3963bf9478d8.png" alt="" style="display:block;margin:0 auto" />

<h2>WHEN CREATED:</h2>
<p><strong>Token-Oriented Object Notation (TOON)</strong> is a very recent innovation, with its initial public projects and format definition emerging around <strong>late 2024 / early 2025</strong>. This timing is crucial, as it places TOON's creation squarely in the era where Large Language Model (LLM) technology became mainstream and its associated operational costs became a primary concern for businesses. The format was designed to be a direct, practical solution to this problem: Standard JSON, which was never designed with token efficiency in mind, wastes a significant number of tokens on redundant characters (quotes, braces, commas, and repeated keys). TOON was specifically engineered as a <strong>lossless, drop-in replacement</strong> for JSON data when used as an LLM prompt input. Crucially, the TOON format and its reference implementations are released under the <strong>MIT License</strong>, ensuring it is open-source, easily accessible, and free for both commercial and private use, allowing developers to immediately benefit from its efficiency and send the same information with significantly fewer tokens. <strong>The Problem: JSON is Too "Chatty"</strong></p>
<p>AI is becoming cheaper and more accessible, and while larger context windows allow us to feed LLMs more data, <strong>LLM tokens still cost money</strong>. The fundamental issue is that <strong>standard JSON is verbose and token-expensive</strong>. It was designed for machine-to-machine communication, not for token-efficient LLM input. Every piece of punctuation—the braces, brackets, colons, and repeated quotation marks—consumes tokens without adding unique, meaningful information. For example, look at a small user array in standard JSON:</p>
<pre><code class="language-json">{
"users": [
{ "id": 1, "name": "Alice", "role": "admin" },
{ "id": 2, "name": "Bob", "role": "user" }
]
}

// Number of token : 50
</code></pre>
<p>JSON relies heavily on specific characters to define its structure. These characters must be included in your prompt and consume tokens, but they don't add unique information about your users (Alice and Bob).</p>
<table>
<thead>
<tr>
<th><strong>Redundant Character</strong></th>
<th><strong>Why It's Wasteful (Token-Consuming)</strong></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Quotes (</strong><code>"</code><strong>)</strong></td>
<td>Repeated around every single key (<code>"id"</code>, <code>"name"</code>, <code>"role"</code>) and every string value (<code>"Alice"</code>, <code>"admin"</code>). This is the biggest token killer.</td>
</tr>
<tr>
<td><strong>Braces (</strong><code>{ }</code><strong>)</strong></td>
<td>Repeated for <em>every</em> object (user) in the array.</td>
</tr>
<tr>
<td><strong>Brackets (</strong><code>[ ]</code><strong>)</strong></td>
<td>Used to define the start and end of the list (<code>"users"</code> array).</td>
</tr>
<tr>
<td><strong>Colons (</strong><code>:</code><strong>) and Commas (</strong><code>,</code><strong>)</strong></td>
<td>Repeatedly used as separators between keys, values, and objects.</td>
</tr>
</tbody></table>
<p>In your small example, the core data is <code>1, Alice, admin, 2, Bob, user</code>. Everything else is just formatting that you pay for</p>
<p>This "chatty" nature of JSON directly translates to three main penalties for the user:</p>
<ol>
<li><p><strong>Higher API Costs:</strong> You are paying the LLM provider for every redundant token. If 30-60% of your prompt is just JSON syntax, your bill is unnecessarily inflated.</p>
</li>
<li><p><strong>Context Window Limits:</strong> Every wasted token takes up valuable space in the LLM's <strong>context window</strong> (the maximum text it can process). This means you can send the model fewer actual users or products before you hit the limit and have to split your request.</p>
</li>
<li><p><strong>Slower Latency:</strong> The LLM has to process more tokens, leading to slower response times.</p>
</li>
</ol>
<h2><strong>The TOON Solution: Declare Once, Stream Data:</strong></h2>
<p>The core brilliance of <strong>Token-Oriented Object Notation (TOON)</strong> lies in its philosophy of <strong>"Declare Once, Stream Data,"</strong> which is achieved by borrowing the best ideas from formats like <strong>YAML (for indentation)</strong> and <strong>CSV (for tabular data)</strong> to create a final format that is both human-readable and <strong>hyper-efficient for LLM processing</strong>. This efficiency is realized by eliminating the repetitive redundancy that plagues JSON, especially with uniform lists; instead of forcing developers to repeat field names for every single item, TOON simply <strong>declares the entire data structure (including keys and item count) only one time</strong>, and then allows the data values to be cleanly streamed in a compact, row-by-row fashion</p>
<table>
<thead>
<tr>
<th><strong>JSON (Verbose)</strong></th>
<th><strong>TOON (Efficient)</strong></th>
</tr>
</thead>
<tbody><tr>
<td><code>json{ "users": [ { "id": 1, "name": "Alice", "role": "admin" }, { "id": 2, "name": "Bob", "role": "user" } ]}</code></td>
<td><code>toonusers[2]{id,name,role}: 1,Alice,admin 2,Bob,user</code></td>
</tr>
<tr>
<td>50 Tokens</td>
<td>19 Tokens</td>
</tr>
</tbody></table>
<p>The difference is staggering. In the TOON snippet (which contains approximately <strong>19 tokens</strong>), the structural information is handled by a single header line: <code>users[2]{id,name,role}:</code>. This line efficiently communicates:</p>
<ol>
<li><p><strong>Object Name:</strong> A list called <code>"users"</code>.</p>
</li>
<li><p><strong>Explicit Length:</strong> It contains <strong>2 items</strong> (<code>[2]</code>).</p>
</li>
<li><p><strong>Keys:</strong> The keys for each item are <code>"id"</code>, <code>"name"</code>, and <code>"role"</code>.</p>
</li>
</ol>
<p>After this single declaration, it simply <strong>streams the comma-separated values</strong> for each row: <code>1,Alice,admin</code> and <code>2,Bob,user</code></p>
<h2>The Payoff: Massive Token Savings</h2>
<p>The efficacy of <strong>Token-Oriented Object Notation (TOON)</strong> is clearly demonstrated by its performance benchmarks. The project's own testing confirms that these are not trivial savings; they translate directly into a significant reduction in operational costs. For instance, in a test involving <strong>100 GitHub repository objects</strong>, TOON delivered an impressive token reduction of <strong>42.3%</strong> compared to standard JSON. The savings were even more dramatic when applied to a daily web analytics dataset, where it achieved a token reduction of nearly <strong>58.9%</strong>. When developers are making hundreds or even thousands of Large Language Model (LLM) calls per day, this massive efficiency gain quickly compounds, making TOON an essential tool for managing API expenses and scaling LLM-powered applications affordably.</p>
<img src="https://cdn.hashnode.com/uploads/covers/64907f53a264d397cc4765ad/35b8f15a-9b34-4a4c-b9c9-6357e7256451.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>But Can LLMs Actually Understand It?</strong></h2>
<p>This is the most critical question. What's the point of saving tokens if the model can't retrieve the data?</p>
<p>The answer is a definitive <strong>yes</strong>, and in many cases, Large Language Models (LLMs) can process TOON data as reliably as, or even better than, standard JSON. The reason for this success lies in TOON's smart design, which avoids completely reinventing the wheel. Instead, it leverages structural patterns that LLMs were extensively trained on: the <strong>indentation-based structure of YAML</strong> to define hierarchy and the <strong>tabular nature of CSV</strong> for lists. By relying on these familiar, predictable formats, TOON minimizes ambiguity and allows the LLM to apply its existing parsing capabilities, demonstrating that token savings do not need to compromise model comprehension.</p>
<p>Furthermore, TOON incorporates key <strong>LLM-friendly "guardrails"</strong> that aid in accurate processing. For instance, notations like <code>users[2]</code> explicitly declare the expected number of items in an array. This is a critical feature because it helps prevent common LLM issues such as truncating a list or <em>hallucinating</em> extra objects, which can often happen when JSON objects are deeply nested or lengthy. By removing the visual and token "noise" of repetitive JSON punctuation (like quotes and braces) and replacing it with clean, simple tabular structures, TOON allows the model to focus its attention entirely on the meaningful data—the keys and values—leading to high accuracy in data retrieval tasks, even while using 40-60% fewer tokens.</p>
<p>Ultimately, the goal is not just token efficiency but <strong>reliable data exchange</strong>. Benchmarks have shown that TOON performs strongly in data extraction tasks, proving that its compact design is highly predictable and easily understandable by the current generation of large language models.</p>
<p>Accuracy between four models in Toon</p>
<img src="https://cdn.hashnode.com/uploads/covers/64907f53a264d397cc4765ad/e0548fea-ab8d-42ca-9035-d560e653b1da.png" alt="" style="display:block;margin:0 auto" />

<h2><strong>How to Get Started &amp; INSTALL</strong></h2>
<p>Getting started with <strong>Token-Oriented Object Notation (TOON)</strong> is designed to be straightforward—it's essentially a drop-in replacement for <code>JSON.stringify()</code> when preparing data for your LLM prompts.</p>
<pre><code class="language-jsx"># npm
npm install @toon-format/toon

# pnpm
pnpm add @toon-format/toon

# yarn
yarn add @toon-format/toon
</code></pre>
<p><strong>Example Code</strong></p>
<pre><code class="language-jsx">import { encode } from '@toon-format/toon'

const data = {
  users: [
    { id: 1, name: 'Alice', role: 'admin' },
    { id: 2, name: 'Bob', role: 'user' }
  ]
}

console.log(encode(data))
// users[2]{id,name,role}:
//   1,Alice,admin
//   2,Bob,user
</code></pre>
<h3><strong>CLI</strong></h3>
<p>Command-line tool for converting between JSON and TOON formats.</p>
<p>The <code>toon</code> Command Line Interface (CLI) is designed for <strong>flexibility and ease of use</strong>, allowing developers to seamlessly integrate TOON conversion into their terminal workflows. The tool is smart enough to handle input data from two sources: directly from a specified file or via <strong>standard input (</strong><code>stdin</code><strong>)</strong>, where data is piped directly from the output of another command (by omitting the input argument or using a single hyphen <code>-</code>). For simple file-based conversions, the tool offers <strong>auto-detection</strong>: it automatically knows to <strong>encode</strong> (JSON to TOON) if the input file ends in <code>.json</code> and to <strong>decode</strong> (TOON to JSON) if the input file ends in <code>.toon</code>.</p>
<p>Examples:</p>
<pre><code class="language-jsx"># Encode JSON to TOON (auto-detected)
npx @toon-format/cli input.json -o output.toon

# Decode TOON to JSON (auto-detected)
npx @toon-format/cli data.toon -o output.json

# Output to stdout
npx @toon-format/cli input.json

# Pipe from stdin (no argument needed)
cat data.json | npx @toon-format/cli
echo '{"name": "Ada"}' | npx @toon-format/cli

# Explicit stdin with hyphen (equivalent to above)
cat data.json | npx @toon-format/cli -

# Decode from stdin
cat data.toon | npx @toon-format/cli --decode
</code></pre>
<p><strong>Options</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/64907f53a264d397cc4765ad/c34ec6df-a31c-41bc-b850-9bfd63669f61.png" alt="" style="display:block;margin:0 auto" />

<h3>Json To Toon Examples</h3>
<p>Imagine you have a simple list of people with their names and ages. In JSON, it would look something like this:</p>
<pre><code class="language-jsx">[
  {
    "name": "Alex Johnson",
    "age": 30
  },
  {
    "name": "Maria Rodriguez",
    "age": 25
  },
  {
    "name": "Ben Carter",
    "age": 42
  },
  {
    "name": "Samantha Lee",
    "age": 19
  },
  {
    "name": "David Chen",
    "age": 55
  }
]
</code></pre>
<p><strong>Convert it into toon using</strong></p>
<pre><code class="language-jsx">npx @toon-format/cli input.json
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="language-jsx">[5]{name,age}:
  Alex Johnson, 30
  Maria Rodriguez, 25
  Ben Carter, 42
  Samantha Lee, 19
  David Chen, 55
</code></pre>
<p>If You want to save the output in a file the use this command</p>
<pre><code class="language-jsx">npx @toon-format/cli input.json -o output.toon
</code></pre>
<h3>Toon To Json Examples</h3>
<pre><code class="language-jsx">npx @toon-format/cli --decode data.toon -o output.json
</code></pre>
<p>This command successfully takes your compact TOON data (<code>data.toon</code>) and reconstructs the verbose, standard JSON structure into a new file named <code>output.json</code>.</p>
<h2>USING TOON FILE WITH LLM MODEL</h2>
<p>We’ve seen the <strong>token savings</strong> and <strong>readability</strong> of the TOON format. Now, let’s bring it all together with a practical example showing exactly how a Node.js application uses that compact data to dynamically build a <strong>highly specific prompt</strong> for a Large Language Model (LLM).</p>
<p>LLM Model used : Xenova/gpt2 ( <a href="https://huggingface.co/Xenova/gpt2">https://huggingface.co/Xenova/gpt2</a>)</p>
<p>Toon file</p>
<p>What does it do: The LLM Model genrates a story about the famous dish of a given city if it’s data is store inside the Toon file</p>
<pre><code class="language-jsx">[52]: # The array length (52 entries total)
  - city: Mumbai
    state: Maharashtra
    famous_dish: Vada Pav
    alternates[3]: Pav Bhaji,Misal Pav,Bhel Puri
  - city: Delhi
    state: National Capital Territory
    famous_dish: Chole Bhature
    alternates[3]: "Chaat (Gol Gappe, Aloo Tikki)",Parathe,Butter Chicken
  - city: Kolkata
    state: West Bengal
    famous_dish: Rosogolla (Mishti Doi)
    alternates[3]: Kathi Rolls,Phuchka,Fish Curry (Machher Jhol)
  # ...  other entries ...
</code></pre>
<p><strong>Code using toon file with LLM model</strong></p>
<pre><code class="language-jsx">import { pipeline } from '@huggingface/transformers';
import * as fs from 'fs'; 
import * as path from 'path'; 

function buildCityMap(data) {
    if (!data) return null;
    
    if (!Array.isArray(data) &amp;&amp; typeof data === 'object') {
        const map = {};
        for (const k of Object.keys(data)) {
            map[k.trim().toLowerCase()] = data[k];
        }
        return map;
    }

    const map = {};
    if (Array.isArray(data)) {
        for (const entry of data) {
            if (!entry || !entry.city) continue;
            const normalized = entry.city.trim().toLowerCase();
            map[normalized] = entry;
        }
    }
    return map;
}

function loadToonData() {
    const TOON_PATH = path.join(process.cwd(), 'output.toon');
    try {
        if (!fs.existsSync(TOON_PATH)) return null;
        const text = fs.readFileSync(TOON_PATH, 'utf8');
        const lines = text.split(/\r?\n/);
        const entries = [];
        let current = null;

        for (let raw of lines) {
            const line = raw.trim();
            const mCity = line.match(/^-?\s*city:\s*(.+)$/i);
            if (mCity) {
                if (current) entries.push(current);
                current = { city: mCity[1].replace(/^"|"$/g, '').trim() };
                continue;
            }
            if (!current) continue;

            const mState = line.match(/^state:\s*(.+)$/i);
            if (mState) {
                current.state = mState[1].replace(/^"|"$/g, '').trim();
                continue;
            }

            const mDish = line.match(/^famous_dish:\s*(.+)$/i);
            if (mDish) {
                current.famous_dish = mDish[1].replace(/^"|"$/g, '').trim();
                continue;
            }

            const mAlt = line.match(/^alternates(?:\[\d+\])?:\s*(.+)$/i);
            if (mAlt) {
                const list = mAlt[1]
                    .split(',')
                    .map(s =&gt; s.replace(/^"|"$/g, '').trim())
                    .filter(Boolean);
                current.alternates = list;
                continue;
            }
        }

        if (current) entries.push(current);
        return entries;
    } catch (err) {
        console.error(`Could not read/parse output.toon: ${err.message}`);
        return null;
    }
}

const toonData = loadToonData();

// Build cityMap from toonData only
const cityMap = buildCityMap(Array.isArray(toonData) ? toonData : []);

// --- 2. Main Execution Function ---

async function runTextGenerationWithContext() {
    
    if (!cityMap) {
        console.error('No city data available (output.toon missing or empty).');
        return; // Stop if data loading failed
    }
    
    // --- SIMULATE USER INPUT ---
    // In a real app, you would use a library like 'readline' to get input.
    const userCity = 'Delhi'; // &lt;--- Change this to test different cities
    console.log(`\nUser's selected city: **${userCity}**\n`);

    // Use a normalized, case-insensitive lookup into the city map
    const normalizedKey = userCity.trim().toLowerCase();
    let initialPrompt;

    // --- City Lookup and Prompt Customization ---
    const cityEntry = cityMap[normalizedKey];
    if (cityEntry) {
        const food = cityEntry.famous_dish;
        const state = cityEntry.state;
        const displayCity = cityEntry.city || userCity;

        // Custom prompt using the found food item
        console.log(`Found famous dish: **${food}** from ${state}.`);
        initialPrompt = `Once upon a time there was a developer who visited ${displayCity}. They were so excited to try the famous ${food} that they`;
    } else {
        // Fallback prompt if city is not in the JSON file
        console.log(`City ${userCity} not found in food data. Using a generic prompt.`);
        initialPrompt = 'Once upon a time there was a developer who';
    }

    // --- 3. Hugging Face Pipeline ---

    // Generate prompt message
    console.log(`Generating text with prompt: "${initialPrompt}"`);

    // Initialize the pipeline while suppressing any noisy logs from
    // the underlying runtime (e.g., dtype warnings). We temporarily
    // silence console methods during initialization and restore them
    // immediately after to avoid hiding other messages.
    let generator;
    const origLog = console.log;
    const origWarn = console.warn;
    const origError = console.error;
    try {
        console.log = () =&gt; {};
        console.warn = () =&gt; {};
        console.error = () =&gt; {};
        generator = await pipeline('text-generation', 'Xenova/gpt2');
    } finally {
        console.log = origLog;
        console.warn = origWarn;
        console.error = origError;
    }

    const output = await generator(initialPrompt, {
        max_new_tokens: 50,
    });

    // --- 4. Output Result ---
    
    console.log('\n--- Generated Story ---\n');
    console.log(output[0].generated_text);
    console.log('\n-----------------------\n');
}

runTextGenerationWithContext();
</code></pre>
<p>The provided JavaScript code sets up a complete process for <strong>contextualizing a Large Language Model (LLM) prompt</strong> using local TOON data. It first defines functions (<code>loadToonData</code> and <code>buildCityMap</code>) to read the <strong>compact TOON file</strong> (<code>output.toon</code>)—which efficiently stores city and food data—and converts it into a fast-lookup map. The main function, <code>runTextGenerationWithContext</code>, simulates user city input (e.g., 'Delhi'), uses the TOON map to retrieve a specific fact (e.g., 'Chole Bhature'), and then injects that fact into the starting phrase of a story. Finally, it uses the locally running, optimized <code>Xenova/gpt2</code> model (via Hugging Face Transformers.js) to generate a customized and highly relevant story continuation, demonstrating how TOON enables efficient data context for high-quality, local LLM output.</p>
<h2><strong>Why Toon is not better in every scenario</strong></h2>
<p>TOON files are not always good for every model because large language models do not truly “understand” data formats logically; they rely on patterns they have seen frequently during training. While TOON is more compact and token-efficient, many models have not been extensively trained on this notation, so they struggle to reliably infer structure, hierarchy, and field boundaries from it. In contrast, JSON and CSV are extremely common across web data, documentation, APIs, logs, and training corpora, making their syntax and structure deeply familiar to most models. JSON provides explicit hierarchy and key–value clarity, which helps models preserve relationships between data fields, while CSV offers a simple, predictable, flat structure that models can parse with high confidence. As a result, even though TOON uses fewer tokens and contains the same information, models often perform better with JSON or CSV because familiarity, structural cues, and training exposure matter more than compactness for accurate interpretation and reasoning.</p>
<h2>CONCLUSION:</h2>
<p>TOON is a practical, drop‑in way to slash LLM token spend without sacrificing structure or accuracy. By declaring schema once and streaming compact rows, it routinely cuts prompt size by 40–60%, letting you fit more real data into the same context window, speed up responses, and lower costs. Just as important, its YAML‑like hierarchy and CSV‑style tables make it easy for models to parse reliably, while length declarations add guardrails against truncation or hallucinated items.</p>
<p>If your workloads include uniform arrays of objects—catalogs, profiles, telemetry, analytics—TOON will likely pay for itself on day one. Keep JSON for highly irregular, deeply nested edge cases; use TOON for the vast middle where structure is consistent and volume is high.</p>
<h2>Sources</h2>
<ul>
<li><p><a href="https://github.com/toon-format/toon">GitHub repo</a></p>
</li>
<li><p><a href="https://huggingface.co/Xenova/gpt2">Hugging Face model (example LLM)</a></p>
</li>
<li><p><a href="https://github.com/toon-format/spec">Additional GitHub resources</a></p>
</li>
<li><p><a href="https://www.curiouslychase.com/playground/format-tokenization-exploration">Chase’s write‑up</a></p>
</li>
</ul>
]]></content:encoded></item></channel></rss>