BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / LLM inference and serving1 of 36 in topic

427. Trim a chat history to fit the context window

EasyLLM inference and serving

Every model has a context window: a maximum number of tokens it can read at once. Chat apps keep the system prompt, then fit in as many of the most recent messages as they can.

Write fit_history(messages, budget, count_tokens) where messages is a list of dicts like {"role": "user", "content": "..."}, messages[0] is always the system prompt, and count_tokens(text) returns the token count of a string.

Always keep the system prompt. Then walk backwards from the newest message, keeping each message while the running total stays within budget. Stop at the first message that does not fit (do not skip over it to grab older ones). Return the kept messages in their original order.

If the system prompt alone is over budget, return just the system prompt.

Functiondef fit_history(messages, budget, count_tokens)

Example 1

Input: fit_history([{'role': 'system', 'content': 'be brief'}, {'role': 'user', 'content': 'hi there'}, {'role': 'assistant', 'content': 'hello'}], 3, lambda t: len(t.split()))

Output: [{'role': 'system', 'content': 'be brief'}, {'role': 'assistant', 'content': 'hello'}]

Constraints

  • Python 3 standard library. Code runs in your browser.
  • Your code must pass all 4 tests to be accepted.
Hint 1

Count the system prompt first.

Hint 2

Walk reversed(messages[1:]) and break at the first message that does not fit, then reverse what you kept.

Understand the idea

A model can only read a fixed number of tokens, so a chat app must decide which messages to keep. The system prompt always stays. Then you add messages starting from the newest, because recent turns matter most, and stop as soon as one does not fit. You do not skip over a large message to grab older small ones, because that would leave a gap in the conversation.

Worked example

budget 10. System prompt is 3 tokens. Other messages, oldest to newest, are m1 = 4, m2 = 5, m3 = 2 tokens. Start at 3. Add m3: total 5. Add m2: total 10, still within budget. Try m1: total 14, too big, so stop. Return [system, m2, m3] in original order. If the system prompt alone is over budget, return only it.

keep system, walk backwards adding while running total <= budget, stop at the first failure, then restore order

Every chat product built on an LLM API needs this trimming.

Topics
LLM inference and serving
Similar questions
  • Work out how many tokens fit in GPU memory for the KV cacheEasy
  • Compute TTFT, TPOT and throughput from request timestampsEasy
  • Price an API request with cached input tokensEasy
  • Size concurrency with Little's lawEasy
All LLM inference and serving problems
Report
427 / 903
Python 3solution.pyPython idle
1
2
3
4
def fit_history(messages, budget, count_tokens):
# your code here
pass
​
[m["content"] for m in fit_history(_msgs, 14, _ct)]

This case uses generated data, so it runs as written. Press + to add your own case.

Run checks these cases in your browser, no sign-in needed. Submit checks all 4 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS