Trim a conversation to a budget

Trim a conversation to a budget

Sierra LLM Interview Question

A support agent's conversation grows until it no longer fits in the model's context. The usual fix is to drop the oldest turns while keeping the system prompt, which holds the instructions the agent needs on every call.

Write a function trim(messages, budget) that returns the messages to send. Always keep a message whose role is system, wherever it sits. Then keep as many of the most recent other messages as fit in what is left of the budget, stopping at the first that does not fit, and return everything in the original order. A system prompt larger than the budget on its own is still kept, and nothing else is.

Asked of

  • AI Engineer
  • ML Engineer
  • Data Scientist

Example 1

Input

messages = [{"role": "system", "tokens": 10}, {"role": "user", "tokens": 30}, {"role": "assistant", "tokens": 20}, {"role": "user", "tokens": 15}], budget = 50

Output

[{"role": "system", "tokens": 10}, {"role": "assistant", "tokens": 20}, {"role": "user", "tokens": 15}]

Example 2

Input

messages = [{"role": "system", "tokens": 99}], budget = 10

Output

[{"role": "system", "tokens": 99}]

Explanation

In the first example the system message takes 10 of the 50 tokens. Walking back from the end, the last two messages take 15 and 20, which fits in the 40 that remain; the one before them needs 30 more and does not.

Submit also runs 2 hidden test cases that check edge cases.

Similar questions