One order result, six encodings: compact JSON costs 67 percent of pretty JSON, CSV 46 percent but loses types, nulls and nesting. Measure with your tokenizer.
One tool, six encodings of the same answer
Tanishka maintains the order-lookup tool that the help-desk agent at Belgavi's Book Store calls most often. It returns recent orders for a customer: order number, status, when it was placed, total, currency, the items with ISBN, title and quantity, an optional customer note, and whether the order is a gift. The tool returns pretty-printed JSON because that is what the web API already produced.
Tool results are input tokens on every later turn of the conversation, so their encoding is a cost multiplier. Teams often hear that JSON is wasteful and switch to CSV or a custom line format. Some of that is true and some of it loses data silently. The only way to know which applies to your tool is to measure your own payloads with the tokenizer your model uses and check that the format still carries what the agent needs.
The companion example does that for the order rows: six encodings of identical data, token counts with two tiktoken encodings, and a round trip through a plain parser to see what each format preserves.
The six formats
- Pretty JSON:
json.dumps(..., indent=2), what most HTTP APIs return. - Compact JSON: the same object with no whitespace.
- Short-key JSON: one-letter or two-letter keys plus a legend object that maps them back.
- Columnar JSON: a
columnslist once, then each row as an array of values. - CSV: a header row, then one line per order; the nested items are flattened into
isbn|title|qtyjoined by semicolons. - Key-value lines: one line per order,
field=valuepairs with JSON-encoded values.
The rows are deterministic and synthetic, so the counts are reproducible. Titles, notes with commas and quotes, null notes and nested item lists are included on purpose, because real order data has all of them.
The measurements
Tokens in the o200k_base encoding, and the share of pretty JSON:
| Format | 1 row | 5 rows | 25 rows | 100 rows | Share at 100 |
|---|---|---|---|---|---|
| Pretty JSON | 129 | 774 | 3,954 | 15,908 | 100% |
| Compact JSON | 86 | 519 | 2,648 | 10,654 | 67.0% |
| Short-key JSON | 121 | 542 | 2,611 | 10,392 | 65.3% |
| Columnar JSON | 87 | 448 | 2,199 | 8,802 | 55.3% |
| Key-value lines | 75 | 495 | 2,544 | 10,262 | 64.5% |
| CSV | 69 | 370 | 1,821 | 7,298 | 45.9% |
The cl100k_base counts are within 2.5% of these in every cell, and the ranking at 100 rows is the same for both encodings. Four results deserve attention.
Removing whitespace is the largest free win. Compact JSON is about two thirds of pretty JSON at every size, with no change in meaning and no change to the consumer. If your tool returns indented JSON today, this is the first change to make.
Short keys do not pay for small results. The legend costs tokens once per result. At one row, short-key JSON costs 121 tokens against 86 for compact JSON; at 100 rows it saves only 2.5% over compact JSON. Common English field names are cheap in modern encodings because they are often single tokens, so abbreviating them saves little and makes the payload harder to read for the model and for people debugging it.
Columnar JSON saves by not repeating keys. It reaches 55% of pretty JSON at 100 rows and still round-trips exactly, including nested items and nulls. For uniform lists it is the strongest JSON option.
CSV is the smallest and the lossiest. At 100 rows it costs 7,298 tokens, 46% of pretty JSON. A plain round trip through Python's csv reader changed four fields:
| Field | Rows changed of 100 | What happened |
|---|---|---|
total | 100 | numbers come back as strings |
gift | 100 | booleans come back as the strings True or False |
items | 100 | the nested list becomes one delimited string |
customer_note | 37 | null becomes an empty string, indistinguishable from a blank note |
A model reading the CSV may still understand most of it. But "no note" and "an empty note" are now the same, and a title containing the | or ; used for flattening would corrupt the items column. Every convention you add to make CSV safe is a convention the model must also infer.
The measuring code
The core is short enough to adapt to any tool:
import json
import tiktoken
def measure(rows, formats, encodings=("o200k_base", "cl100k_base")):
encs = {e: tiktoken.get_encoding(e) for e in encodings}
out = {}
for name, fn in formats.items():
text = fn(rows)
out[name] = {e: len(enc.encode(text)) for e, enc in encs.items()}
out[name]["fields_changed"] = fidelity(rows, parse_back(name, text))
return out
def compact_json(rows):
return json.dumps({"orders": rows}, separators=(",", ":"), ensure_ascii=False)fidelity compares every field of every row after parsing back, so a format that loses types or nulls shows up as a number instead of a surprise in production. ensure_ascii=False matters for non-English titles and names: escaping them as \uXXXX multiplies their token count.
Choosing a format
- Start from compact JSON. It is lossless, every model handles it, and it removes a third of the cost of indented JSON.
- For lists of uniform records with more than a few rows, try columnar JSON and measure. Keep the field names readable.
- Use CSV only for flat, string-like data where nulls and types do not matter, and say so in the tool description.
- Shrink what you return before you change how you encode it. Dropping fields the agent never uses, returning 10 rows with a continuation argument instead of 100, and summarising long free text usually saves more than any encoding.
- Measure with your provider's own token counter. Providers add framing around tool results, and models outside the encodings measured here use different tokenizers. Anthropic and others expose token-counting endpoints that count a full request including tools.
A decision for the order tool
Tanishka applied the measurements to the team's own tool rather than adopting one format everywhere. The order lookup returns between one and five orders in almost every call, so Tanishka switched it from pretty JSON to compact JSON: a third fewer tokens, the same parser, no change for the web API that shares the serializer, and no loss of nulls or nesting. The order search tool, which returns up to 50 rows of the same shape, moved to columnar JSON with readable column names, which roughly halved its cost against the old pretty output while still round-tripping exactly. CSV was rejected for both because the agent decides gift wrapping from the boolean gift field and treats a missing note differently from an empty one. The search tool's default page was also cut from 50 rows to 10, with a continuation argument, which saved more than either encoding change. Each change went in with a test that parses the tool output back and compares it field by field with the source rows.
What this does not measure
No model was called. The measurements say how many tokens each format costs and what a parser recovers, not how accurately a given model answers questions from each format. That depends on the model, the task and the prompt, and it is worth testing separately with a small evaluation: ask the questions your agent actually asks, such as which orders are gifts or which have a note, and compare answers across formats. A format that saves 30% of tokens and causes one wrong refund decision is not a saving.
Failure modes
- A format change that breaks a downstream consumer. Tool results are often logged and parsed by other systems; check who reads them.
- Truncation. A result that hits a length limit mid-row in CSV still parses as a shorter, wrong table. JSON fails to parse, which is the better failure.
- Inconsistent nulls. If some rows omit a key and others set it to null, columnar and CSV formats must pick one representation; decide which and document it.
- Locale formatting. Numbers formatted with thousands separators or decimal commas cost more tokens and break parsers.
Verification
Run python example.py in the companion and compare with expected.json; the tests assert the compact-JSON ratio, the one-row short-key penalty, exact round trips for the JSON formats and the CSV losses above. Then replace rows() with a real, anonymised sample of your tool's output and rerun. Keep the result next to the tool's code so the next format change starts from a measurement.