Deep dive 7 of 27: Token Counting Middleware
Nov 19, 2026 · Michael Chang · Status in NurseOps Now: ⬜ not built (illustrative)
Show definitions in ( ) · hover a highlighted word for its meaning, click it for details · open with ?defs=1 to show definitions
Part of: Remembering the right things: state management in NurseOps Now, section Implementing Short-Term Memory: Token Budgets and Window Management (7.1) · All 27 solutions · ← Agentic Outcome: Strict State Serialization · Dynamic Context Loading →
Read in this order
- In plain words: what it is, without jargon
- The problem it solves: the problem, and the standard approach in my words
- How to implement it (ServiceApps): scenario, steps, code and real output
- In NurseOps Now: built or not, and where
- Trade-offs and Interview answer
In plain words
Token counting middleware (code that counts tokens before every AI call and acts when the window gets too full) is a small check that runs before every AI call: it counts how full the window is and decides what to do, from "send as is" to "summarize now". It turns a silent failure into a planned one.
In plain terms: a fuel gauge with warning lights at 70%, 85% and 95%, instead of finding out when the engine stops.
The problem it solves
The token window is a hard limit (everything sent to the AI shares one fixed size budget), Sliding window truncation (silently dropping the oldest messages when the window is full) and Worse answers near capacity (a very full window makes the AI miss details in the middle): without counting, you only find out the window is full when something gets cut or the answers get worse.
The standard approach (in my words): put a pre-flight token (the unit the AI reads and is billed by, about three quarters of a word) check before every API call, with thresholds (the cut-off a score must stay above) that trigger stronger compression as the window fills.
How to implement it (ServiceApps)
Illustrative example: no ServiceApps (a company platform for IT tickets, HR requests and help-center articles) instance is connected, so the scenario and data are made up. The code is a self-contained sketch; it was run on that made-up data on Nov 19, 2026, and the output below is from that run.
The setting. ServiceApps (a company platform for IT tickets, HR requests and help-center articles) Assist, an AI helper inside a company's ServiceApps (a company platform for IT tickets, HR requests and help-center articles) portal. Employees ask it IT and HR questions; it answers from knowledge-base (KB (knowledge base: a library of help articles)) articles, looks up the employee's own tickets (incidents (a ServiceApps ticket for something broken) like INC0012345) and requests, and keeps one conversation per employee and ticket.
The scenario. A long ServiceApps (a company platform for IT tickets, HR requests and help-center articles) Assist chat grows to 43 messages against a 4,000-token window.
Steps.
- Count the tokens (pieces of words the AI reads and writes; cost is per token) of everything you're about to send (use the provider (the doctor or clinic asking for the test)'s count-tokens API in production).
- Compare with the model's limit and pick a level: OK, NOTICE (70%), WARNING (85%), CRITICAL (95%).
- Act per level: drop old turns, summarize, or summarize hard and trim tool (a function the AI can call, such as policy search) output.
- Log the level and action for every call.
The code (Python):
LIMIT = 4000
def count_tokens(messages): # rough: ~4 characters per token; use the real API in production
return sum(-(-len(m["content"]) // 4) for m in messages)
def check_budget(messages, limit=LIMIT):
u = count_tokens(messages) / limit
if u > 0.95: return u, "CRITICAL", "summarize hard, trim tool output"
if u > 0.85: return u, "WARNING", "summarize the oldest turns"
if u > 0.70: return u, "NOTICE", "drop the oldest turns"
return u, "OK", "send as is"
def middleware(messages, send):
u, level, action = check_budget(messages)
print(f"{len(messages):3d} msgs {u:5.0%} {level:8s} -> {action}")
if level in ("WARNING", "CRITICAL"):
messages = messages[-6:] # stand-in for summarizing
return send(messages)
chat = []
for i in range(1, 44):
chat.append({"role": "user", "content": "x" * 360})
if i in (10, 20, 33, 38, 43):
middleware(list(chat), send=lambda m: len(m))
Output (from running the code above):
10 msgs 22% OK -> send as is 20 msgs 45% OK -> send as is 33 msgs 74% NOTICE -> drop the oldest turns 38 msgs 86% WARNING -> summarize the oldest turns 43 msgs 97% CRITICAL -> summarize hard, trim tool output
What to watch for.
- Count everything: rules, tools (a function the AI can call, such as policy search)' descriptions, tool (a function the AI can call, such as policy search) results and history, not just the chat.
- Tune thresholds (the cut-off a score must stay above) per model; 70/85/95 are a starting point, not a standard.
- Make the action visible in logs, so you can see how often it fires.
In plain terms: before every call, glance at the fuel gauge and decide whether to keep driving, refuel, or stop.
In NurseOps Now
Not built. NurseOps Now records input and output tokens (pieces of words the AI reads and writes; cost is per token) after each call (llm_calls table), but nothing counts them before the call; the window is limited by turns instead. This is Plan 1.
Trade-offs
- A real count is an extra API call or a local tokenizer; a rough estimate is free but can be off.
- More levels give finer control but more paths to test.
Interview answer
"I'd add token counting middleware (code that counts tokens before every AI call and acts when the window gets too full) in front of every model call: count the full request with the provider (the doctor or clinic asking for the test)'s API, compare it with the limit, and act at thresholds (the cut-off a score must stay above), dropping or summarizing old turns before anything is silently cut. Each call logs its level, so we can tune it."
All data in this post is made up. No real people, tickets or patient data.
← Back to all 27 solutions in the state management blog
Key terms
Every highlighted word in this post links here. Click ↩ Back to return to the spot you came from.
- incident
- A ServiceApps ticket for something broken.Used in: How to implement it (ServiceApps)↩ Back to where you were
- KB
- Knowledge base: a library of help articles.Used in: How to implement it (ServiceApps)↩ Back to where you were
- provider
- The doctor or clinic asking for the test.Used in: How to implement it (ServiceApps), Interview answer↩ Back to where you were
- ServiceApps
- A company platform for IT tickets, HR requests and help-center articles.Used in: How to implement it (ServiceApps)↩ Back to where you were
- sliding window truncation
- Silently dropping the oldest messages when the window is full.Used in: The problem it solves↩ Back to where you were
- the token window is a hard limit
- Everything sent to the AI shares one fixed size budget.Used in: The problem it solves↩ Back to where you were
- threshold
- The cut-off a score must stay above.Used in: The problem it solves, How to implement it (ServiceApps), Interview answer↩ Back to where you were
- token
- The unit the AI reads and is billed by, about three quarters of a word.Used in: The problem it solves↩ Back to where you were
- token counting middleware
- Code that counts tokens before every AI call and acts when the window gets too full.Used in: In plain words, Interview answer↩ Back to where you were
- tokens
- Pieces of words the AI reads and writes; cost is per token.Used in: How to implement it (ServiceApps), In NurseOps Now↩ Back to where you were
- tool
- A function the AI can call, such as policy search.Used in: How to implement it (ServiceApps)↩ Back to where you were
- worse answers near capacity
- A very full window makes the AI miss details in the middle.Used in: The problem it solves↩ Back to where you were