Commit graph

2696 commits

Author SHA1 Message Date
chopratejas
37c30d4790 Bump version to 0.2.9
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 16:33:56 -08:00
chopratejas
0b945cf862 Add feature coverage and known limitations to Agno docs
Documents what the integration optimizes (messages, tool calls, streaming)
and what operates outside the optimization boundary (agent memory, knowledge
bases, agent teams). Includes best practices and future improvement plans.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 16:25:31 -08:00
chopratejas
aaaca9fa6a Add Agno integration documentation
- Update README.md with Agno quickstart and framework integration
- Create comprehensive docs/agno.md guide covering:
  - Model wrapping with HeadroomAgnoModel
  - Observability hooks (HeadroomPreHook, HeadroomPostHook)
  - Multi-provider auto-detection
  - Real-world examples and configuration reference
- Update docs/README.md index with Agno link
2026-01-16 16:17:14 -08:00
chopratejas
1f806cef4c Add Agno integration tests to CI workflow 2026-01-16 16:11:02 -08:00
chopratejas
f1e7b628c4 Add Agno agent framework integration
- HeadroomAgnoModel: Drop-in wrapper for any Agno model with automatic
  context optimization
- HeadroomPreHook/HeadroomPostHook: Agent-level hooks for tracking
  optimization metrics across tool calls
- Provider detection for Agno models (OpenAI, Anthropic, Google, etc.)
- Full test coverage for model wrapper and hooks
2026-01-16 16:02:55 -08:00
chopratejas
09973b614d Use LiteLLM for model pricing instead of hardcoded values
- Add litellm as a core dependency for accessing its community-maintained
  model pricing database (2,425+ models across all major providers)
- Create headroom/pricing/litellm_pricing.py with simple wrapper functions
- Update ModelRegistry.estimate_cost() to fetch pricing from LiteLLM
- Remove hardcoded pricing fields from ModelInfo dataclass
- Update tests to reflect new pricing source
2026-01-16 00:35:04 -08:00
Tejas Chopra
319fb56530 Fix proxy passthrough routing to use SDK headers instead of User-Agent
The passthrough route was incorrectly routing requests based on
User-Agent string, which caused requests from Anthropic SDK to be
forwarded to OpenAI's API instead of Anthropic's API.

Now checks for anthropic-version header or x-api-key header to
reliably detect Anthropic SDK requests and route them correctly.
2026-01-15 23:49:45 -08:00
chopratejas
1a25d56cd0 Bump version to 0.2.8 2026-01-15 23:22:21 -08:00
chopratejas
dcbc220929 Fix mypy type annotation error in content_router.py 2026-01-15 23:22:09 -08:00
chopratejas
01472fefec Bump version to 0.2.7 2026-01-15 23:10:34 -08:00
chopratejas
ac3b21bfde Add CCR marker support to all compressors and fix retrieval
- Fix CCRToolInjector detection for LLMLingua (use standard marker format)
- Add CCR marker output to CodeAwareCompressor
- Add SmartCrusher.crush() method for ContentRouter integration
- Fix ContentRouter to pass CCRConfig to SmartCrusher
- Fix CCR response handler decompression error (remove encoding headers)
- Add content block processing for Anthropic tool_result format
2026-01-15 23:08:47 -08:00
chopratejas
02fd2284e0 Fix LLMLingua API: use context=[content] not original_prompt
The LLMLingua PromptCompressor.compress_prompt() expects context as a list,
not original_prompt as a string. Also use empty list [] for force_tokens
instead of None.
2026-01-15 21:33:39 -08:00
chopratejas
07dfa9d25c Fix 'list' object has no attribute 'strip' error
Handle multimodal messages (images) where content is a list instead of string.
Skip non-string content in LLMLingua and code-aware compression transforms.
2026-01-15 21:25:48 -08:00
chopratejas
e6370026bc Bump version to 0.2.6 2026-01-15 21:18:26 -08:00
chopratejas
d5ea931635 Enable LLMLingua and code-aware compression by default in proxy
- Add --no-llmlingua flag (compression ON by default, opt-out)
- Add --llmlingua-device and --llmlingua-rate flags
- Add --no-code-aware flag (AST compression ON by default, opt-out)
- Add code_aware_enabled config and _setup_code_aware() method
- Update banner to show Code-Aware compression status
- Better UX: zero-config proxy starts with all optimizations enabled
2026-01-15 21:17:10 -08:00
chopratejas
bcd96b3a94 Bump version to 0.2.5 2026-01-15 21:08:15 -08:00
chopratejas
2c225854bb Fix mypy type errors in compression module
- Fix compress_with_llmlingua call: use compression_rate parameter
- Fix CompressionStore.store() call: use positional args for original/compressed
- Fix extract_json_schema return type to support arrays
- Add proper type casts for Any returns
2026-01-15 16:41:43 -08:00
chopratejas
64a747d66e Fix flaky JavaScript signature preservation test threshold
Lower threshold from 70% to 60% - methods inside class bodies
may be compressed, which is expected behavior.
2026-01-15 15:38:25 -08:00
chopratejas
31aa72c885 Add universal compression module with ML-based content detection
- Add headroom.compression module with UniversalCompressor
- ML-based content detection using Magika (JSON, code, logs, text)
- Structure-preserving compression via handler protocol
- JSON handler: preserves keys, brackets, high-entropy values (UUIDs)
- Code handler: preserves imports, signatures, types (tree-sitter AST)
- Entropy-based preservation for identifiers and hashes
- CCR integration for reversible compression
- Comprehensive test suite with LLM eval tests
- Add docs/compression.md with full API documentation
2026-01-15 15:26:14 -08:00
chopratejas
2ec223c071 Bump version to 0.2.4 2026-01-14 21:47:58 -08:00
chopratejas
9c9bb30ded Add persistent memory system with zero-latency inline extraction
Features:
- with_fast_memory(): Zero-latency inline extraction (Letta-style)
  - Memory extracted as part of LLM response, no extra API calls
  - Semantic retrieval with local embeddings (sub-50ms)
- with_memory(): Background extraction for non-blocking memory
- SQLite + FTS5 storage with vector similarity search
- Multi-user isolation by user_id

Memory enables temporal compression - extract key facts instead of
carrying full conversation history (4000 tokens → 50 tokens).

Includes:
- Comprehensive test suite (71 new tests)
- Documentation (docs/memory.md)
- Benchmark examples comparing approaches
- E2E test with LLM-as-judge evaluation
2026-01-14 21:32:09 -08:00
Tejas Chopra
d97fcfd0bd Merge pull request #4 from pythoninthegrass/main
Improve CI: Add Python 3.13, optimize linting, and fix unused import
2026-01-14 18:33:21 -08:00
pythoninthegrass
82f65990e7 Remove unused ProxyConfig import from compression tests
Fixes linting error F401 where ProxyConfig was imported but never used.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-14 20:27:08 -06:00
pythoninthegrass
ec7886481c Use oldest supported Python version (3.10) for package build
Build artifacts with Python 3.10 to ensure maximum compatibility
and avoid accidentally using newer features in build tooling.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-14 20:26:44 -06:00
pythoninthegrass
783fb080f5 Add Python 3.13 to CI matrix and optimize linting steps
Adds Python 3.13 to the test matrix. Optimizes CI by running linting
and type checking only on Python 3.12 instead of all versions.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-14 20:26:44 -06:00
Tejas Chopra
4c28393ef3 Merge pull request #3 from pythoninthegrass/main
Fix ZlibError by removing compression headers after httpx decompression
2026-01-14 18:20:34 -08:00
pythoninthegrass
876e8601cf Add tests for compression header removal fix
Test cases verify:
- Content-Encoding and Content-Length headers are correctly removed
- Response bodies are already decompressed by httpx
- Keeping compression headers causes length mismatch issues
- The fix doesn't break uncompressed responses

These tests will catch regressions of the ZlibError bug.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-14 20:03:14 -06:00
pythoninthegrass
8599bf76fc Fix ZlibError by removing compression headers after httpx decompression
httpx automatically decompresses responses when reading response.content,
but the proxy was forwarding the original Content-Encoding headers. This
caused clients to attempt double-decompression, resulting in ZlibError.

Fixes compression header handling in:
- Non-streaming Anthropic/OpenAI responses
- Cached responses
- Passthrough handler

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-14 19:36:41 -06:00
chopratejas
bb041047c8 Add seamless LangChain integration
- Add HeadroomChatModel wrapper with auto provider detection (OpenAI, Anthropic, Google)
- Add HeadroomChatMessageHistory for automatic conversation compression
- Add HeadroomDocumentCompressor for retriever integration
- Add wrap_tools_with_headroom() for agent tool output compression
- Add async support (ainvoke, astream)
- Add LangSmith integration for observability
- Restructure integrations package into nested langchain/ and mcp/ subpackages
- Fix Pydantic v2 deprecation warning
- Add comprehensive docs/langchain.md guide with real-world examples
- Update README with LangChain quickstart and framework integrations

Bump version to 0.2.3
2026-01-14 16:03:34 -08:00
chopratejas
905c229251 Add AST-based code compression and custom model configuration
CodeAwareCompressor:
- Tree-sitter based AST parsing for Python, JS, TS, Go, Rust, Java, C, C++
- Preserves imports, signatures, type annotations, error handlers
- Guarantees syntactically valid output
- Uses tree-sitter-language-pack for broad language support

ContentRouter:
- Intelligent compression orchestrator
- Auto-routes content to optimal compressor based on type detection
- Source hint support for high-confidence routing

Custom Model Configuration:
- HEADROOM_MODEL_LIMITS env var and ~/.headroom/models.json support
- Pattern-based inference for unknown models (opus/sonnet/haiku tiers)
- Support for Claude 4.5, Claude 4, o3, o3-mini
- Graceful fallback - never crashes on unknown models
2026-01-14 13:46:55 -08:00
chopratejas
d724f14022 v0.2.2: Add CCR Response Handler, Context Tracker, and restructure docs
Features:
- CCR Response Handler: Automatically intercepts and handles headroom_retrieve tool calls
- CCR Context Tracker: Multi-turn awareness with proactive expansion of relevant compressed content
- New CCR demo script showing before/after flow

Documentation:
- Restructured README from 885 lines to 190 lines for better DevEx
- Split detailed docs into focused guides: ccr.md, sdk.md, configuration.md,
  text-compression.md, llmlingua.md, metrics.md, errors.md
- Updated docs/README.md index with all new documentation

Tests:
- Added comprehensive tests for Response Handler (32 tests)
- Added comprehensive tests for Context Tracker (32 tests)
- All 977 tests passing
2026-01-14 13:03:41 -08:00
chopratejas
45633b69ab Add LLMLingua-2 opt-in support to proxy server
Integrate Microsoft's LLMLingua-2 ML-based compression as an opt-in
feature for the proxy server, with excellent developer experience.

Features:
- New CLI flags: --llmlingua, --llmlingua-device, --llmlingua-rate
- ProxyConfig options: llmlingua_enabled, llmlingua_device, llmlingua_target_rate
- Smart startup hints when llmlingua is available but not enabled
- Helpful error messages when enabled but not installed
- LLMLinguaCompressor inserted before RollingWindow in pipeline

Why opt-in:
- Heavy dependencies (~2GB torch, transformers)
- 10-30s cold start for model loading
- ~1GB RAM when loaded
- Default proxy stays lightweight (<5ms overhead)

Tests:
- 26 new tests in test_proxy_llmlingua.py covering config, setup,
  banner status, CLI args, DevEx messages, and edge cases

Documentation:
- Updated README.md with proxy integration section
- Updated docs/proxy.md with LLMLingua CLI options
- Updated docs/transforms.md with LLMLinguaCompressor reference
- Updated docs/ARCHITECTURE.md with pipeline and file structure
- Updated CHANGELOG.md with new feature
2026-01-14 12:21:51 -08:00
chopratejas
c2117ab70c Fix mypy errors: correct CompressionStore.store() arguments 2026-01-12 18:01:48 -08:00
chopratejas
946ba4fab6 Fix lint errors in text compression utilities 2026-01-12 17:32:51 -08:00
chopratejas
eac2890bce Add opt-in text compression utilities for coding tasks
Add standalone text compression utilities that applications can use
explicitly for non-JSON content:

- SearchCompressor: for grep/ripgrep output (file:line:content format)
- LogCompressor: for build/test logs (pytest, npm, cargo output)
- TextCompressor: for generic plain text with anchor preservation
- detect_content_type: content type detection for routing decisions

Design decision: Text compression is OPT-IN, not automatic. SmartCrusher
continues to compress JSON automatically (structure-preserving, safe),
but passes non-JSON through unchanged. Applications decide when and how
to compress text content based on their specific needs.

This prevents lossy text compression from being applied automatically,
which could lose important context in coding tasks (e.g., root cause
errors in logs, critical matches in search results).

Includes 22 tests covering content detection, compression utilities,
and SmartCrusher pass-through behavior.
2026-01-12 17:25:06 -08:00
chopratejas
22fa9eb927 Add deterministic anchor matching to all compression plans
Separates deterministic anchor matching from probabilistic relevance
scoring to reliably preserve needle records in crushing:

- Add extract_query_anchors() calls before relevance scoring
- Items matching UUIDs, quoted names, IDs are now always preserved
- Works across all 4 compression plans: time_series, cluster_sample,
  top_n, and smart_sample

This fixes the test_preserves_needle_by_name failure where "Alice" at
index 50 was dropped because hybrid relevance scoring gave it only
0.17 (below 0.25 threshold). Now anchor matching catches exact
matches deterministically.
2026-01-10 18:40:36 -08:00
chopratejas
3ab0a5dba0 Fix all mypy type errors and flaky embedding test
- Fix 34 mypy errors across 17 files with type annotations and casts
- Add type: ignore comments for legitimate dynamic patterns
- Handle None operands with (value or 0) pattern
- Cast return values to proper types (int, float, str, bool)
- Add EstimatingTokenCounter imports where needed
- Use getattr() for potentially missing attributes
- Fix flaky test_paraphrase_match with more distinct semantic examples
- Add mlx to mypy ignore list (broken third-party stubs)
2026-01-10 18:40:36 -08:00
chopratejas
bf779b54e6 Fix all mypy type errors and flaky embedding test
- Fix 34 mypy errors across 17 files with type annotations and casts
- Add type: ignore comments for legitimate dynamic patterns
- Handle None operands with (value or 0) pattern
- Cast return values to proper types (int, float, str, bool)
- Add EstimatingTokenCounter imports where needed
- Use getattr() for potentially missing attributes
- Fix flaky test_paraphrase_match with more distinct semantic examples
- Add mlx to mypy ignore list (broken third-party stubs)
2026-01-10 18:27:33 -08:00
chopratejas
e4a41faa33 Fix all ruff lint and format errors for CI
- Fix E402: Move module-level imports to top of file
- Fix F401: Add noqa for availability check imports
- Fix F402: Rename loop variables shadowing imports
- Fix E722: Replace bare except with except Exception
- Fix B904: Add exception chaining (from e)
- Fix F811: Remove duplicate imports
- Fix B027: Add noqa for empty close() method
- Fix E741: Rename ambiguous variable l -> label
- Fix I001: Import sorting issues
- Apply ruff format to all 106 files

All 902 tests pass.
2026-01-10 15:33:44 -08:00
chopratejas
55814fe09c Fix GitHub URLs and PyPI badge links (v0.2.1)
- Update all GitHub URLs from headroom-sdk/headroom to chopratejas/headroom
- Fix PyPI badge URLs from headroom to headroom-ai
- Bump version to 0.2.1
2026-01-10 15:11:57 -08:00
Tejas Chopra
e782723ac3 Update CONTRIBUTING.md 2026-01-10 15:05:16 -08:00
chopratejas
90d3aea44c Publish headroom-ai v0.2.0 to PyPI with DevEx fixes
- Renamed package from 'headroom' to 'headroom-ai' (PyPI name conflict)
- Fixed numpy/jinja2 imports to be lazy (core install no longer crashes)
- Fixed SQLite default path (now uses temp directory)
- Fixed f-string {tool} crash in proxy server
- Updated README with correct package name and examples
- Added quickstart and troubleshooting docs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 14:51:08 -08:00
chopratejas
c1feb60595 feat: Add CCR architecture, TOIN telemetry, and DevEx improvements
## Core Features

### Compress-Cache-Retrieve (CCR) Architecture
- Implement reversible compression with automatic retrieval support
- Add CompressionStore for caching original content with TTL-based eviction
- Add CompressionFeedback for learning from retrieval patterns
- Implement tool injection for LLM retrieval capability
- Add MCP server support for CCR operations
- Track retrieval rates to dynamically adjust compression aggressiveness

### Tool Output Intelligence Network (TOIN)
- Implement cross-session pattern learning for tool compression
- Add ToolSignature for structural hashing of tool outputs
- Track compression success rates per strategy (top_n, sample, truncate, etc.)
- Implement privacy-preserving telemetry with SHA256 hashing
- Add persistent storage with JSON file backend
- Support network-effect learning across tool types

### SmartCrusher Enhancements
- Add crushability analysis with variance/uniqueness detection
- Implement statistical anomaly detection for outlier preservation
- Add relevance-based item prioritization using BM25 scoring
- Support multiple compression strategies with quality retention
- Add change point detection for time-series data
- Implement constant factoring for homogeneous datasets

## Developer Experience Improvements

### Exception Hierarchy
- Add HeadroomError base class for all custom exceptions
- Add specific exceptions: ConfigurationError, ProviderError,
  StorageError, CompressionError, TokenizationError, CacheError,
  ValidationError, TransformError

### Client Enhancements
- Add validate_setup() for configuration verification
- Add get_stats() for in-memory session metrics without DB query
- Track session statistics (requests, tokens saved, cache hits)

### Logging Infrastructure
- Add structured logging to TransformPipeline with token savings
- Add logging to RollingWindow for dropped message tracking
- Add logging to ToolCrusher for compression events
- Add logging to CacheAligner for cache hit/miss detection
- Add logging to SmartCrusher for strategy selection

## Bug Fixes (from deep analysis)

### Critical Fixes
- Fix eviction heap memory leak with stale entry tracking
- Fix hash collision detection in compression store
- Fix strategy truncation desync in TOIN
- Fix non-deterministic set truncation with sorted iteration
- Fix race conditions in lazy initialization with proper locking
- Fix user count double-counting in TOIN metrics

### High Priority Fixes
- Fix unbounded strategy_success_rates growth with LRU eviction
- Fix mutable pattern references with defensive copying
- Fix lock held during file I/O with copy-then-write pattern
- Fix state divergence on eviction with success event recording
- Fix TOIN skip check order for CPU efficiency
- Fix preserve_fields type mismatch (set vs list)
- Fix prioritize_indices exceeding max_items limit
- Fix instance ID collision risk (32-bit to 64-bit hash)

## Testing

- Add comprehensive test suites for CCR, TOIN, and telemetry
- Add crushability detection tests
- Add quality retention tests for compression
- Add integration tests for cross-component data flow
- All 902 tests passing
2026-01-10 10:12:13 -08:00
chopratejas
7a05808e0f Add cache optimization module with scalable dynamic content detection
Implements a comprehensive cache optimization layer for LLM providers:

- Provider-specific optimizers (Anthropic, OpenAI, Google) with distinct
  caching strategies: explicit breakpoints, prefix stabilization, and
  CachedContent API respectively

- Scalable dynamic content detector using three strategies:
  1. Structural detection: "Label: value" patterns (language-agnostic)
  2. Entropy-based detection: high-entropy strings (IDs, tokens, hashes)
  3. Universal patterns: ISO 8601, UUIDs, JWTs, hex hashes

- NO hardcoded locale-specific patterns (no month names, etc.)

- Semantic caching layer with LRU eviction and TTL support

- Plugin registry for provider selection and custom optimizers

- 131 tests, real-world benchmarks showing 20-55% compression at <0.3ms
2026-01-07 14:07:49 -08:00
chopratejas
175746cc26 Prepare for OSS release v0.2.0
This commit prepares Headroom for public open source release with
comprehensive documentation, licensing, and community infrastructure.

License & Legal:
- Add Apache 2.0 LICENSE file
- Add NOTICE file with third-party attributions
- Add SECURITY.md for vulnerability reporting

Community:
- Add CONTRIBUTING.md with contribution guidelines
- Add CODE_OF_CONDUCT.md (Contributor Covenant)
- Add GitHub issue templates (bug report, feature request)
- Add pull request template

Documentation:
- Update README.md with compelling value proposition
- Add docs/getting-started.md
- Add docs/proxy.md for proxy server documentation
- Add docs/transforms.md for transform reference
- Add docs/api.md for API reference
- Add examples/README.md

Package Infrastructure:
- Add headroom/py.typed for PEP 561 compliance
- Add headroom/cli.py for CLI entry point
- Add .github/workflows/ci.yml for CI pipeline
- Add .github/workflows/publish.yml for PyPI publishing
- Update pyproject.toml with proper metadata

New Features:
- Add multi-provider support (Google, Cohere, LiteLLM, OpenAI-compatible)
- Add universal tokenizer registry with multiple backends
- Add model registry with pricing and context limits
- Add production proxy server with caching and rate limiting

Code Quality:
- Fix 83 lint issues via ruff auto-fix
- Fix version consistency (benchmarks 0.1.0 → 0.2.0)
- Add skip decorators for optional dependency tests
2026-01-07 11:36:44 -08:00
chopratejas
9c7d4512d6 Initial commit: Headroom SDK - LLM context optimization toolkit
A comprehensive SDK for optimizing LLM context windows, reducing token
usage while preserving critical information for AI agents.

Core Features:
- SmartCrusher: Statistical compression of tool outputs (70-85% reduction)
- CacheAligner: Prefix optimization for prompt cache hits
- RollingWindow: Intelligent context window management
- BM25/Hybrid relevance scoring for smart item selection

Integrations:
- OpenAI and Anthropic provider support
- LangChain integration (ChatModel, Callbacks, Runnable)
- MCP (Model Context Protocol) integration for tool compression

Test Coverage:
- 372 tests passing across all modules
- 35 performance benchmarks
- Real-world agent evaluations with 88% token savings

Key Components:
- headroom/transforms/: Core compression transforms
- headroom/providers/: OpenAI and Anthropic support
- headroom/integrations/: LangChain and MCP integrations
- headroom/relevance/: BM25 and hybrid scoring
- headroom/pricing/: Model pricing registry
- benchmarks/: Performance benchmark suite
- examples/: Usage examples and demos
2026-01-06 23:16:58 -08:00