LLM API에 보내는 모든 토큰은 돈이 듭니다. 토큰당 비용은 크지 않지만 — 프롬프트에 JSON으로 포맷된 50행의 사용자 데이터가 포함된 데이터셋이 있으면, 모든 중괄호, 모든 반복 키 이름, 모든 따옴표에 대해 비용을 지불하고 있는 것입니다. 10개 필드와 100개 행을 가진 데이터셋에서 JSON은 토큰의 약 60~70%를 구조적 노이즈에 소비합니다. TOON은 정확히 이것을 해결하기 위해 구축되었습니다. 이 문서는 @toon-format/toon을 사용하여 구조를 잃지 않고 프롬프트 토큰 수를 — 때로는 절반 이상 — 줄이는 방법을 보여줍니다.
LLM 토큰 가격 작동 방식
GPT-4o와 Claude 같은 모델은 입력 토큰당, 출력 토큰당 청구합니다. OpenAI Tokenizer 도구를 사용하면 텍스트를 붙여넣고 정확히 얼마나 많은 토큰이 드는지 볼 수 있습니다. 대략 말하면, 1 토큰 ≈ 4자의 영어 텍스트 — 하지만 JSON의 구조적 문자(따옴표, 콜론, 중괄호)는 종종 개별적으로 토큰화되어, JSON 중심의 프롬프트는 동일한 문자 수의 일반 산문보다 더 나쁘게 토큰화됩니다. 모든 요청에 구조적 세금을 내는 셈입니다.
각 프롬프트에 구조화된 데이터가 있는 수천 건의 요청을 하루에 실행하는 일반적인 SaaS 앱의 경우, 그 세금은 빠르게 누적됩니다. 대형 언어 모델의 아키텍처는 모델이 실제로 그 모든 포맷 노이즈가 필요하지 않음을 의미합니다 — 형식이 모호하지 않고 잘 설명된다면 JSON의 장황함 없이 구조화된 데이터를 충분히 읽을 수 있습니다.
JSON vs TOON — 구체적인 토큰 비교
이것을 구체적으로 만들어 보겠습니다. 다음은 JSON에서 10행 사용자 데이터셋입니다:
[
{ "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 표 형식 표기법으로 정확히 동일한 데이터입니다:
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,trueTOON 버전은 약 135~150 토큰으로 토큰화됩니다 — 약 55% 더 적음. 규모에서 이것은 반올림 오차가 아닙니다. GPT-4o 가격으로 하루에 10,000개의 이러한 쿼리를 실행한다면, 프롬프트에서만 JSON과 TOON의 차이는 의미 있는 금액이 됩니다.
Node.js에서 설치 및 데이터 변환
npm에서 패키지를 설치하세요. Node.js 18+ 및 최신 브라우저에서 작동합니다:
npm install @toon-format/toon가져오기는 단일 구조 분해입니다:
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을 다시 디코딩합니다.
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 객체 배열에 비해 상당한 토큰을 절약합니다.
- 반복적인 구조화된 쿼리. 애플리케이션이 하루에 수천 번 같은 형태의 쿼리를 만드는 경우(예: 각 프롬프트에 사용자 레코드가 있는 "이 사용자의 활동 분석"), 누적 절약이 상당합니다.
- 배치 처리 작업. LLM을 통해 수천 개의 레코드를 처리하는 스크립트 — 분류, 태깅, 풍부화, 요약 — 는 엄청난 혜택을 받습니다. 호출당 더 적은 토큰은 더 빠른 처리량과 더 낮은 비용을 의미합니다.
- 컨텍스트 창 제약 작업. 대규모 시스템 프롬프트와 few-shot 예시와 함께 128k 컨텍스트 창에 대규모 데이터셋을 맞추려고 할 때, 모든 토큰이 중요합니다. TOON을 사용하면 같은 창에 더 많은 행을 맞출 수 있습니다.
- 비용에 민감한 프로덕션 API. 무료 취미 프로젝트는 눈치채지 못할 것입니다. 규모에서 유료 사용자를 서비스하는 프로덕션 앱은 절대적으로 알아챌 것입니다.
한 가지 주의사항: LLM이 형식을 알아야 합니다
TOON은 JSON처럼 어떤 LLM의 훈련 데이터에도 포함되어 있지 않습니다. 모델은 .toon 파일을 본 적이 없습니다. 이는 시스템 프롬프트에 간단한 형식 설명을 포함해야 함을 의미합니다 — 그렇지 않으면 모델이 입력을 거부하거나 잘못 파싱할 것입니다. 좋은 소식은 설명이 짧고, 대화 또는 요청당 한 번만 비용을 지불한다는 것입니다.
안정적으로 작동하는 최소 시스템 프롬프트 추가:
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 Formatter를 사용하여 올바르게 보이는지 확인하세요.
마무리
LLM 워크플로우에서 TOON의 경우는 간단합니다: 토큰당 비용을 지불하고, JSON의 구조화된 데이터는 토큰 비효율적이며, TOON은 직접적인 해결책입니다. 표 형식 표기법만으로도 일반적인 행 기반 데이터셋에서 토큰 사용이 50~60% 줄어듭니다. npm 패키지 — @toon-format/toon — 는 작고, API는 두 가지 함수이며, 기존 API 호출에의 통합은 5분이면 됩니다. 기억해야 할 유일한 것은 시스템 프롬프트의 형식 설명입니다 — 없으면 모델이 추측하게 됩니다. 그것이 있으면 절반의 토큰 비용으로 데이터를 올바르게 읽는 모델을 얻게 됩니다. JSON to TOON으로 기존 데이터를 변환하고, TOON Validator로 검증하고, TOON to JSON 또는 decode()를 사용하여 필요할 때 구조화된 응답을 다시 변환하세요.