Context Optimization Engine (COE)

Compact LLM context without losing facts. COE reorganizes and deduplicates RAG chunks, chat history, tools, and code before they reach the model.


Quick Pitch

While PCM optimizes instructions, COE optimizes context — the knowledge, data, and history you provide to the LLM. Unlike summarization tools that lose information, COE is deterministic: it removes redundancy and groups facts while preserving everything that matters.

Raw blocks → COE → compact prose → LLM

COE does NOT summarize. It removes redundancy and groups facts.


The Problem

When you provide context to an LLM, it often contains massive redundancy:

[Chunk A] Company: ACME / Juan works at ACME.
[Chunk B] Company: ACME / Budget: 50k / Juan approved the budget.
[Chunk C] Company: ACME / Pedro works at ACME.

The model wastes tokens (and your money) re-reading "Company: ACME" three times.


The Solution

COE transforms the above into:

Company: ACME
Juan works at ACME and approved the budget.
Budget: 50k
Pedro works at ACME.

Same facts, fewer tokens, better organization.


Token Savings & Quality

Benchmarked Results

Profile Case Before After Saved Factual Recall Comprehension
n1_n2_en acme_budget_v1 43 28 35% ≥ 0.95 ≥ 0.90
n1_n2_en acme_team_v1 19 13 32% ≥ 0.95 ≥ 0.90
n1_n2_es acme_budget_es_v1 44 29 34% ≥ 0.95 ≥ 0.90
n1_n2_zh acme_budget_zh_v1 24 13 46% ≥ 0.95 ≥ 0.90

Typical savings: 32-46% on context tokens with guaranteed quality thresholds.

See docs/benchmark-results.md for full methodology.


How It Works

Core Principle

COE doesn't generate new text. It reorganizes existing text using these strategies:

  1. Deduplication (Level 1) - Remove identical lines across chunks
  2. Entity Grouping (Level 2) - Group related facts about the same entity
  3. Relation Extraction (Level 3) - Identify relationships between entities
  4. Graph Slicing (Level 4) - Extract relevant subgraphs from knowledge graphs
  5. Session Memory (Level 5) - Maintain context across multi-turn conversations

What COE Processes

✅ RAG chunks — Document retrievals with overlap
✅ Chat history — Previous conversation turns
✅ Code snippets — Related code files
✅ Tool outputs — Function results and logs
✅ Structured data — JSON, CSV, database records
❌ Binary data — Images, audio, video (pass through)


Integration Options

Python Library (Recommended)

from coe import optimize_context
from coe.models import ContextBlock

response = optimize_context(
    [
        ContextBlock(id="A", content="Company: ACME\nJuan works at ACME.", source_type="rag"),
        ContextBlock(id="B", content="Company: ACME\nBudget: 50k\nJuan approved the budget.", source_type="rag"),
        ContextBlock(id="C", content="Company: ACME\nPedro works at ACME.", source_type="rag"),
    ],
    levels=[1, 2],
    locale="en",
)

print(response.text)
# Company: ACME
# Juan works at ACME and approved the budget.
# Budget: 50k
# Pedro works at ACME.

Docker + HTTP API

# Start the server
git clone https://github.com/ntnglz/Context-Optimization-Engine.git
cd Context-Optimization-Engine
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[http]"
python scripts/http/run_server.py

# Use it
curl -s -X POST http://127.0.0.1:8080/optimize \
  -H 'Content-Type: application/json' \
  -d @data/examples/http_optimize_rag.json

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 scripts/mcp/run_server.py

Add to .cursor/mcp.json:

{
  "mcpServers": {
    "coe": {
      "command": "/path/to/.venv/bin/python",
      "args": ["/path/to/Context-Optimization-Engine/scripts/mcp/run_server.py"]
    }
  }
}

CLI Quick Test

python run.py --demo          # Canonical EN RAG example
python run.py --quickstart    # Demo + copy-paste snippet
python run.py --test          # Run pytest suite

Choosing Optimization Levels

Level Guide

Levels What it does Best for Token Impact
[1] Line deduplication Simple repetition Low
[1, 2] Dedup + entity grouping Narrative RAG (default) Medium
[1, 2, 3, 4] + relations & graph slice Complex multi-entity High
[1, 2, 3, 4, 5] + session_id Full + session memory Multi-turn agents High

Common Configurations

# Conservative (minimal changes)
levels=[1]

# Balanced (recommended for most use cases)
levels=[1, 2]

# Aggressive (maximum compaction)
levels=[1, 2, 3, 4]

# With language unification
levels=[1, 2], l0=True, target_lang="en"

Language Support

COE supports multiple locales for optimal prose patterns:

Locale Support Notes
en ✅ Full English (default)
es ✅ Full Spanish
zh ✅ Full Chinese
fr ⚠️ Partial French (basic)
de ⚠️ Partial German (basic)

Language unification (l0=True) translates all context to a target language before optimization.


Use Cases

RAG Systems

Optimize retrieved documents before sending to LLM. Typical savings: 35-45%.

Chat Applications

Compact conversation history to fit more context in model window.

Code Analysis

Group related code snippets and remove duplicate imports/declarations.

Multi-agent Systems

Maintain coherent context across agent interactions with session memory.

Customer Support

Deduplicate customer information across multiple tickets and interactions.


When to Use COE

Scenario Recommended Reason
Context > 200 tokens ✅ Yes Worthwhile savings
Repetitive content ✅ Yes High redundancy
Multi-document RAG ✅ Yes Overlapping chunks
Long chat history ✅ Yes Repeated information
Need exact information ✅ Yes Preserves all facts

When NOT to Use COE

  • Context < 200 tokens — Below threshold, savings minimal
  • Need generative summary — COE is deterministic, not abstractive
  • Pure tabular data — Raw JSON/CSV better left unchanged
  • No context yet — COE optimizes text you already have, doesn't retrieve

PCM + COE: Better Together

User → PCM (instruction compression) → COE (context optimization) → LLM

Combined Savings Example

Component Original After PCM After PCM+COE Total Saved
Instruction 160 tokens 31 tokens 31 tokens 129 tokens
Context 95 tokens 95 tokens 55 tokens 40 tokens
Total 255 tokens 126 tokens 86 tokens 169 tokens (66%)

Real-world: Cursor-style dev session with RAG context.


Project Details

Aspect Details
Language Python 3.10+
License MIT
Status Active development
Stars GitHub
Documentation Full docs
Pair with Prompt Compression Middleware (PCM)

Architecture Overview

┌─────────────────────────────────────────────────────────────┐
│                       Your Application                          │
└─────────────────┬───────────────────────────────────┬───────┘
                  │                                       │
                  ▼                                       ▼
┌─────────────────────────────────────────────────────────────┐
│                      Context Blocks                           │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐            │
│  │  RAG Chunk  │  │ Chat History │  │  Code File   │            │
│  │    A        │  │     B        │  │      C      │            │
│  └─────────────┘  └─────────────┘  └─────────────┘            │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    COE Pipeline                               │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐      │
│  │   Ingest    │───▶│   Levels    │───▶│   Output    │      │
│  │  & Parse    │    │ Processing  │    │ Generation  │      │
│  └─────────────┘    └─────────────┘    └─────────────┘      │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    Optimized Context                          │
│              (Fewer tokens, same facts, better organized)    │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                      LLM Input                                 │
└─────────────────────────────────────────────────────────────┘

MIT License — Open source. Use responsibly.