This is a comprehensive design document for your Python package, llm-context-manager. You can use this directly as your project's README.md or as the architectural blueprint for development.
Project: llm-context-manager
1. Background & Problem Statement
Large Language Models (LLMs) are moving from simple "Prompt Engineering" (crafting a single query) to "Context Engineering" (managing a massive ecosystem of retrieved documents, tools, and history).
The current problem is Context Pollution:
- Overloading: RAG (Retrieval Augmented Generation) pipelines often dump too much data, exceeding token limits.
- Noise: Duplicate or irrelevant information confuses the model and increases hallucination rates.
- Formatting Chaos: Different models (Claude vs. Llama vs. GPT) require different formatting (XML vs. Markdown vs. Plain Text), leading to messy, hard-to-maintain string concatenation code.
- Black Box: Developers rarely see exactly what "context" was sent to the LLM until after a failure occurs.
The Solution: llm-context-manager acts as a middleware layer for the LLM pipeline. It creates a structured, optimized, and budget-aware "context payload" before it reaches the model.
2. Architecture: Where It Fits
The package sits strictly between the Retrieval/Agent Layer (e.g., LangChain, LlamaIndex) and the Execution Layer (the LLM API).
Diagram: The "Before" (Standard Pipeline)
Without llm-context-manager, retrieval is messy and often truncated arbitrarily.
graph LR
A[User Query] --> B[LangChain Retriever]
B --> C{Result: 15 Docs}
C -->|Raw Dump| D[LLM Context Window]
D -->|Token Limit Exceeded!| E[Truncated/Error]
Diagram: The "After" (With llm-context-manager)
With your package, the context is curated, prioritized, and formatted.
graph LR
A[User Query] --> B[LangChain Retriever]
B --> C[Raw Data: 15 Docs + History]
C --> D[**llm-context-manager**]
subgraph "Your Middleware"
D --> E["1. Token Budgeting"]
E --> F["2. Semantic Pruning"]
F --> G["3. Formatting (XML/JSON)"]
end
G --> H[Optimized Prompt]
H --> I[LLM API]
3. Key Features & Tools
Here is the breakdown of the 4 core modules, the features they provide, and the libraries powering them.
Module A: The Budget Controller (budget)
- Goal: Ensure the context never exceeds the model's limit (e.g., 8192 tokens) while keeping the most important information.
- Feature:
PriorityQueue. Users assign a priority (Critical, High, Medium, Low) to every piece of context. If the budget is full, "Low" items are dropped first. - Supported Providers & Tools:
- OpenAI (
gpt-4,o1,o3, etc.):tiktoken— fast, local token counting. - HuggingFace (
meta-llama/...,mistralai/...):tokenizers— for open-source models. - Google (
gemini-2.0-flash,gemma-...):google-genai— API-basedcount_tokens. - Anthropic (
claude-sonnet-4-20250514, etc.):anthropic— API-basedcount_tokens.
- OpenAI (
- Installation (pick what you need):
pip install llm-context-manager[openai] # tiktoken pip install llm-context-manager[huggingface] # tokenizers pip install llm-context-manager[google] # google-genai pip install llm-context-manager[anthropic] # anthropic pip install llm-context-manager[all] # everything
Module B: The Semantic Pruner (prune)
- Goal: Remove redundancy. If three retrieved documents say "Python is great," keep only the best one.
- Features:
Deduplicator(block-level): Calculates cosine similarity between context blocks and removes duplicate blocks. Among duplicates, the highest-priority block is kept.Deduplicator.deduplicate_chunks()(chunk-level): Splits a single block's content by separator (e.g.\n\n), deduplicates the chunks internally, and reassembles the cleaned content. Ideal for RAG results where multiple retrieved chunks within one block are semantically redundant.
- Tools:
FastEmbed: Lightweight embedding generation (CPU-friendly, no heavy PyTorch needed).Numpy: For efficient vector math (dot products).
- Installation:
pip install llm-context-manager[prune]
Module C: Context Distillation (distill)
- Goal: Compress individual blocks by removing non-essential tokens (e.g., reduces a 5000-token document to 2500 tokens) using a small ML model.
- Feature:
Compressor. Uses LLMLingua-2 (small BERT-based token classifier) to keep only the most important words. - Tools:
llmlingua: Microsoft's library for prompt compression.onnxruntime/transformers: For running the small BERT model.
- Installation:
pip install llm-context-manager[distill]
Module D: The Formatter (format)
-
Goal: Adapt the text structure to the specific LLM being used without changing the data.
-
Feature:
ModelAdapter. -
Claude Mode: Wraps data in XML tags (
<doc id="1">...</doc>). -
Llama Mode: Uses specific Markdown headers or
[INST]tags. -
Tools:
-
Jinja2: For powerful, logic-based string templates. -
Pydantic: To enforce strict schema validation on the input data.
Module E: Observability (inspect)
- Goal: Let the developer see exactly what is happening.
- Feature:
ContextVisualizerandSnapshot. Prints a colored bar chart of token usage to the terminal and saves the final prompt to a JSON file for debugging. - Tools:
Rich: For beautiful terminal output and progress bars.
4. Installation & Usage Guide
Installation
pip install llm-context-manager
Example Usage Code
This is how a developer would use your package in their Python script.
from context_manager import ContextEngine, ContextBlock
from context_manager.strategies import PriorityPruning
# 1. Initialize the Engine
engine = ContextEngine(
model="gpt-4",
token_limit=4000,
pruning_strategy=PriorityPruning()
)
# 2. Add Data (Raw from LangChain/User)
# System Prompt (Critical Priority)
engine.add(ContextBlock(
content="You are a helpful AI assistant for financial analysis.",
role="system",
priority="critical"
))
# User History (High Priority)
engine.add(ContextBlock(
content="User: What is the PE ratio of Apple?",
role="history",
priority="high"
))
# Retrieved Documents (Medium Priority - acting as 'Low' if space is tight)
docs = ["Apple PE is 28...", "Microsoft PE is 35...", "Banana prices are up..."]
for doc in docs:
engine.add(ContextBlock(
content=doc,
role="rag_context",
priority="medium"
))
# 3. BUILD THE CONTEXT
# This triggers the budgeting, pruning, and formatting
final_prompt = engine.compile()
# 4. INSPECT (Optional)
engine.visualize()
# Output: [██ system (10%) ][████ history (20%) ][██████ rag (40%) ][ unused (30%) ]
# 5. SEND TO LLM
openai.ChatCompletion.create(messages=final_prompt)
5. Roadmap for Development
- v0.1 (MVP): Implement
tiktokencounting andPriorityPruning. Just get the math right. - v0.2 (Structure): Add
Jinja2templates for "Claude Style" (XML) vs "OpenAI Style" (JSON). - v0.3 (Smarts): Integrate
FastEmbedto automatically detect and remove duplicate documents. - v0.4 (Vis): Add the
Richterminal visualization.
This design gives you a clear path to building a high-value tool that solves a specific, painful problem for AI engineers.
Metadata
Release files for llm-context-engineering 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| llm_context_engineering-0.1.0.tar.gz | 24.5 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| llm_context_engineering-0.1.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 46.7 kB
Release files / llm_context_engineering-0.1.0.tar.gz
| Download URL | llm_context_engineering-0.1.0.tar.gz |
|---|---|
| Size | 24.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
090ebaa6ed7b01f1d243ee4e1f2b47ea0abce098c7a2690a2c4eb2c5cf03aae1
|
|
BLAKE2b-256 checksum How to use checksums |
71900abe51d828cd8a08da2e97cf56918405b459bcf2c3d88852fb6528713d74
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.14
|
Release files / llm_context_engineering-0.1.0-py3-none-any.whl
| Download URL | llm_context_engineering-0.1.0-py3-none-any.whl |
|---|---|
| Size | 22.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
cb16a5effca827a21c97518b85ed21976cbc5cb01955e1f2fee72a64bd5897be
|
|
BLAKE2b-256 checksum How to use checksums |
26564605c2ba8eb3a947d1f97794ed22c6b1c73939811a0d1895910c534912a9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.14
|
Security for llm-context-engineering 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.