Observed since 20 Oct, 21:42 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
agent-context-manager
Lightweight context window management for AI agents
A lightweight Python library for managing LLM context windows in AI agents. Prevents context overflow, reduces token costs, and maintains conversation coherence.
AI agents face a critical challenge: context windows fill up fast. When they overflow:
Current solutions are either too complex (require LLM calls for summarization) or too naive (just truncate old messages).
agent-context-manager provides intelligent context compression without requiring additional LLM calls:
pip install agent-context-manager
from agent_context_manager import ContextManager, SlidingWindowStrategy
# Create a context manager with 8K token limit
manager = ContextManager(
max_tokens=8000,
strategy=SlidingWindowStrategy(keep_system=True, keep_recent=10)
)
# Add messages as your agent works
manager.add_message({"role": "system", "content": "You are a helpful assistant."})
manager.add_message({"role": "user", "content": "Hello!"})
manager.add_message({"role": "assistant", "content": "Hi there!"})
# Get compressed context when needed
context = manager.get_context()
# Check token usage
print(f"Tokens used: {manager.token_count}/{manager.max_tokens}")
Keeps the most recent N messages, always preserving system messages.
from agent_context_manager import SlidingWindowStrategy
strategy = SlidingWindowStrategy(
keep_system=True, # Always keep system messages
keep_recent=20, # Keep last 20 messages
keep_first_user=True # Keep the original user request
)
Scores messages by relevance and keeps the most important ones.
from agent_context_manager import ImportanceStrategy
strategy = ImportanceStrategy(
system_weight=1.0, # System messages always kept
user_weight=0.8, # User messages high priority
assistant_weight=0.6, # Assistant messages medium priority
tool_weight=0.4, # Tool results lower priority
recency_decay=0.95 # Recent messages score higher
)
Removes near-duplicate messages to reduce redundancy.
from agent_context_manager import DeduplicationStrategy
strategy = DeduplicationStrategy(
similarity_threshold=0.85, # Remove if >85% similar
keep_latest=True # Keep the most recent of duplicates
)
Combines multiple strategies for best results.
from agent_context_manager import HybridStrategy
strategy = HybridStrategy([
DeduplicationStrategy(similarity_threshold=0.9),
ImportanceStrategy(recency_decay=0.95),
SlidingWindowStrategy(keep_recent=50)
])
Built-in token counting for popular models:
from agent_context_manager import ContextManager
# Auto-detect tokenizer based on model
manager = ContextManager(max_tokens=8000, model="gpt-4")
manager = ContextManager(max_tokens=100000, model="claude-3")
# Or use a custom tokenizer
manager = ContextManager(
max_tokens=8000,
tokenizer=my_custom_tokenizer
)
from agent_context_manager import ContextManager, OverflowPolicy
manager = ContextManager(
max_tokens=8000,
overflow_policy=OverflowPolicy.COMPRESS, # Auto-compress when near limit
overflow_threshold=0.9 # Compress at 90% capacity
)
# Or get warnings instead
manager = ContextManager(
max_tokens=8000,
overflow_policy=OverflowPolicy.WARN
)
# Check status
if manager.is_near_overflow():
print(f"Warning: {manager.usage_percent}% of context used")
Organize context into logical blocks with size limits:
from agent_context_manager import ContextManager, MemoryBlock
manager = ContextManager(max_tokens=8000)
# Define memory blocks
manager.add_block(MemoryBlock(
name="system",
max_tokens=500,
priority=1.0, # Highest priority, never compressed
content="You are a helpful coding assistant."
))
manager.add_block(MemoryBlock(
name="user_profile",
max_tokens=200,
priority=0.9,
content="User prefers Python, uses VS Code."
))
manager.add_block(MemoryBlock(
name="conversation",
max_tokens=7000,
priority=0.5, # Can be compressed if needed
strategy=SlidingWindowStrategy(keep_recent=30)
))
# Update blocks as needed
manager.update_block("user_profile", "User prefers Python, uses VS Code, timezone: PST")
from openai import OpenAI
from agent_context_manager import ContextManager
client = OpenAI()
manager = ContextManager(max_tokens=8000, model="gpt-4")
manager.add_message({"role": "system", "content": "You are helpful."})
while True:
user_input = input("You: ")
manager.add_message({"role": "user", "content": user_input})
response = client.chat.completions.create(
model="gpt-4",
messages=manager.get_context() # Auto-compressed if needed
)
assistant_message = response.choices[0].message.content
manager.add_message({"role": "assistant", "content": assistant_message})
print(f"Assistant: {assistant_message}")
from anthropic import Anthropic
from agent_context_manager import ContextManager
client = Anthropic()
manager = ContextManager(max_tokens=100000, model="claude-3")
# Same pattern works with any provider
from langchain.memory import ConversationBufferMemory
from agent_context_manager import ContextManager, LangChainAdapter
manager = ContextManager(max_tokens=8000)
memory = LangChainAdapter(manager) # Drop-in replacement
| Method | Description |
|---|---|
add_message(msg) | Add a message to context |
get_context() | Get compressed context as message list |
token_count | Current token count |
usage_percent | Percentage of context used |
is_near_overflow() | Check if approaching limit |
compress() | Manually trigger compression |
clear() | Clear all messages |
| Strategy | Best For |
|---|---|
SlidingWindowStrategy | Simple agents, chatbots |
ImportanceStrategy | Complex agents with tool use |
DeduplicationStrategy | Repetitive workflows |
HybridStrategy | Production systems |
Contributions welcome! Please read CONTRIBUTING.md first.
MIT License - see LICENSE file.
Download counts and popularity will appear here as the collector receives them.
| Package / target | Requirement | Relationship |
|---|---|---|
tiktokenEnvironment{
"extras": "",
"marker": "extra == \"tiktoken\"",
"requires_python": ">=3.8",
"evaluation": "NOT_EVALUATED"
} | tiktoken>=0.5.0; extra == "tiktoken" | runtime |
anthropicEnvironment{
"extras": "",
"marker": "extra == \"anthropic\"",
"requires_python": ">=3.8",
"evaluation": "NOT_EVALUATED"
} | anthropic>=0.18.0; extra == "anthropic" | runtime |
pytestEnvironment{
"extras": "",
"marker": "extra == \"dev\"",
"requires_python": ">=3.8",
"evaluation": "NOT_EVALUATED"
} | pytest>=7.0.0; extra == "dev" | runtime |
pytest-covEnvironment{
"extras": "",
"marker": "extra == \"dev\"",
"requires_python": ">=3.8",
"evaluation": "NOT_EVALUATED"
} | pytest-cov>=4.0.0; extra == "dev" | runtime |
blackEnvironment{
"extras": "",
"marker": "extra == \"dev\"",
"requires_python": ">=3.8",
"evaluation": "NOT_EVALUATED"
} | black>=23.0.0; extra == "dev" | runtime |
mypyEnvironment{
"extras": "",
"marker": "extra == \"dev\"",
"requires_python": ">=3.8",
"evaluation": "NOT_EVALUATED"
} | mypy>=1.0.0; extra == "dev" | runtime |
bdist_wheel · 14.4 KB · Python py3
sdist · 18.75 KB · Python source
Shared repository data · GitHub
Observed since 20 Oct, 21:42 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
package_version:7b63fec3579ad0a1bdb891246b979a8bef0a889e52e26fca11f7b6dc4bcffc5d