PIXELBANKv9.1.0
Menu

Estimate Token Count of a Message List

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:
  • Process the first message with content "hello" (length 5): estimate tokens as ⌈5/4⌉+3=2+3=5\lceil 5/4 \rceil + 3 = 2 + 3 = 5, adding the character-based estimate plus the fixed overhead.
  • Process the second message with content "world!!" (length 7): estimate tokens as ⌈7/4⌉+3=2+3=5\lceil 7/4 \rceil + 3 = 2 + 3 = 5, applying the same ceiling division and overhead logic.
  • Sum the individual message costs to get the total context estimate: 5+5=105 + 5 = 10.
  • The final output is 10

Constraints:

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

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

0/0
Run code to see test results.