Heuristic:AMAP ML SkillClaw Context Truncation Strategy
| Knowledge Sources | |
|---|---|
| Domains | Optimization, LLMs |
| Last Updated | 2026-10-22 00:00 GMT |
Overview
Context truncation strategy that preserves system messages and the newest user message while dropping oldest non-system messages to fit within token budget.
Description
When the estimated prompt token count exceeds `max_prompt_tokens`, SkillClaw drops the oldest non-system messages one at a time until the budget is met. System messages (including injected skill catalogs) are always preserved — they contain critical behavioral rules. The newest message is also always kept (the loop condition `len(non_sys) - dropped > 1` ensures at least one non-system message remains). A dependency-free token estimator (`_estimate_openai_body_input_tokens`) is used — no tiktoken call per truncation step — making it fast and side-effect free.
Usage
Use this heuristic when agent conversations grow long and exceed the context window limit. It is applied automatically in `SkillClawAPIServer._truncate_messages` before forwarding to the upstream LLM.
The Insight (Rule of Thumb)
- Action: Split messages into system and non-system; drop oldest non-system messages iteratively until under budget.
- Value: Always keep: all system messages + the single newest non-system message. Drop from the oldest end.
- Trade-off: Loses early conversation context (which may contain important task setup), but preserves the current instruction and all behavioral rules.
- Compatibility: Uses a dependency-free token estimator (no external API calls); works with any OpenAI-compatible endpoint.
Reasoning
System messages contain injected skill catalogs and behavioral rules that are essential for correct agent behavior — losing them would cause the agent to forget how to use skills. The newest message is what the user/agent is currently working on. Older messages are the least likely to be directly referenced and can be sacrificed first. The iterative approach (drop one, re-check) ensures minimal context loss — only as many messages as needed are removed.
Code Evidence
Truncation logic from `skillclaw/api_server.py:3137-3180`:
def _truncate_messages(self, messages, tools, max_prompt_tokens):
def _prompt_len(msgs):
return _estimate_openai_body_input_tokens({"messages": msgs, "tools": tools})
original_tokens = _prompt_len(messages)
if original_tokens <= max_prompt_tokens:
return messages
sys_msgs = [m for m in messages if m.get("role") == "system"]
non_sys = [m for m in messages if m.get("role") != "system"]
dropped = 0
while len(non_sys) - dropped > 1:
dropped += 1
candidate = sys_msgs + non_sys[dropped:]
if _prompt_len(candidate) <= max_prompt_tokens:
break
result = sys_msgs + non_sys[dropped:]
if dropped:
logger.info(
"[OpenClaw] context truncated: dropped %d oldest messages (%d -> %d est tokens, limit=%d)",
dropped, original_tokens, _prompt_len(result), max_prompt_tokens,
)
return result