A chat assistant resends the conversation on every turn, and the history must fit in a fixed token budget. Write the trimming step that drops the oldest turns while always keeping the system prompt.
Implement trim_history(messages, max_tokens).
messages: list of dicts {"role": ..., "content": ...} with role in "system", "user", "assistant", "tool", oldest first.max_tokens: int budget.The cost of one message is , where is the number of whitespace-separated words in its content (len(content.split())).
Rules:
"system" message is kept.max_tokens minus the cost of all system messages. If it is negative, return only the system messages."assistant" or "tool", drop it, so the kept window starts on a "user" turn (or is empty).Return the kept messages in their original order.