Prompt Compression Middleware (PCM)

Compress natural-language instructions into compact PCM format before they reach your upstream LLM. Code blocks, documents, and other payloads pass through unchanged.


Quick Pitch

PCM is a pre-processing layer that sits between your application and your LLM API. It intercepts natural language instructions and compresses them into a token-efficient format, then forwards the optimized prompt to your LLM provider.

Client → PCM Proxy (:8090) → Mistral / OpenAI-compatible API
              ↓
         Ollama (local compressor: granite4.1:3b | pcm-granite)

The Problem

Natural language prompts are often verbose and repetitive:

"Please review this Python code very carefully for any potential race conditions,
memory leaks, or optimization opportunities that might exist. Then provide
a detailed Markdown report that lists all issues found, ordered by their
severity level from most critical to least important."

This is 48 tokens of instruction that could be conveyed in far fewer.


The Solution

PCM transforms the above into:

TASK=review INPUT=python CHECK=race,leak,perf FORMAT=markdown ORDER=severity

22 tokens — a 54% reduction while preserving all semantic meaning.


Token Savings

Real-world Examples

Case Original Compressed Savings
Dev triage prompt 160 tokens 31 tokens 81%
Code review request 85 tokens 24 tokens 72%
Data analysis ask 120 tokens 45 tokens 63%
General instructions 48 tokens 22 tokens 54%

Full message savings (instruction + payload):

  • Cursor-style dev session: 255 → 126 tokens (51% saved)

See PCM + COE guide for detailed benchmarks.


How It Works

Architecture

┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│   Client     │────▶│   PCM Proxy │────▶│   LLM API   │
│ (your app)   │     │  (:8090)    │     │ (Mistral, etc)
└─────────────┘     └─────────────┘     └─────────────┘
                              │
                              ▼
                     ┌─────────────┐
                     │  Ollama     │
                     │ (compressor)│
                     └─────────────┘

Compression Process

  1. Receive request from client
  2. Extract instruction from the message
  3. Compress using a fine-tuned model (granite4.1:3b)
  4. Reconstruct message with compressed instruction + original payload
  5. Forward to upstream LLM

What Gets Compressed

✅ Instructions — Natural language tasks and requests
✅ System prompts — Long contextual instructions
❌ Code blocks — Pass through verbatim
❌ Documents — Pass through verbatim
❌ JSON data — Pass through verbatim


Integration Options

Docker Proxy (Recommended for Production)

# Clone and start
git clone https://github.com/ntnglz/Prompt-Compression-Middleware.git
cd Prompt-Compression-Middleware
cp .env.example .env  # Set your MISTRAL_API_KEY
docker compose up --build

# Test it
curl http://localhost:8090/health

# Use it
curl http://localhost:8090/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"messages": [{"role": "user", "content": "Review this code..."}]}'

Local Proxy

pip install -e ".[dev]"
python run.py --proxy
# Listening on :8090

REST API (Compression Only)

python run.py --http
# POST /compress endpoint

curl -X POST http://localhost:8000/compress \
  -H "Content-Type: application/json" \
  -d '{"text": "Review this Python code for race conditions..."}'

Python Library

from pcm.compressor import compress_instruction

original = "Review this Python code carefully for race conditions..."
compressed = compress_instruction(original)
print(compressed)  # TASK=review INPUT=python CHECK=race FORMAT=markdown

MCP (Model Context Protocol)

For integration with Cursor, Claude Desktop, and other AI tools:

# Generate Cursor config
python scripts/mcp/print_cursor_config.py

# Run MCP server
python run.py --stdio  # For stdio
python run.py --mcp-http  # For HTTP MCP (:8001/mcp)

When to Use PCM

Scenario Recommended Reason
Prompts > 12 tokens ✅ Yes Threshold for activation
Long, verbose instructions ✅ Yes High savings potential
Already in PCM format ❌ Skip Detects TASK= prefix
Short prompts (< 12 tokens) ❌ Skip Below threshold
No upstream LLM ⚠️ Use REST/MCP Compression only mode

When NOT to Use PCM

  • Short prompts — Below 12 tokens are skipped automatically
  • Already compressed — Messages starting with TASK= are left as-is
  • No LLM upstream — Use POST /compress or MCP if you only need compression
  • Full context optimization needed — Pair with COE instead

Response Headers

PCM adds informative headers to responses:

Header Description
X-PCM-Messages-Compressed Number of messages compressed
X-PCM-Compression-Ratio Token savings ratio (0 if skipped)
X-PCM-Tokens-Saved Input tokens saved
X-PCM-Compression-Time-Ms Compression processing time
X-PCM-Upstream-Provider Provider (mistral, openai, etc.)
X-PCM-Upstream-Model Model used upstream

Disable per request: Add header x-pcm-disable: true


Quick Start

# Fastest (no Ollama, no API key):
git clone https://github.com/ntnglz/Prompt-Compression-Middleware.git
cd Prompt-Compression-Middleware
pip install -e ".[dev]"
python run.py --demo-stub

# Production (Docker + upstream):
cp .env.example .env  # Set MISTRAL_API_KEY
docker compose up --build
curl http://localhost:8090/health

Project Details

Aspect Details
Language Python 3.11+
License Research prototype
Status Active development
Stars GitHub
Documentation Full docs
Pair with Context Optimization Engine (COE)

Use Cases

Dev Tooling

Compress long instructions in IDE plugins, code review bots, and automated testing systems.

Customer Support

Optimize detailed support ticket analysis prompts.

Data Analysis

Compress complex analysis requests while preserving data payloads.

Chatbots

Reduce token usage in conversational AI systems with long system prompts.


Architecture Diagram

┌─────────────────────────────────────────────────────────────┐
│                         Your Application                        │
└─────────────────┬───────────────────────────────────┬───────┘
                  │                                       │
                  ▼                                       ▼
┌─────────────────────────────────────────────────────────────┐
│                    PCM Proxy (:8090)                         │
│  ┌─────────────┐         ┌─────────────┐         ┌────────┐ │
│  │  Receive    │         │  Compress   │         │Forward │ │
│  │  Request    │────────▶│ Instruction │────────▶│  to LLM│ │
│  └─────────────┘         └─────────────┘         └────────┘ │
│                        │                                      │
│                        ▼                                      │
│              ┌─────────────────────┐                        │
│              │   Local Compressor   │                        │
│              │   (Ollama + Model)   │                        │
│              └─────────────────────┘                        │
└─────────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                    Upstream LLM API                           │
│              (Mistral, OpenAI, etc.)                          │
└─────────────────────────────────────────────────────────────┘

Research prototype — use at your own risk. Not production-ready.