Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(langchain): implement get_metrics() on HeadroomChatModel (#3446) (#3459)
Waqas Ahmeddba5d2f1e7b0
diff --git a/headroom/integrations/langchain/chat_model.py b/headroom/integrations/langchain/chat_model.pyindex d8d095409..b9b51452c 100644--- a/headroom/integrations/langchain/chat_model.py+++ b/headroom/integrations/langchain/chat_model.py@@ -571,6 +571,16 @@ class HeadroomChatModel(BaseChatModel):"total_tokens_after": sum(m.tokens_after for m in self._metrics_history),}+ def get_metrics(self) -> dict[str, Any]:+ """Get metrics from the optimization history (see wiki/langchain.md).++ Same aggregate data as get_savings_summary(), with a ``tokens_saved``+ key so ``llm.get_metrics()['tokens_saved']`` works as documented.+ """+ summary = self.get_savings_summary()+ summary["tokens_saved"] = summary["total_tokens_saved"]+ return summary+class HeadroomCallbackHandler(BaseCallbackHandler):"""LangChain callback handler for Headroom metrics and observability.diff --git a/tests/test_integrations/langchain/test_chat_model.py b/tests/test_integrations/langchain/test_chat_model.pyindex e557dd00a..777b8737e 100644--- a/tests/test_integrations/langchain/test_chat_model.py+++ b/tests/test_integrations/langchain/test_chat_model.py@@ -293,6 +293,52 @@ class TestHeadroomChatModel:assert summary["total_tokens_saved"] == 70assert summary["average_savings_percent"] == 22.5+ def test_get_metrics_empty(self, mock_chat_model):+ """get_metrics with no history."""+ from headroom.integrations import HeadroomChatModel++ model = HeadroomChatModel(mock_chat_model)+ metrics = model.get_metrics()++ assert metrics["tokens_saved"] == 0+ assert metrics["total_requests"] == 0++ def test_get_metrics_with_data(self, mock_chat_model):+ """get_metrics returns tokens_saved from tracked optimization history."""+ from headroom.integrations import HeadroomChatModel+ from headroom.integrations.langchain import OptimizationMetrics++ model = HeadroomChatModel(mock_chat_model)++ model._metrics_history = [+ OptimizationMetrics(+ request_id="1",+ timestamp=datetime.now(),+ tokens_before=100,+ tokens_after=80,+ tokens_saved=20,+ savings_percent=20.0,+ transforms_applied=["smart_crusher"],+ model="gpt-4o",+ ),+ OptimizationMetrics(+ request_id="2",+ timestamp=datetime.now(),+ tokens_before=200,+ tokens_after=150,+ tokens_saved=50,+ savings_percent=25.0,+ transforms_applied=["cache_aligner"],+ model="gpt-4o",+ ),+ ]+ model._total_tokens_saved = 70++ metrics = model.get_metrics()++ assert metrics["tokens_saved"] == 70+ assert metrics["total_requests"] == 2+class TestHeadroomCallbackHandler:"""Tests for HeadroomCallbackHandler."""