File size: 6,231 Bytes
9c7d451
90d3aea
 
 
9c7d451
 
90d3aea
 
 
 
9c7d451
90d3aea
9c7d451
 
 
 
90d3aea
9c7d451
90d3aea
 
 
9c7d451
 
90d3aea
 
9c7d451
90d3aea
 
 
9c7d451
 
90d3aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c7d451
 
90d3aea
9c7d451
 
90d3aea
 
 
 
 
 
 
 
 
 
 
 
 
 
9c7d451
 
7a05808
 
 
 
 
 
 
 
 
 
 
 
 
 
9c7d451
 
 
 
7a05808
9c7d451
 
 
 
 
 
 
 
 
 
 
 
 
 
c1feb60
 
 
 
 
 
 
 
 
 
 
9c9bb30
050d435
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c7d451
050d435
 
9c7d451
 
 
 
 
 
 
 
 
175746c
 
 
 
 
 
 
 
 
9c7d451
44e938e
9c7d451
 
 
 
 
 
 
 
 
c1feb60
 
 
 
 
 
 
 
 
 
9c7d451
 
 
 
 
 
7a05808
9c7d451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a05808
 
 
 
 
 
 
 
 
 
 
 
 
9c7d451
 
 
 
 
 
 
 
 
 
 
 
 
04a98a0
 
9c9bb30
04a98a0
 
 
 
6505c43
 
 
 
 
 
 
61e7398
 
9c7d451
6505c43
 
 
 
61e7398
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
"""
Headroom - The Context Optimization Layer for LLM Applications.

Cut your LLM costs by 50-90% without losing accuracy.

Headroom wraps LLM clients to provide:
- Smart compression of tool outputs (keeps errors, anomalies, relevant items)
- Cache-aligned prefix optimization for better provider cache hits
- Rolling window token management for long conversations
- Full streaming support with zero accuracy loss

Quick Start:

    from headroom import HeadroomClient, OpenAIProvider
    from openai import OpenAI

    # Wrap your existing client
    client = HeadroomClient(
        original_client=OpenAI(),
        provider=OpenAIProvider(),
        default_mode="optimize",
    )

    # Use exactly like the original client
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "user", "content": "Hello!"},
        ],
    )

    # Check savings
    stats = client.get_stats()
    print(f"Tokens saved: {stats['session']['tokens_saved_total']}")

Verify It's Working:

    # Validate configuration
    result = client.validate_setup()
    if not result["valid"]:
        print("Issues:", result)

    # Enable logging to see what's happening
    import logging
    logging.basicConfig(level=logging.INFO)
    # INFO:headroom.transforms.pipeline:Pipeline complete: 45000 -> 4500 tokens

Simulate Before Sending:

    plan = client.chat.completions.simulate(
        model="gpt-4o",
        messages=large_messages,
    )
    print(f"Would save {plan.tokens_saved} tokens")
    print(f"Transforms: {plan.transforms}")

Error Handling:

    from headroom import HeadroomError, ConfigurationError, ProviderError

    try:
        response = client.chat.completions.create(...)
    except ConfigurationError as e:
        print(f"Config issue: {e.details}")
    except HeadroomError as e:
        print(f"Headroom error: {e}")

For more examples, see https://github.com/headroom-sdk/headroom/tree/main/examples
"""

from .cache import (
    AnthropicCacheOptimizer,
    BaseCacheOptimizer,
    CacheConfig,
    CacheMetrics,
    CacheOptimizerRegistry,
    CacheResult,
    CacheStrategy,
    GoogleCacheOptimizer,
    OpenAICacheOptimizer,
    OptimizationContext,
    SemanticCache,
    SemanticCacheLayer,
)
from .client import HeadroomClient
from .config import (
    Block,
    CacheAlignerConfig,
    CacheOptimizerConfig,
    CachePrefixMetrics,
    DiffArtifact,
    HeadroomConfig,
    HeadroomMode,
    RelevanceScorerConfig,
    RequestMetrics,
    RollingWindowConfig,
    SimulationResult,
    SmartCrusherConfig,
    ToolCrusherConfig,
    TransformDiff,
    TransformResult,
    WasteSignals,
)
from .exceptions import (
    CacheError,
    CompressionError,
    ConfigurationError,
    HeadroomError,
    ProviderError,
    StorageError,
    TokenizationError,
    TransformError,
    ValidationError,
)

# Memory module - optional (requires numpy, hnswlib, etc.)
try:
    from .memory import (
        EmbedderBackend,
        HierarchicalMemory,
        Memory,
        MemoryConfig,
        ScopeLevel,
        with_memory,
    )
except ImportError:
    EmbedderBackend = None  # type: ignore[assignment,misc]
    HierarchicalMemory = None  # type: ignore[assignment,misc]
    Memory = None  # type: ignore[assignment,misc]
    MemoryConfig = None  # type: ignore[assignment,misc]
    ScopeLevel = None  # type: ignore[assignment,misc]
    with_memory = None  # type: ignore[assignment]

from .providers import AnthropicProvider, OpenAIProvider, Provider, TokenCounter

# Relevance scoring - BM25 always available, embedding requires sentence-transformers
from .relevance import (
    BM25Scorer,
    EmbeddingScorer,
    HybridScorer,
    RelevanceScore,
    RelevanceScorer,
    create_scorer,
    embedding_available,
)
from .reporting import generate_report
from .tokenizer import Tokenizer, count_tokens_messages, count_tokens_text
from .transforms import (
    CacheAligner,
    RollingWindow,
    SmartCrusher,
    ToolCrusher,
    TransformPipeline,
)

__version__ = "0.5.18"

__all__ = [
    # Main client
    "HeadroomClient",
    # Providers
    "Provider",
    "TokenCounter",
    "OpenAIProvider",
    "AnthropicProvider",
    # Exceptions
    "HeadroomError",
    "ConfigurationError",
    "ProviderError",
    "StorageError",
    "CompressionError",
    "TokenizationError",
    "CacheError",
    "ValidationError",
    "TransformError",
    # Config
    "HeadroomConfig",
    "HeadroomMode",
    "ToolCrusherConfig",
    "SmartCrusherConfig",
    "CacheAlignerConfig",
    "CacheOptimizerConfig",
    "RollingWindowConfig",
    "RelevanceScorerConfig",
    # Data models
    "Block",
    "CachePrefixMetrics",
    "DiffArtifact",
    "RequestMetrics",
    "SimulationResult",
    "TransformDiff",
    "TransformResult",
    "WasteSignals",
    # Transforms
    "ToolCrusher",
    "SmartCrusher",
    "CacheAligner",
    "RollingWindow",
    "TransformPipeline",
    # Cache optimizers
    "BaseCacheOptimizer",
    "CacheConfig",
    "CacheMetrics",
    "CacheResult",
    "CacheStrategy",
    "OptimizationContext",
    "CacheOptimizerRegistry",
    "AnthropicCacheOptimizer",
    "OpenAICacheOptimizer",
    "GoogleCacheOptimizer",
    "SemanticCache",
    "SemanticCacheLayer",
    # Relevance scoring
    "RelevanceScore",
    "RelevanceScorer",
    "BM25Scorer",
    "EmbeddingScorer",
    "HybridScorer",
    "create_scorer",
    "embedding_available",
    # Utilities
    "Tokenizer",
    "count_tokens_text",
    "count_tokens_messages",
    "generate_report",
    # Memory - hierarchical memory system
    "with_memory",  # Main user-facing API
    "Memory",
    "ScopeLevel",
    "HierarchicalMemory",
    "MemoryConfig",
    "EmbedderBackend",
    # One-function API
    "compress",
    "CompressResult",
    # Hooks
    "CompressionHooks",
    "CompressContext",
    "CompressEvent",
    # Shared context
    "SharedContext",
]

# One-function compression API
from headroom.compress import CompressResult, compress  # noqa: E402
from headroom.hooks import CompressContext, CompressEvent, CompressionHooks  # noqa: E402

# Shared context for multi-agent workflows
from headroom.shared_context import SharedContext  # noqa: E402