Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions litellm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1176,6 +1176,7 @@ def add_known_models(model_cost_map: Optional[Dict] = None):

## Lazy loading this is not straightforward, will leave it here for now.
from .main import * # type: ignore
from .compression import compress

# Skills API
from .skills.main import (
Expand Down
3 changes: 3 additions & 0 deletions litellm/compression/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from litellm.compression.compress import compress

__all__ = ["compress"]
232 changes: 232 additions & 0 deletions litellm/compression/compress.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
"""
Main compress() function — orchestrates BM25/embedding scoring, message stubbing,
and retrieval tool injection.
"""

from typing import Dict, List, Optional, Set

from litellm.caching.dual_cache import DualCache
from litellm.compression.message_stubbing import extract_key, stub_message, truncate_message
from litellm.compression.retrieval_tool import build_retrieval_tool
from litellm.compression.scoring.bm25 import bm25_score_messages
from litellm.litellm_core_utils.token_counter import token_counter
from litellm.types.compression import CompressedResult


def _extract_last_user_message(messages: List[dict]) -> str:
"""Return the text content of the last user message."""
for msg in reversed(messages):
if msg.get("role") == "user":
content = msg.get("content", "")
if isinstance(content, str):
return content
if isinstance(content, list):
parts = []
for part in content:
if isinstance(part, dict) and part.get("type") == "text":
parts.append(part.get("text", ""))
elif isinstance(part, str):
parts.append(part)
return " ".join(parts)
return ""


def _get_protected_indices(messages: List[dict]) -> List[int]:
"""
Return indices of messages that must never be compressed:
- All system messages
- The last user message
- The last assistant message
"""
protected: List[int] = []

last_user_idx = None
last_assistant_idx = None

for i, msg in enumerate(messages):
role = msg.get("role", "")
if role == "system":
protected.append(i)
elif role == "user":
last_user_idx = i
elif role == "assistant":
last_assistant_idx = i

if last_user_idx is not None:
protected.append(last_user_idx)
if last_assistant_idx is not None:
protected.append(last_assistant_idx)

return protected


def _combine_scores(
bm25_scores: List[float],
emb_scores: List[float],
bm25_weight: float = 0.4,
) -> List[float]:
"""Weighted average of BM25 and embedding scores, with min-max normalization."""

def _normalize(scores: List[float]) -> List[float]:
min_s = min(scores) if scores else 0.0
max_s = max(scores) if scores else 0.0
rng = max_s - min_s
if rng == 0:
return [0.0] * len(scores)
return [(s - min_s) / rng for s in scores]

norm_bm25 = _normalize(bm25_scores)
norm_emb = _normalize(emb_scores)
emb_weight = 1.0 - bm25_weight

return [bm25_weight * b + emb_weight * e for b, e in zip(norm_bm25, norm_emb)]


def compress(
messages: List[dict],
model: str,
compression_trigger: int = 200_000,
compression_target: Optional[int] = None,
embedding_model: Optional[str] = None,
compression_cache: Optional[DualCache] = None,
) -> CompressedResult:
"""
Compress a list of messages by replacing low-relevance content with stubs.

Messages below ``compression_trigger`` tokens pass through unchanged.
Messages above are scored with BM25 (and optionally embeddings), ranked,
and the lowest-relevance messages are replaced with stubs. Originals are
cached and a retrieval tool is injected so the model can recover dropped
content on demand.

Parameters:
messages: The conversation messages to (potentially) compress.
model: The LLM model name — used for token counting.
compression_trigger: Only compress if input exceeds this token count.
compression_target: Target token count after compression.
Defaults to ``compression_trigger // 2``.
embedding_model: If provided, use BM25 + embeddings for scoring.
If ``None``, BM25 only.
compression_cache: Passed through to ``litellm.embedding()`` for
cross-turn caching of embedding vectors.

Returns:
A ``CompressedResult`` dict containing compressed messages, token
counts, a cache of original content, and the retrieval tool definition.
"""
if compression_target is None:
compression_target = compression_trigger // 2

original_tokens = token_counter(model=model, messages=messages)

# Pass through if below trigger
if original_tokens <= compression_trigger:
return CompressedResult(
messages=messages,
original_tokens=original_tokens,
compressed_tokens=original_tokens,
compression_ratio=0.0,
cache={},
tools=[],
)

# Extract query for relevance scoring
query = _extract_last_user_message(messages)

# Score each message
bm25_scores = bm25_score_messages(query, messages)

if embedding_model:
from litellm.compression.scoring.embedding_scorer import (
embedding_score_messages,
)

emb_scores = embedding_score_messages(
query, messages, model=embedding_model, cache=compression_cache
)
Comment on lines +146 to +157

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Inline import inside function body

Per CLAUDE.md, imports should be at module level, not inside functions. The import of embedding_score_messages is conditional on embedding_model being truthy, but this isn't a circular-import situation — litellm.compression.scoring.embedding_scorer doesn't import back into compress.py. Moving this to the top of the file is straightforward.

Suggested change
if embedding_model:
from litellm.compression.scoring.embedding_scorer import (
embedding_score_messages,
)
emb_scores = embedding_score_messages(
query, messages, model=embedding_model, cache=compression_cache
)
from litellm.compression.scoring.embedding_scorer import embedding_score_messages

(Add to the module-level import block at the top of the file and remove the inline import here.)

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

combined_scores = _combine_scores(bm25_scores, emb_scores, bm25_weight=0.4)
else:
combined_scores = bm25_scores

# Sort message indices by score descending
ranked_indices = sorted(
range(len(messages)),
key=lambda i: combined_scores[i],
reverse=True,
)

# Protected messages are never compressed
protected_indices = _get_protected_indices(messages)
kept_indices: Set[int] = set(protected_indices)

# Count tokens for protected messages
current_tokens = 0
for i in kept_indices:
current_tokens += token_counter(
model=model, text=messages[i].get("content", "") or ""
)

# Fill token budget from highest-scoring messages.
# For each candidate (ranked by relevance):
# - If it fits entirely → keep it as-is.
# - If it doesn't fit but there's meaningful remaining budget → truncate it
# to fill that budget (so the LLM always has real content to work with).
# - Otherwise → stub it (pointer only, content goes to cache).
# We only truncate one message (the highest-scoring one that overflows) so
# the budget is consumed and the rest are stubbed cleanly.
truncated_overrides: Dict[int, dict] = {} # idx -> truncated message dict

for idx in ranked_indices:
if idx in kept_indices:
continue
msg_content = messages[idx].get("content", "") or ""
msg_tokens = token_counter(model=model, text=msg_content)
remaining = compression_target - current_tokens

if current_tokens + msg_tokens <= compression_target:
# Fits entirely
kept_indices.add(idx)
current_tokens += msg_tokens
elif remaining >= 100 and idx not in truncated_overrides:
# Too large to fit whole, but we have budget — truncate it.
# Only do this once (the highest-scoring overflow message).
truncated = truncate_message(messages[idx], remaining)
truncated_overrides[idx] = truncated
kept_indices.add(idx)
current_tokens = compression_target # budget consumed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Token budget uses text= but final count uses messages=

The budget accumulation calls token_counter(model=model, text=...) which counts only raw content tokens, while the final compressed count uses token_counter(model=model, messages=...) which adds per-message overhead (~4 tokens/message for OpenAI models). For small compression_target values (e.g. < 1000), the accumulated overhead across many messages can cause the actual compressed_tokens to meaningfully exceed compression_target. Both loops should use the same counting method for consistency.


# Build compressed messages and cache
compressed_messages: List[dict] = []
cache: Dict[str, str] = {}
used_keys: Set[str] = set()

for i, msg in enumerate(messages):
if i in kept_indices:
# Use the truncated version if we made one, otherwise the original
compressed_messages.append(truncated_overrides.get(i, msg))
else:
key = extract_key(msg, fallback_index=i, used_keys=used_keys)
content = msg.get("content", "")
if isinstance(content, list):
content = " ".join(
p.get("text", "") if isinstance(p, dict) else str(p)
for p in content
)
cache[key] = content
compressed_messages.append(stub_message(msg, key))

# Build retrieval tool
tools = [build_retrieval_tool(list(cache.keys()))] if cache else []

compressed_tokens = token_counter(model=model, messages=compressed_messages)

return CompressedResult(
messages=compressed_messages,
original_tokens=original_tokens,
compressed_tokens=compressed_tokens,
compression_ratio=round(1 - (compressed_tokens / original_tokens), 4)
if original_tokens > 0
else 0.0,
cache=cache,
tools=tools,
)
45 changes: 45 additions & 0 deletions litellm/compression/content_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""
Auto-detect content type per message: code, JSON, or text.
"""

import json
import re


_CODE_KEYWORDS = re.compile(
r"\b(?:def |function |class |import |from |require\(|#include|fn |func |const |let |var |public |private |static )\b"
)


def detect_content_type(content: str) -> str:
"""
Detect whether content is code, JSON, or plain text.

Returns one of: "code", "json", "text"
"""
stripped = content.strip()
if not stripped:
return "text"

# Check JSON
if stripped[0] in ("{", "["):
try:
json.loads(stripped)
return "json"
except (json.JSONDecodeError, ValueError):
pass

# Check code indicators
# Sample first 5000 chars for performance
sample = stripped[:5000]
keyword_matches = len(_CODE_KEYWORDS.findall(sample))
lines = sample.split("\n")
indented_lines = sum(
1 for line in lines if line.startswith((" ", "\t")) and line.strip()
)

# If we see multiple code keywords or significant indentation, it's likely code
if keyword_matches >= 3 or (indented_lines > len(lines) * 0.3 and len(lines) > 5):
return "code"

return "text"
108 changes: 108 additions & 0 deletions litellm/compression/message_stubbing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""
Replace messages with compact stubs and extract human-readable keys.
"""

import re
from typing import Set

from litellm.compression.content_detection import detect_content_type

# Patterns for extracting file paths from content
_FILE_PATH_PATTERNS = [
re.compile(r"^#\s*(\S+\.\w+)", re.MULTILINE), # # filename.py
re.compile(r"^//\s*(\S+\.\w+)", re.MULTILINE), # // filename.js
re.compile(r"^File:\s*(\S+)", re.MULTILINE), # File: path/to/file
re.compile(r"^---\s*(\S+\.\w+)", re.MULTILINE), # --- filename.ext
re.compile(r"`(\S+\.\w{1,5})`"), # `filename.ext` in backticks
]


def extract_key(message: dict, fallback_index: int, used_keys: Set[str]) -> str:
"""
Extract a human-readable key for the message.

Looks for file path patterns in the content. Falls back to message_{index}.
Handles duplicates by appending _2, _3, etc.
"""
content = message.get("content", "")
if isinstance(content, list):
content = " ".join(
p.get("text", "") if isinstance(p, dict) else str(p) for p in content
)

key = None
for pattern in _FILE_PATH_PATTERNS:
match = pattern.search(content[:2000]) # Only search the beginning
if match:
# Use just the filename, not full path
path = match.group(1)
key = path.split("/")[-1]
break

if key is None:
key = f"message_{fallback_index}"

# Handle duplicates
base_key = key
counter = 2
while key in used_keys:
key = f"{base_key}_{counter}"
counter += 1

used_keys.add(key)
return key


def stub_message(message: dict, key: str) -> dict:
"""
Replace message content with a compact stub.

Returns a new message dict with the same role but content replaced
with a short description referencing the retrieval tool.
"""
content = message.get("content", "")
if isinstance(content, list):
content = " ".join(
p.get("text", "") if isinstance(p, dict) else str(p) for p in content
)

line_count = content.count("\n") + 1
content_type = detect_content_type(content)

stub_content = (
f"[Compressed: {key} — {line_count} lines, {content_type}. "
f"Use litellm_content_retrieve tool to get full content.]"
)

return {**message, "content": stub_content}


def truncate_message(message: dict, max_tokens: int) -> dict:
"""
Truncate a message's content to approximately max_tokens by keeping
the first 70% and last 30% of words with a separator in between.

Used when a message is too large to fit entirely in the budget but
too relevant to fully stub out.
"""
content = message.get("content", "")
if isinstance(content, list):
content = " ".join(
p.get("text", "") if isinstance(p, dict) else str(p) for p in content
)

# Rough conversion: 1 token ≈ 0.75 words
target_words = max(1, int(max_tokens * 0.75))
words = content.split()

if len(words) <= target_words:
return {**message, "content": content}

first_count = (target_words * 2) // 3
last_count = target_words - first_count
truncated = (
" ".join(words[:first_count])
+ "\n...[truncated for context window]...\n"
+ " ".join(words[-last_count:])
)
return {**message, "content": truncated}
Loading
Loading