context-window-management
Skill0 starsChanged 6 months agoMITView on GitHub
Shows how to manage an agent's context window using ShortTermMemory sliding-window trimming and manual message truncation helpers. Use when limiting token usage, implementing conversation history pruning, or estimating prompt sizes before sending to the LLM.
8 other projects use a version of this.
Adopted by
Most recently taken up by
- Wsh7Ash/skillmcptheir own version, first seen Nov 8, 2026
- xfstudio/skillstheir own version, first seen Oct 13, 2026
- varunk130/ai-workflow-playbookstheir own version, first seen May 22, 2026
- Fandry96/k3-agentic-skillstheir own version, first seen May 12, 2026
- hmzainjamil/claude-ai-skillstheir own version, first seen May 10, 2026
- tjennychen/claude-context-window-managementtheir own version, first seen May 2, 2026
Other versions8 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 8
- mlopscommunity/Coding-Agents-Conference-skills★ 38same name
- Fandry96/k3-agentic-skills★ 27same name
- xfstudio/skills★ 9same name
- hmzainjamil/claude-ai-skills★ 3same name
- ai4brands-design/claude-skills★ 2same name
- varunk130/ai-workflow-playbooks★ 2same name
- tjennychen/claude-context-window-management★ 0same name
- Wsh7Ash/skillmcp★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository65 other files it gives its agents.
- AGENTS.mdAGENTS.md
- skills/building-agents/agents.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- llms-full.txtllms.txt
- llms.txtllms.txt
- adding-guardrailsSkill
- agent-health-timeoutSkill
- agent-permission-scopingSkill
- agent-session-isolationSkill
- agent-step-loggingSkill
- agent-supervisor-routerSkill
- agent-telemetrySkill
- async-agent-backgroundSkill
- building-agentsSkill
- building-teamsSkill
- building-toolsSkill
- calendar-scheduling-toolSkill
- callback-tracing-handlerSkill
- chain-of-thought-promptingSkill
- chat-model-configurationSkill
- code-execution-sandboxSkill
- common-agent-patternsSkill
- conversation-memorySkill
- conversation-state-dbSkill
- database-query-toolSkill
- document-loadersSkill
- document-rerankingSkill
- email-notification-toolSkill
- embedding-model-ingestionSkill
- fallback-model-chainSkill
- few-shot-injectionSkill
- filesystem-toolSkill
- human-in-the-loopSkill
- hybrid-searchSkill
- inspecting-streamsSkill
- integrating-with-laurenSkill
- json-schema-enforcementSkill
- llm-provider-connectionSkill
- llm-rate-limitingSkill
- long-term-vector-memorySkill
- managing-memorySkill
- migrating-to-lauren-aiSkill
- multi-agent-delegationSkill
- multi-tool-orchestrationSkill
- multi-turn-tool-stateSkill
- output-guardrailsSkill
- plan-and-execute-agentSkill
- prompt-injection-defenseSkill
- prompt-versioningSkill
- rag-pipelineSkill
- react-agent-loopSkill
- response-validation-retrySkill
- rest-api-toolSkill
- securing-agentsSkill
- semantic-cacheSkill
- streaming-response-handlerSkill
- structured-output-parsingSkill
- sub-agent-spawningSkill
- system-prompt-templatingSkill
- testing-agentsSkill
- The first 60 shown.
The file
Files
Use
codemap find "SymbolName"to locate any symbol before reading — it gives exact file + line range and is faster than grep across the whole repo.
Agent Context Window Management & Trimming
Overview
ShortTermMemory automatically trims the oldest non-system messages when the
conversation grows beyond max_tokens. Configure it per-agent via
@agent(memory=ShortTermMemory(max_tokens=N)).
Configuring a sliding window
# agents.py — from __future__ import annotations is safe here
from __future__ import annotations
from lauren_ai import agent, ShortTermMemory
from lauren_ai._memory._stores import InMemoryConversationStore
@agent(
model="claude-opus-4-6",
system="You are a helpful assistant.",
memory=ShortTermMemory(max_tokens=4000),
conversation_store=InMemoryConversationStore(),
)
class ContextManagedAgent: ...ShortTermMemory.messages() returns a trimmed snapshot without mutating the
internal buffer. The oldest non-system messages are dropped first.
Manual trim helper
def trim_messages(messages: list[dict], max_turns: int = 10) -> list[dict]:
"""Keep system messages + the last *max_turns* user/assistant pairs."""
system = [m for m in messages if m.get("role") == "system"]
turns = [m for m in messages if m.get("role") != "system"]
if len(turns) > max_turns * 2: # *2 for user + assistant
turns = turns[-(max_turns * 2):]
return system + turnsToken estimation
def estimate_tokens(messages: list[dict]) -> int:
"""Rough token estimate — 4 chars ≈ 1 token."""
return sum(len(m.get("content", "")) // 4 for m in messages)ShortTermMemory.token_estimate uses the same heuristic internally.
When to use each approach
| Approach | When to use |
ShortTermMemory(max_tokens=N) | Automatic per-run sliding window |
trim_messages(msgs, max_turns=N) | Manual preprocessing before injecting history |
memory.trim_to_fit(max_tokens) | Mutate the buffer in-place (use sparingly) |
Full ShortTermMemory API
mem = ShortTermMemory(max_tokens=8000)
mem.add_user("Hello") # add a user message
mem.add_assistant(completion) # add a Completion or dict
mem.add_tool_result(result) # add a ToolResult
msgs = mem.messages() # trimmed snapshot
snap = mem.snapshot() # deep copy, no trimming
mem.restore(snap) # load a snapshot
mem.clear() # wipe the buffer
tok = mem.token_estimate # heuristic token countReference files
| File | Contents |
src/lauren_ai/_memory/__init__.py | ShortTermMemory implementation |
src/lauren_ai/_memory/_stores.py | InMemoryConversationStore |
src/lauren_ai/_agents/_runner.py | Memory creation and restore in run() |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

