{"slug": "don-t-send-the-whole-table-to-the-model-cutting-agent-tokens-on-data-heavy-apis", "title": "Don't send the whole table to the model: cutting agent tokens on data-heavy APIs", "summary": "A developer measured how much context data-heavy API payloads consume when handed to an LLM agent, finding that a pretty-printed 1,000-row ledger sample cost 236,366 tokens under tiktoken's o200k_base encoding while only 46 rows matched the actual question. Projecting to a short list of needed fields cut the payload to 39,329 tokens, and server-side filtering to a 25-row page plus totals reduced it to 1,028 tokens, roughly 0.4% of the naive dump. The developer argues the fix belongs in the tool result — query where the data lives and return a projected page with match counts — rather than in the model.", "body_md": "The first time I wired an agent to a data-heavy screen, I gave it the same JSON the table already uses. That felt honest. The UI needs every column, so the model probably does too.\n\nIt does not. A list endpoint for a ledger, a log, or a payments grid is shaped for people who scroll. An agent that is trying to answer one question does not need the names, tags, timestamps and metadata that travel with every row. Those fields still become input tokens, on every turn, until something evicts them from the context.\n\nThis article is about counting that cost, then changing the tool result, not the model. I built a 1,000-row sample ledger, asked a narrow question, and measured five payload shapes with tiktoken. The encoding is `o200k_base`, which is what current OpenAI models use. I also checked `cl100k_base`; the counts were within a few hundred tokens. Claude's tokenizer is not identical, so treat these as measured sizes, not an invoice.\n\nThe question is ordinary:\n\nPosted EUR lines booked in November 2026 with an amount over 10,000 minor units. How many are there, and what are the references?\n\nThe naive tool does this:\n\n```\njson.dumps(rows, indent=2)\n```\n\nEach row looks like a row a table would render: debit and credit names, a description, tags, a metadata object, created-by, timestamps. That is a reasonable UI payload. It is a poor prompt.\n\nOn this sample, that pretty-printed dump is 697,169 characters and **236,366 tokens**.\n\nThe sample is deterministic (`seed=42`), so you can reproduce the numbers. Of the 1,000 rows, **46** actually match the question. The model does not need the other 954 in order to answer.\n\nI used a small helper and five shapes of the same data:\n\n``` python\nimport tiktoken\n\ndef count_tokens(text: str, encoding_name: str = \"o200k_base\") -> int:\n    return len(tiktoken.get_encoding(encoding_name).encode(text))\n```\n\n| Shape | Characters | Tokens | Versus pretty JSON | \n|---|---|---|---|\n| Pretty JSON, all 1,000 rows | 697,169 | 236,366 | 100% | \n| Compact JSON, all 1,000 rows | 528,168 | 161,366 | 68.3% | \n| Projected columns, all 1,000 rows | 122,318 | 39,329 | 16.6% | \n| Server-filtered page of 25, plus totals | 3,238 | 1,028 | 0.4% | \n| One projected row | 122 | 40 | — | \n\nDropping whitespace helps, and it is free. It does not fix the real problem. You are still sending a thousand rows so the model can throw most of them away.\n\nIf the agent needs a reference, a date, an amount, a currency and a status, do not also send display names, tags and metadata. A projection is a short, explicit list of keys:\n\n```\nPROJECTED_FIELDS = (\n    \"id\",\n    \"reference\",\n    \"booked_on\",\n    \"amount_minor\",\n    \"currency\",\n    \"status\",\n)\n\ndef project(row: dict) -> dict:\n    return {key: row[key] for key in PROJECTED_FIELDS}\n```\n\nOn this ledger, projecting every row and compacting the JSON cut the payload from 236,366 tokens to **39,329**. That is a real saving, and it is still the wrong shape for this question, because 954 of those rows cannot be the answer.\n\nKeep the full row in your database. Give the tool a narrow view of it.\n\nThe cheaper move is the one a data-heavy UI already makes: run the query where the data lives, then return a page and a total. The tool result should say what was asked, how many rows matched, whether more remain, and a short page of projected rows.\n\n``` php\ndef matches_query(row: dict) -> bool:\n    return (\n        row[\"currency\"] == \"EUR\"\n        and row[\"status\"] == \"posted\"\n        and row[\"booked_on\"].startswith(\"2026-11\")\n        and row[\"amount_minor\"] > 10_000\n    )\n\ndef paged_payload(rows: list[dict], *, page_size: int = 25, cursor: int = 0) -> str:\n    matched = [project(r) for r in rows if matches_query(r)]\n    page = matched[cursor : cursor + page_size]\n    next_cursor = cursor + page_size\n    has_more = next_cursor < len(matched)\n    return json.dumps(\n        {\n            \"query\": {\n                \"currency\": \"EUR\",\n                \"status\": \"posted\",\n                \"booked_on\": \"2026-11\",\n                \"amount_minor_gt\": 10_000,\n            },\n            \"total\": len(matched),\n            \"has_more\": has_more,\n            \"next_cursor\": next_cursor if has_more else None,\n            \"sum_amount_minor\": sum(r[\"amount_minor\"] for r in matched),\n            \"rows\": page,\n        },\n        separators=(\",\", \":\"),\n    )\n```\n\nThat first page is **1,028 tokens**. The second page, which holds the remaining 21 matching rows, is **872 tokens**. If the agent fetches both pages, it has seen every matching row for **1,900 tokens**. That is 0.8% of the pretty-printed dump.\n\nThe echo of `query` is deliberate. It costs a few tokens and stops the model from answering a slightly different question than the one the server just ran. The totals let it say \"46 lines, summing to 5,929,244 minor units\" without scanning a thousand objects.\n\nThe cursor in this sample is an index into an already filtered, frozen list. That is fine for a measurement. On a live table that other people are writing to, encode a keyset such as `(booked_on, id)` instead, so a new insert cannot skip a row between pages.\n\nOnce the page has an `id`, a second tool can return that row alone. In this sample, one projected row is **40 tokens**.\n\nThat is the pattern I want from an agent on a data-heavy API: a cheap index first, a precise read second. It is the same split I want from a human UI. The table does not render a detail drawer for every row up front.\n\nA TypeScript contract for the tool keeps both sides honest:\n\n```\ntype LedgerRow = {\n  id: string;\n  reference: string;\n  booked_on: string;\n  amount_minor: number;\n  currency: string;\n  status: string;\n};\n\ntype LedgerPage = {\n  query: {\n    currency: string;\n    status: string;\n    booked_on: string;\n    amount_minor_gt: number;\n  };\n  total: number;\n  has_more: boolean;\n  next_cursor: number | null;\n  sum_amount_minor: number;\n  rows: LedgerRow[];\n};\n```\n\nWhen the user changes a filter, start again from the first page. Do not reuse a cursor that was built for a different query. And do not invent page numbers in the UI if the API does not have a stable total in that sense; `has_more` and `total` are enough for an agent, and usually enough for a grid.\n\nThe payload is only half of the contract. The tool's input should look like the filters a data-heavy table already sends to its API, not like `fetchLedger()`. If the model wants posted EUR lines in November over 10,000, it should pass those values in. The server applies them, the way `matches_query` does above, and returns a page. The model should not receive a thousand rows and then pretend to be a database. That is the same lesson a data-heavy UI already learned: do not ship the whole dataset to the browser and filter it in a `useMemo` if the API can do the work.\n\nThis also keeps later turns cheaper. A compact page of 25 rows is easier to evict, summarise, or ignore than a 200,000-token blob that now sits in the history. If you later add a mode where the model writes a small script to call tools in a sandbox, the same rule applies: intermediate results can stay out of the conversation, but only if they were never huge to begin with.\n\n**Pretty-printing is not free.** `indent=2` turned a 161,366-token compact dump into 236,366 tokens. Logs and debug prints are a common way this sneaks into a tool result.\n\n**Projection is not a substitute for a query.** Sending every row with fewer fields is still sending every row. If the question has a filter, run the filter on the server.\n\n**Do not hide the rest.** If 46 rows match and you only return 25, say so with `total` and `has_more`. A short \"here are some results\" payload that does not admit it is a page will make the model invent a complete answer.\n\n**Be honest about the tokenizer.** I measured with tiktoken. If you ship against Claude or another model, count with that vendor's tokenizer before you treat a saving as a budget line. The ranking of these shapes should hold; the exact integers will move.\n\n**Do not put the whole table in the system prompt \"for reference.\"** A tool result you can page is cheaper than a prefix you pay for on every later turn, even when a cache hits part of it.\n\n**Keep the tool list small, or load schemas on demand.** This article is about the payload, not the tool catalogue. The catalogue matters too, but shrinking a 236,000-token result comes first.\n\nIf I am attaching an agent to a screen I already know, I would not expose the table's list endpoint as a tool. I would expose a query: filters the server can apply, a projected page, a total, and a way to fetch one row by id. I would count a real response with tiktoken before I shipped it. And I would keep the UI payload and the tool payload as two views of the same data, not one JSON blob that tries to serve both.\n\nThe model can still be wrong. It just no longer has to be wrong with a hundred thousand tokens of leftover columns in the way.\n\nI'm Aran Shayan, a frontend developer at SOHA who builds data-heavy interfaces and the APIs behind them. More at [aranshayan.com](https://aranshayan.com).", "url": "https://wpnews.pro/news/don-t-send-the-whole-table-to-the-model-cutting-agent-tokens-on-data-heavy-apis", "canonical_source": "https://dev.to/aranshayan/dont-send-the-whole-table-to-the-model-cutting-agent-tokens-on-data-heavy-apis-4cme", "published_at": "2026-11-26 14:39:26+00:00", "updated_at": "2026-11-26 14:45:37.135032+00:00", "lang": "en", "topics": ["ai-agents", "large-language-models", "ai-tools"], "entities": ["OpenAI", "Anthropic", "Claude", "tiktoken"], "also_reported_by": [], "takeaway": "Projecting ledger rows to six needed fields and server-filtering to a 25-row page with totals cut a 1,000-row payload from 236,366 tokens to 1,028 under o200k_base, versus 39,329 for projection alone.", "recommendation": {"advice": "Filter and project data server-side before returning tool results to an agent: a 25-row projected page with totals cost 1,028 tokens versus 236,366 for the full pretty-printed dump.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/don-t-send-the-whole-table-to-the-model-cutting-agent-tokens-on-data-heavy-apis", "markdown": "https://wpnews.pro/news/don-t-send-the-whole-table-to-the-model-cutting-agent-tokens-on-data-heavy-apis.md", "text": "https://wpnews.pro/news/don-t-send-the-whole-table-to-the-model-cutting-agent-tokens-on-data-heavy-apis.txt", "jsonld": "https://wpnews.pro/news/don-t-send-the-whole-table-to-the-model-cutting-agent-tokens-on-data-heavy-apis.jsonld"}}