LLM APIに送るすべてのトークンにはコストがかかります。トークンあたりはそれほど高くありません — しかし、プロンプトにJSONとしてフォーマットされた50行のユーザーデータのデータセットが含まれる場合、すべての波括弧、すべての繰り返しキー名、すべての引用符に対して支払っています。10フィールドと100行のデータセットでは、JSONはトークンの約60〜70%を構造ノイズに費やします。TOONはまさにこれを解決するために構築されました。この記事では、@toon-format/toonを使ってプロンプトトークン数を削減する方法を示します — 時には半分以上 — モデルが必要とする構造を失うことなく。

LLMトークン料金の仕組み

GPT-4oやClaudeなどのモデルは入力トークンと出力トークンごとに課金します。OpenAI Tokenizerツールを使えば、任意のテキストを貼り付けて正確にいくつのトークンがかかるかを確認できます。おおよそ、1トークン ≈ 英語テキスト4文字 — しかしJSONの構造的文字(引用符、コロン、波括弧)は個別にトークン化されることが多く、JSONが多いプロンプトは同じ文字数の通常の文章よりもトークン効率が悪いです。各リクエストで構造税を支払っています。

各プロンプトに構造化データを含む1日数千のリクエストを実行している典型的なSaaSアプリでは、その税は急速に積み重なります。大規模言語モデルのアーキテクチャは、モデルがすべてのフォーマットノイズを必要としないことを意味します — フォーマットが明確で十分に説明されていれば、JSONの冗長性なしで構造化データを問題なく読めます。

JSONとTOON — 具体的なトークン比較

これを具体的にしましょう。JSONで10行のユーザーデータセット:

json
[
  { "id": 1, "username": "alice_dev", "email": "[email protected]", "plan": "pro", "active": true },
  { "id": 2, "username": "bob_writer", "email": "[email protected]", "plan": "free", "active": true },
  { "id": 3, "username": "carol_ops", "email": "[email protected]", "plan": "pro", "active": false },
  { "id": 4, "username": "dan_qa", "email": "[email protected]", "plan": "team", "active": true },
  { "id": 5, "username": "eve_design", "email": "[email protected]", "plan": "pro", "active": true },
  { "id": 6, "username": "frank_sec", "email": "[email protected]", "plan": "team", "active": true },
  { "id": 7, "username": "grace_ml", "email": "[email protected]", "plan": "pro", "active": false },
  { "id": 8, "username": "henry_be", "email": "[email protected]", "plan": "free", "active": true },
  { "id": 9, "username": "iris_fe", "email": "[email protected]", "plan": "pro", "active": true },
  { "id": 10, "username": "jack_devrel", "email": "[email protected]", "plan": "team", "active": true }
]

そのJSONブロックは約310〜330トークンになります。同じデータをTOONの表形式表記で:

text
users[10]{id,username,email,plan,active}:
  1,alice_dev,[email protected],pro,true
  2,bob_writer,[email protected],free,true
  3,carol_ops,[email protected],pro,false
  4,dan_qa,[email protected],team,true
  5,eve_design,[email protected],pro,true
  6,frank_sec,[email protected],team,true
  7,grace_ml,[email protected],pro,false
  8,henry_be,[email protected],free,true
  9,iris_fe,[email protected],pro,true
  10,jack_devrel,[email protected],team,true

TOONバージョンは約135〜150トークン — 約55%少ないです。スケール時、これは丸め誤差ではありません。GPT-4oの価格でこのようなクエリを1日10,000件実行している場合、プロンプト内のJSONとTOONの差だけでも重要になります。

トークン節約は列ではなく行でスケールします。データセットの行が多いほど、より大きな効果があります — TOONは列ヘッダーのコストを一度だけ支払いますが、JSONはすべての行でキー名のコストを支払います。TOONの100行テーブルは、この10行の例とほぼ同じ割合を節約します。

Node.jsでのインストールとデータ変換

npmからパッケージをインストールします。Node.js18+とモダンブラウザで動作します:

bash
npm install @toon-format/toon

インポートは1つの分割代入:

js
import { encode, decode } from '@toon-format/toon';

// Convert a JS array/object to TOON before sending to an LLM
const users = [
  { id: 1, username: 'alice_dev', email: '[email protected]', plan: 'pro', active: true },
  { id: 2, username: 'bob_writer', email: '[email protected]', plan: 'free', active: true },
  // ... more rows
];

const toonData = encode(users, { indent: 2 });
console.log(toonData);
// users[2]{id,username,email,plan,active}:
//   1,alice_dev,[email protected],pro,true
//   2,bob_writer,[email protected],free,true

実用的なパターン:Fetch → Encode → Prompt → Decode

LLM APIでTOONを使用するワークフローは4ステップです。データをどんなソースからでも取得し(データベース、REST API、CSVファイル)、TOONにエンコードし、プロンプトを構築し、オプションでモデルの応答から構造化されたTOONをデコードします。

js
import { encode, decode } from '@toon-format/toon';
import OpenAI from 'openai';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

async function analyseUsers(users) {
  // Step 1: encode data to TOON
  const toonData = encode(users, { indent: 2 });

  // Step 2: build the prompt
  const systemPrompt = [
    'You analyse user datasets. Data is provided in TOON (Token-Optimised Object Notation).',
    'TOON tabular format: name[count]{col1,col2,...}: followed by comma-separated rows, one per line.',
    'Respond with plain prose unless asked to return data, in which case use TOON format.'
  ].join('\n');

  const userPrompt = `Here is the user dataset:\n\n${toonData}\n\nWhich plan has the most active users?`;

  // Step 3: call the API
  const response = await openai.chat.completions.create({
    model: 'gpt-4o',
    messages: [
      { role: 'system', content: systemPrompt },
      { role: 'user', content: userPrompt }
    ]
  });

  return response.choices[0].message.content;
}

// Step 4 (optional): if the model returns TOON, decode it back
const rawResponse = await analyseUsers(myUserArray);
try {
  const structured = decode(rawResponse);
  console.log('Structured result:', structured);
} catch {
  console.log('Prose response:', rawResponse);
}

同じパターンはAnthropic Claude APIでも動作します — クライアントを入れ替えるだけです。プロンプト構造とTOONエンコーディングはプロバイダーに関係なく同一です。認証設定とモデル選択の詳細についてはOpenAI APIドキュメントを確認してください。

最も重要な場面

TOONが最も効果を発揮するシナリオ:

  • コンテキスト内の大きなデータセット。プロンプトに~20行以上の構造化データを入れる場合、TOONの表形式表記でJSONオブジェクトの配列と比べて大幅なトークン節約ができます。
  • 繰り返しの構造化クエリ。アプリケーションが1日に何千回も同じ形状のクエリを行う場合(例:各プロンプトにユーザーレコードを含む「このユーザーのアクティビティを分析」)、累積節約は相当なものです。
  • バッチ処理ジョブ。LLMを通じて数千のレコードを処理するスクリプト — 分類、タグ付け、エンリッチメント、要約 — は大きなメリットがあります。呼び出しあたりのトークンが少ないということは、スループットが高くコストが低くなることを意味します。
  • コンテキストウィンドウ制約のあるタスク。長いシステムプロンプトとfew-shotの例とともに大きなデータセットを128kコンテキストウィンドウに収めようとする場合、すべてのトークンが重要です。TOONを使えば同じウィンドウにより多くの行を詰め込めます。
  • コスト敏感な本番API。無料層の趣味プロジェクトは気づかないでしょう。有料ユーザーをスケールで提供する本番アプリは確実に気づきます。

注意点:LLMはフォーマットを知る必要があります

TOONはJSONのようにどのLLMの学習データにも含まれていません。モデルは.toonファイルを見たことがありません。これはシステムプロンプトに簡単なフォーマット説明を含める必要があります —そうしないとモデルは入力を拒否するか誤って解析します。良いニュースは説明が短く、会話やリクエストごとに一度だけ支払うことです。

信頼できる最小限のシステムプロンプトへの追加:

text
Data is provided in TOON (Token-Optimised Object Notation).
TOON syntax:
- Objects: {key:value,key2:value2} — keys are never quoted
- Arrays: [val1,val2,val3]
- Tabular: name[rowCount]{col1,col2,...}:
    rowval1,rowval2,...
    rowval1,rowval2,...
Parse each row by matching values to the column headers in order.
Strings containing commas are double-quoted.

このブロックはシステムプロンプトに約60トークンを追加します — 5〜6行以上のデータセットですぐに回収できる一回限りのコストです。TOONデータで多くのAPIコールを行うアプリケーションでは、フォーマット説明トークンはほぼゼロに償却されます。プロンプトを構築する前にJSON to TOONでデータを変換し、TOONフォーマッターで正しく見えることを確認してください。

まとめ

LLMワークフローにおけるTOONの根拠は単純です:トークンごとに支払い、JSONの構造化データはトークン効率が悪く、TOONは直接的な解決策です。表形式表記だけで、典型的な行ベースのデータセットでトークン使用量を50〜60%削減します。npmパッケージ —@toon-format/toon— は小さく、APIは2つの関数で、既存のAPIコールへの統合は5分の作業です。覚えておくべき唯一のことはシステムプロンプトのフォーマット説明です — それなしではモデルが推測しています。それがあれば、半分のトークンコストでデータを正しく読むモデルが得られます。JSON to TOONから始めて既存のデータを変換し、TOONバリデーターで検証し、必要に応じてTOON to JSONまたはdecode()で構造化された応答を戻して変換してください。