v9.1.1
Menu

Estimate Token Count of a Message List

easyPROContext & Agent MemoryAI AgentsAI Agents 1

Problem Statement

Before sending messages to an LLM you need a cheap token estimate. Use the common heuristic that one token is roughly four characters of text, rounded up per message, then summed.

Background

Exact tokenization needs the model's tokenizer, but agents often gate context with a fast approximation: ceil(len(content) / 4) tokens per message, plus a small fixed per-message overhead for role/formatting markers. Summing these gives a conservative estimate used to decide whether to trim.

Your Task

Implement:

def estimate_tokens(messages, per_message_overhead=3):
  • messages: list of dicts each with a "content" string.
  • Each message costs ceil(len(content)/4) + per_message_overhead tokens.
  • Return the total as an int.

Input Format

  • messages (list of dicts), per_message_overhead (int).

Output Format

  • A single int.

Sample

print(estimate_tokens([{"content": "hello"}, {"content": "world!!"}]))

Output:

10

Example

Input
print(estimate_tokens([{"content": "hello"}, {"content": "world!!"}]))
Output
10
Reasoning
  • Input: a list of two messages whose "content" strings are "hello" (5 characters) and "world!!" (7 characters), with per_message_overhead left at its default of 3.
  • Text cost: each message's character count is divided by 4 and rounded up to a whole token. For "hello", 5/4=1.255/4 = 1.25 becomes ⌈1.25⌉=2\lceil 1.25 \rceil = 2; for "world!!", 7/4=1.757/4 = 1.75 also becomes 22.
  • Overhead: every message adds a flat 3 tokens for role and formatting markers, so each costs 2+3=52 + 3 = 5.
  • Output: the total over all messages, 5+5=105 + 5 = 10, a single integer.
  • Notice that rounding up happens per message, before summing. Pooling the text first would give ⌈12/4⌉=3\lceil 12/4 \rceil = 3 text tokens instead of 4, so the per-message rule is the more conservative estimate. Notice too that the overhead dominates short messages: with an overhead of 0 the answer would be just 4, and an empty list costs 0.

Constraints

  • 0 <= len(messages) <= 10000.
  • Per-message cost is ceil(len(content)/4) + per_message_overhead.
  • Return an int.

More from AI Agents 1

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.