Sliding Window Keeping the System Message
Problem Statement
Keep an agent's context small by retaining only the most recent turns — but never drop the leading system message, which sets the agent's instructions.
Background
A message list starts with an optional system message (role "system") followed by alternating user/assistant turns. A sliding window keeps the last k non-system messages. If the first message is a system message it is always preserved and prepended to the kept window.
Your Task
Implement:
def sliding_window(messages, k):
- If messages[0]["role"] == "system", always keep it.
- Keep the last k of the remaining (non-system-prefix) messages, in order.
- Return the new list.
Input Format
- messages: list of {"role", "content"} dicts.
- k (int): number of recent non-system messages to keep.
Output Format
- A list of message dicts.
Sample
msgs = [{"role":"system","content":"S"},{"role":"user","content":"a"},{"role":"assistant","content":"b"},{"role":"user","content":"c"}]
print(sliding_window(msgs, 2))
Output:
[{'role': 'system', 'content': 'S'}, {'role': 'assistant', 'content': 'b'}, {'role': 'user', 'content': 'c'}]
Example
msgs = [{"role":"system","content":"S"},{"role":"user","content":"a"},{"role":"assistant","content":"b"},{"role":"user","content":"c"}]
print(sliding_window(msgs, 2))[{'role': 'system', 'content': 'S'}, {'role': 'assistant', 'content': 'b'}, {'role': 'user', 'content': 'c'}]- Identify the leading system message: Since the first message has role
"system", it is separated and preserved as the prefixhead = [{"role":"system","content":"S"}]. - Isolate the remaining conversation turns: The non-system messages form the list
rest = [{"role":"user","content":"a"}, {"role":"assistant","content":"b"}, {"role":"user","content":"c"}], which has a length of 3. - Apply the sliding window constraint: With , we need the last 2 messages from
rest. Using the slice logic, we take elements from index to the end, resulting inkept = [{"role":"assistant","content":"b"}, {"role":"user","content":"c"}]. - Combine the preserved prefix with the recent window: Concatenate
headandkeptto form the final list[{"role":"system","content":"S"}, {"role":"assistant","content":"b"}, {"role":"user","content":"c"}]. - The final output is
[{'role': 'system', 'content': 'S'}, {'role': 'assistant', 'content': 'b'}, {'role': 'user', 'content': 'c'}]
Constraints
0 <= k <= len(messages).- Only a leading system message is special; system messages elsewhere are treated normally.
- Preserve original order.