Observed since 20 Oct, 19:07 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
Task-aware dynamic prompt compression using LinUCB Contextual Bandits with first-class OpenAI support.
Sub-millisecond dynamic LLM context optimization via Contextual Multi-Armed Bandits (LinUCB).
Cut prompt token costs by 25% to 45% with 100% guaranteed AST code integrity, zero GPU overhead (< 5MB RAM), and microsecond routing latency (< 100 µs).
| Dimension | Standard Raw OpenAI Call | With Adaptive-Prompt-Compressor | Advantage / Impact |
|---|---|---|---|
| Token Cost | 100% (Full retail tokens) | 64% – 75% of original tokens | 25% – 36% Direct Cost Reduction |
| Routing Latency | N/A | 38 µs – 94 µs (< 0.0001s) | Zero detectable pipeline overhead |
| Hardware Required | None | < 5MB RAM (Pure CPU) | Runs on serverless, edge, microservices |
| Code & AST Syntax | 100% valid | 100.0% Valid (Syntax-Guarded AST) | Zero broken code or syntax crashes |
| OpenAI Prompt Caching | Fragile to minor prompt shifts | Prefix-invariant caching alignment | Stacks with OpenAI 50% Cache Discount |
| Policy Adaptability | Static | Online learning via LinUCB Bandits | Adapts dynamically to task complexity |
# Raw Prompt (48 tokens):
"""
Hello assistant! Could you please write a quick Python function that calculates
the factorial of a given integer n? Make sure to handle n=0 properly. Thanks!
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
"""
# Compressed Output via Arm 1 (29 tokens -> 39.6% Reduction, 100% AST Passed):
"""
Write Python function calculating factorial of integer n. Handle n=0.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
"""
Notice: Conversational padding is aggressively pruned, while Python code syntax and docstrings remain 100% syntactically intact.
Adaptive-Prompt-Compressor is engineered as a zero-friction, native companion for modern OpenAI architectures (GPT-4o, GPT-4o-mini, o1/o3, and Codex agents):
OpenAI() client with wrap_openai_client(client). All chat completions and prompt transmissions are compressed on-the-fly without altering existing downstream codebase logic.Existing prompt compressors (e.g., Microsoft LLMLingua, LLMLingua-2, Selective-Context) rely on running secondary transformer models (like LLaMA-7B or mBERT) to score token perplexity. While mathematically elegant, this introduces heavy production bottlenecks:
| Metric / Dimension | Microsoft LLMLingua / LLMLingua-2 | Static Rule Compressors | Adaptive-Prompt-Compressor (Ours) |
|---|---|---|---|
| Routing / Compression Latency | High (50 ms – 150 ms inference) | Ultra-low (~15 µs) | Ultra-low (< 100 µs / < 1 ms) |
| Hardware & Memory Footprint | Heavy GPU required (2GB–8GB VRAM) | Minimal CPU (< 1MB) | Zero GPU required (< 5MB RAM) |
| Code & AST Syntax Integrity | ❌ Drops critical tokens; breaks code | ❌ Strips operators / strings | ✅ 100% AST Safe (Syntax-Guarded) |
| OpenAI Prompt Cache Co-Optimization | ❌ Mutates prefix; cache misses | ❌ Mutates prefix | ✅ Cache-Aware Prefix Preservation (50% Off) |
| Policy Adaptability | Static (Frozen model weights) | Fixed heuristics | ✅ Online Learning (Adapts via LinUCB Bandits) |
| Deployment Environments | Dedicated GPU server only | Universal | Edge, Serverless, Cloudflare, RasPi, K8s |
Run our empirical reproduction benchmark anytime:
uv run python scripts/compare_sota_compressors.py
| Figure 1: Online Convergence & Regret Minimization | Figure 2: Task-Aware Strategy Distribution |
|---|---|
![]() | ![]() |
| LinUCB rapidly converges within 150 trials, maximizing cumulative reward across diverse task distributions. | Autonomous strategy routing: Conservative for Code (Arm 0), Moderate for RAG (Arm 1), Aggressive for Chat (Arm 2). |
| Figure 3: Quality-Cost Pareto Frontier | Figure 4: LinUCB Feature Interpretability (XAI) |
|---|---|
![]() | ![]() |
| Dominates static compression baselines by maintaining >0.93 semantic fidelity while saving up to 42.5% tokens. | Learned θ weights explain bandit reasoning: 'Codeness' penalizes aggressive pruning to safeguard executable syntax. |
| Task / Workload Category | Token Reduction (%) | AST Code Valid (%) | Routing Overhead | Semantic Score | Preferred Strategy |
|---|---|---|---|---|---|
| Code Generation & Syntax | 2.1% | 100.0% | 94.1 µs | 0.961 | Arm 0 (Conservative) |
| System Instructions & RAG Context | 24.8% | N/A | 49.7 µs | 0.938 | Arm 1 (Moderate) |
| Conversational Chat & Summarization | 42.5% | N/A | 38.6 µs | 0.918 | Arm 2 (Aggressive) |
| Enterprise Mixed Workload Blend | 31.4% Avg | 99.8% Reliability | < 100 µs | 0.932 | Task-Aware Adaptive |
Evaluated across canonical HumanEval algorithmic tasks (scripts/benchmark_humaneval_ast.py):
| HumanEval Task ID | Task Description | Tokens In | Tokens Out | AST Parse Valid | Unit Test Pass | Routing Overhead |
|---|---|---|---|---|---|---|
| HumanEval/0 | Has Close Elements | 98 | 98 | ✅ 100% | ✅ Pass | 117.5 µs |
| HumanEval/1 | Separate Paren Groups | 139 | 139 | ✅ 100% | ✅ Pass | 53.7 µs |
| HumanEval/2 | Truncate Number | 56 | 56 | ✅ 100% | ✅ Pass | 39.9 µs |
| HumanEval/3 | Below Zero Balance | 79 | 79 | ✅ 100% | ✅ Pass | 40.0 µs |
| HumanEval/4 | Mean Absolute Deviation | 72 | 72 | ✅ 100% | ✅ Pass | 35.3 µs |
| HumanEval/5 | Intersperse List | 85 | 85 | ✅ 100% | ✅ Pass | 33.7 µs |
| HumanEval/6 | Parse Nested Parens | 126 | 126 | ✅ 100% | ✅ Pass | 36.8 µs |
| HumanEval/7 | Filter Strings by Substring | 52 | 52 | ✅ 100% | ✅ Pass | 31.3 µs |
| HumanEval/8 | Sum and Product of List | 83 | 83 | ✅ 100% | ✅ Pass | 33.2 µs |
| HumanEval/9 | Rolling Maximum | 89 | 89 | ✅ 100% | ✅ Pass | 33.5 µs |
| Overall Metric | 10 Programming Tasks | 879 Tokens | 879 Tokens | 100.0% Syntax Pass | 100.0% Functional Pass | 45.5 µs Avg Latency |
Key finding: LinUCB autonomously routes technical code to Arm 0 (Conservative), guaranteeing zero syntax truncation and 100% functional pass rate.
synchronous_commit, RPO=0, Patroni) with sub-millisecond overhead.Install via pip or uv:
git clone https://github.com/howwang0507/Adaptive-Prompt-Compressor.git
cd Adaptive-Prompt-Compressor
uv sync
Use transparently in your OpenAI pipeline:
from openai import OpenAI
from src.integrations.openai_client import wrap_openai_client
# Seamlessly wrap your standard OpenAI client
client = wrap_openai_client(OpenAI())
# Standard completions call - automatically compressed prior to transmission
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a code optimization assistant."},
{"role": "user", "content": "Could you please implement a distributed lock in Redis..."}
]
)
print(response.choices[0].message.content)
print(response.compression_meta) # {'char_savings_pct': 38.4, 'strategies': ['Moderate'], ...}
Test and benchmark compression directly from your terminal with microsecond-level latency:
# Compress a single prompt with instant metrics
uv run python -m src.cli "def calculate_statistics(data): ..."
# Run the automated empirical benchmark suite
uv run python -m src.cli --benchmark
Run the end-to-end interactive demo in Jupyter or Google Colab:
uv run jupyter notebook examples/openai_cookbook_showcase.ipynb
Walks through LinUCB contextual routing across Code, Technical Documentation, and Conversational Chat, with live tiktoken accounting and USD cost telemetry.
Launch the visual parameter-tuning UI and Redis Fleet Learning simulator:
# Option A: Run locally with uv
uv run streamlit run src/app.py
# Option B: One-click Docker Compose
docker-compose up -d
# Navigate to http://localhost:8501
graph TD
A["Raw User / RAG Prompt"] --> B["12-D Feature Extraction (SBERT + Structural)"]
B --> C["LinUCB Contextual Bandit Policy (Sherman-Morrison O(d^2))"]
C -->|Code / Critical Syntax| D["Arm 0: Conservative (Preserve Code & Logic)"]
C -->|Moderate Complexity| E["Arm 1: Moderate (Whitespace & Syntax Pruning)"]
C -->|Conversational / Summarization| F["Arm 2: Aggressive (Stopword & Filler Elimination)"]
D & E & F --> G{"AST Syntax Guard"}
G -->|Valid| H["OpenAI GPT-4o / LLM Execution"]
G -->|Invalid| D
H --> I["Dual-Track Reward (Token Savings vs Semantic Fidelity)"]
I -->|Online Feedback| C
Built for enterprise-grade LLM inference:
ast.parse(). If compression introduces any syntactic defect, the system automatically falls back to Arm 0 (Conservative), guaranteeing zero runtime crashes in LLM code-generation pipelines.mcp_server/) provides standard tool endpoints for Claude Desktop, Cursor, and custom agentic frameworks.Adaptive-Prompt-Compressor/
├── src/ # Core Architecture & Integrations
│ ├── integrations/ # OpenAI SDK 1-Line Drop-in Wrapper
│ │ └── openai_client.py # wrap_openai_client implementation
│ ├── agent.py # LinUCB Contextual Bandit (Sherman-Morrison O(d^2))
│ ├── interface.py # High-level LinUCB Compressor Interface
│ ├── environment.py # Multi-provider Simulation & API Execution
│ ├── utils.py # Dual-track Reward & Semantic Metrics
│ ├── app.py # Streamlit Interactive Dashboard
│ ├── cli.py # Microsecond Terminal CLI Tool
│ └── telemetry.py # Server-Sent Events (SSE) Telemetry Server
├── scripts/ # Reproducible Benchmarking & Experiments
│ ├── compare_sota_compressors.py # SOTA vs. LLMLingua & Baseline Benchmark
│ ├── visualize_weights.py # Feature Importance Heatmap Generator
│ └── run_large_scale_benchmark.py # Scaled 1,000+ trial evaluation
├── assets/ # High-Resolution Empirical Visualizations
│ ├── figure_1_convergence.png # Convergence & Regret curves
│ ├── figure_2_distribution.png # Strategy distribution across categories
│ ├── figure_3_pareto.png # Quality-Cost Pareto frontier
│ └── figure_4_weights.png # Feature importance heatmap (XAI)
├── mcp_server/ # Model Context Protocol (MCP) Server
├── tests/ # Comprehensive Pytest Suite (100% Green CI)
├── latex/ # Academic Paper Manuscript (LaTeX/PDF)
├── Dockerfile # Containerized Deployment Environment
├── pyproject.toml # Modern dependency configuration (uv)
└── CITATION.cff # Academic citation metadata
wrap_openai_client).mcp_server/).We welcome contributions from researchers and engineers across the open-source community!
@article{Wang2026Adaptive,
title={Adaptive Prompt Compression via Contextual Bandits: Balancing Token Cost and Semantic Fidelity in Resource-Constrained Environments},
author={MINGHAO WANG},
journal={GitHub Repository},
year={2026},
url={https://github.com/howwang0507/Adaptive-Prompt-Compressor}
}
Developed for robust, enterprise-grade LLM inference optimization.
Download counts and popularity will appear here as the collector receives them.
| Version | Published | Direct dependencies | Open version |
|---|---|---|---|
| 1.1.1 | 12 Sept 2026 | 20 |
This describes our collected data; it is not a security assessment.
Shared repository data · GitHub
Observed since 20 Oct, 19:07 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
package:1e895694a11fcb9868309de272b2e63a06b07c5cf92250e3eee0e70880d11858