Commit Graph
3 Commits
Author SHA1 Message Date
Tejas ChopraandClaude Opus 5.5 02ce467d2d chore(integrations): fix the broken LangChain example and stale docstrings (#4134)
## Description

This PR fixes a broken example and two stale docstrings in the
integrations.

- `examples/langchain_demo/run_comparison.py` could not run its Headroom
arm at all. It failed in three places, in this order:
1. `HeadroomConfig(smart_crusher_threshold=...,
smart_crusher_max_items=..., cache_alignment=..., rolling_window=...)`:
none of these keyword arguments exist, so it raised `TypeError` before
anything ran. (Rolling-window was removed from the pipeline; see
`docs/content/docs/architecture.mdx`.)
2. `HeadroomChatModel(..., headroom_config=config)`: the constructor
parameter is `config`, so this raised `TypeError: ... got multiple
values for keyword argument 'headroom_config'`.
3. `headroom_model.get_total_tokens_saved()`: `HeadroomChatModel` has no
such method; it exposes the `total_tokens_saved` property, so this would
have raised `AttributeError` at the end of each scenario.
- The `headroom/integrations/mcp/server.py` module docstring showed a
`HeadroomMCPMiddleware` class that does not exist.
- The `headroom/integrations/__init__.py` docstring showed the same Agno
import line twice.

Refs #4136

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `examples/langchain_demo/run_comparison.py`:
- the config becomes `HeadroomConfig()`, with a comment saying why. The
old keyword arguments do not exist, and their nearest real equivalent
(`smart_crusher=SmartCrusherConfig(...)`) would have no effect:
`TransformPipeline` builds its `ContentRouter` from the router's own
defaults and never reads `HeadroomConfig.smart_crusher`. That wiring gap
is a separate product change; it is recorded in the docs ledger because
`api-reference.mdx` shows such a setting;
  - `headroom_config=config` becomes `config=config`;
- `headroom_model.get_total_tokens_saved()` becomes
`headroom_model.total_tokens_saved`.
- the printed narrative no longer claims a 20-item cap or a CacheAligner
gain (CacheAligner is off by default, and the 15-item setting applies
only to lossy row selection); the simulation figure is labelled a rough
5x estimate.
- `headroom/integrations/mcp/server.py`: the "Middleware" docstring
example now uses the real `HeadroomMCPClientWrapper(base_client,
config=config)` and its `call_tool`.
- `headroom/integrations/__init__.py`: the first Agno example line now
shows the package-level import `from headroom.integrations import
HeadroomAgnoModel`, which is re-exported there. The "or explicitly" line
keeps the subpackage import.

## Testing

- [ ] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [ ] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ python -c "from headroom.integrations.langchain import HeadroomChatModel as H; print(type(H.__dict__.get('total_tokens_saved')).__name__, hasattr(H, 'get_total_tokens_saved'))"
property False
$ python -c "from headroom.integrations import HeadroomAgnoModel; print('ok')"
ok
$ python -m py_compile examples/langchain_demo/run_comparison.py && echo compiled
compiled
# run_agent_headroom(SCENARIOS[0]) with ChatOpenAI replaced by a fake LangChain chat model (no API key)
# that first asks for a search_logs tool call, then answers "done"
origin/main: TypeError: HeadroomConfig.__init__() got an unexpected keyword argument 'smart_crusher_threshold'
this branch: model calls: 2 | 2nd call message types: ['SystemMessage', 'HumanMessage', 'AIMessage', 'ToolMessage']
             OK scenario='User Account Investigation' tool_calls=1 tool_output_tokens=25643 final='done' messages=5
$ pytest tests/test_integrations/mcp tests/test_integrations/langchain/test_chat_model.py
70 passed, 9 skipped
$ uvx ruff@0.16.8 check / format --check <3 touched files>  -> All checks passed! / already formatted
```

## Real Behavior Proof

- Environment: macOS, Python 3.12, repo venv.
- Exact command / steps: the commands above. The example run imports
`examples.langchain_demo.run_comparison`, swaps `ChatOpenAI` for a
`FakeMessagesListChatModel` that first returns a `search_logs` tool call
and then answers "done", and calls `run_agent_headroom` on the first
scenario. So construction, a tool-result turn through
`HeadroomChatModel`, and the metrics read all run.
- Observed result: on origin/main the Headroom arm raises `TypeError` at
config construction; on this branch it returns an `AgentRun`. The
docstring imports resolve.
- Smoke harness (real proxy started from this checkout against a local
fake upstream; temp HOME and workspace, offline):

```text
branch: cleanup/cli-integrations-integrations-unused-imports @ 0ff4cbf3
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines (<tmp>/ws/logs/proxy-53143.log):
   2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you configured, operator-configured local endpoints, loopback health probes.
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.
(smoke dir: <tmp>)
```
- Direct runtime command on this PR's own path (temp HOME,
HEADROOM_WORKSPACE_DIR and CODEX_HOME):

```text
$ python examples/langchain_demo check: run_agent_headroom(SCENARIOS[0]) with a fake chat model (tool call, then "done")
model calls: 2 | 2nd call message types: ['SystemMessage', 'HumanMessage', 'AIMessage', 'ToolMessage']
OK scenario='User Account Investigation' tool_calls=1 tool_output_tokens=25627 final='done' messages=5
```
- Not tested: running the full demo against a real model, which needs
live API keys.

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: n/a, example script and docstrings only.
- Stable/default behavior changed: no library behaviour changes.
- Kill switch / disable path: n/a.
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.

- The audit also proposed removing three unused try-block imports:
  - `ModelResponse` in `agno/model.py`;
  - `AIMessageChunk` in `langchain/streaming.py`;
  - `BeforeToolCallEvent` in `strands/hooks.py`.

They are left in place. `from headroom.integrations.<x> import <name>`
works for each of them today, with or without the framework installed,
and nothing importable from `headroom/integrations/` may be removed.
- The branch name still says "unused-imports" for that reason.
- No regression test: the example is not part of the test suite; the
fake-model run above is the check.
- Docs: `wiki/langchain.md:587` documents the same nonexistent
`headroom_config=` keyword. That is recorded in the docs ledger; this PR
does not edit docs.

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

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4134"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 09:02:10 -07: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 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