Trim Chat History to Last K Messages (Keep System Prompt)

Basics
BasicsMemoryContext WindowOpenAIAnthropicGoogle

Problem

Implement trim_history(messages, k) that preserves every 'system' message in original order followed by the last k non-system messages in their original order.

Why It Matters: Sliding-window memory prevents long agent conversations from exceeding the LLM context window while ensuring core system instructions are never evicted.

Function Signature

def trim_history(messages: list[dict], k: int) -> list[dict]:
    """Keep all system messages plus the last k non-system messages."""

Sample Input & Output

Example 1: Keep System Prompt + Last 2 Turns

Input:

messages = [{"role": "system", "c": "s"}, {"role": "user", "c": "1"}, {"role": "assistant", "c": "2"}, {"role": "user", "c": "3"}], k = 2

Expected Output:

[{"role": "system", "c": "s"}, {"role": "assistant", "c": "2"}, {"role": "user", "c": "3"}]

Explanation: System message stays pinned at index 0; only the last 2 non-system messages ('2', '3') are kept.

Example 2: k = 0 Edge Case

Input:

messages = [{"role": "system", "c": "s"}, {"role": "user", "c": "1"}], k = 0

Expected Output:

[{"role": "system", "c": "s"}]

Explanation: Python's rest[-0:] would return the entire list—guard k == 0 explicitly to return only system messages!

Constraints & Edge Cases

  • Always preserve all system messages at the start.
  • Beware the classic Python bug rest[-0:] == rest! Explicitly handle k <= 0.
  • Do not mutate the original messages list.

Constraints & Evaluation Criteria

  • Always preserve all `system` messages at the start.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
1 system + 3 turns, k=2
Expected Output / Criteria
1 system + last 2 turns