Trim an Agent Conversation to a Token Budget Without Orphaning Tool Results
Last updated: November 29, 2026
Quick Overview
Given a chat history where each message has a role and a token count, return the longest recent suffix (plus all system messages) that fits a token budget, never keeping a tool result without the assistant message that requested it.
Ode
November 29, 20260
0
0 solved
Given a chat history where each message has a role and a token count, return the longest recent suffix (plus all system messages) that fits a token budget, never keeping a tool result without the assistant message that requested it.
Agents that Ode deploys for clients run long sessions with many tool calls, and the context window has to be managed explicitly. The interviewer is checking whether the candidate notices that model APIs reject a tool result whose tool call was dropped, and models the history as atomic units rather than individual messages.
What the Interviewer Expects
- Always keep system messages and charge them against the budget first
- Group each assistant tool-call message with the tool results that follow it
- Fill from the newest unit backwards and stop at the first unit that does not fit, so history stays contiguous
- Fail loudly when even the latest turn cannot fit
- Linear time in the number of messages
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Instead of dropping old turns, how would you summarize them, and when would you trigger summarization?
- What if a single tool result is huge, for example a 40k token database dump?
- Why not skip a large unit and keep an older small one?
- How would you test this against a real provider's validation rules?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Messages are dicts with role in {system, user, assistant, tool} and tokens. A tool message belongs to the closest preceding assistant message. Output preserves original order. Keep all system me...
High-Level Design
Two passes. First, separate system messages and build units: every non-tool message starts a new unit, every tool message appends to the current one. Second, walk units from newest to oldest, adding w...