Metadata-Version: 2.4
Name: llm-token-lens
Version: 0.2.0
Summary: Local LLM token efficiency middleware — zero cloud, zero tracking, coaches developers on token waste in the terminal
Project-URL: Homepage, https://github.com/nikhilbahalkar/llm-token-lens
Project-URL: Issues, https://github.com/nikhilbahalkar/llm-token-lens/issues
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship made available under
              the License, as indicated by a copyright notice that is included in
              or attached to the work (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other transformations
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean, as submitted to the Licensor for inclusion
              in the Work by the copyright owner or by an individual or Legal Entity
              authorized to submit on behalf of the copyright owner. For the purposes
              of this definition, "submitted" means any form of electronic, verbal,
              or written communication sent to the Licensor or its representatives,
              including but not limited to communication on electronic mailing lists,
              source code control systems, and issue tracking systems that are managed
              by, or on behalf of, the Licensor for the purpose of contributing to the
              Work, but excluding communication that is conspicuously marked or
              otherwise designated in writing by the copyright owner as "Not a
              Contribution."
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor and included
              within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by the combined work (in which such
              Contribution(s) has been submitted). If You institute patent litigation
              against any entity (including a cross-claim or counterclaim in a
              lawsuit) alleging that the Work or any Work embodied within the Work
              constitutes direct or contributory patent infringement, then any patent
              licenses granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, You must include a readable copy of the
                  attribution notices contained within such NOTICE file, in
                  at least one of the following places: within a NOTICE text
                  file distributed as part of the Derivative Works; within
                  the Source form or documentation, if provided along with the
                  Derivative Works; or, within a display generated by the
                  Derivative Works, if and wherever such third-party notices
                  normally appear. The contents of the NOTICE file are for
                  informational purposes only and do not modify the License.
                  You may add Your own attribution notices within Derivative
                  Works that You distribute, alongside or in addition to the
                  NOTICE text from the Work, provided that such additional
                  attribution notices cannot be construed as modifying the
                  License.
        
              You may add Your own license statement for Your modifications and
              may provide additional grant of rights to use, copy, modify, merge,
              publish, distribute, sublicense, and/or sell copies of the Work.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or reproducing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or exemplary damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (even if such Contributor has been advised of the possibility
              of such damages).
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer, and
              charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may offer such
              obligations only on Your own behalf and on Your sole responsibility,
              not on behalf of any other Contributor, and only if You agree to
              indemnify, defend, and hold each Contributor harmless for any
              liability incurred by, or claims asserted against, such Contributor
              by reason of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
        Copyright 2026 Nikhil Bahalkar
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
        
            http://www.apache.org/licenses/LICENSE-2.0
        
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.12
Provides-Extra: accurate-counting
Requires-Dist: tiktoken>=0.7; extra == 'accurate-counting'
Provides-Extra: dev
Requires-Dist: openai>=1.0.0; extra == 'dev'
Requires-Dist: pytest-cov; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: tiktoken; extra == 'dev'
Provides-Extra: langgraph
Requires-Dist: langchain-core>=0.2; extra == 'langgraph'
Description-Content-Type: text/markdown

# token-lens

**Local LLM token efficiency middleware.**  
Wraps your existing LLM client with one line of code. Detects token waste patterns and prints actionable suggestions to your terminal — during development, with zero cloud dependency and zero data leaving your machine.

```
⚠ [token-lens TL006] No max_tokens set on call to 'openai/gpt-4o-mini'.
  → Without a cap, a misbehaving prompt can generate thousands of tokens and spike costs.

⚠ [token-lens TL001] System prompt is identical across 3+ consecutive calls (~120 tokens each).
  → Use prompt caching. Potential saving: ~80% of system prompt tokens.

── token-lens session summary ──
  calls:             3
  prompt tokens:     612
  completion tokens: 187
  total tokens:      799
  openai/gpt-4o-mini: 3 call(s), 799 tokens
```

---

## Why token-lens?

Existing tools — Helicone, AgentOps, LangSmith, PromptLayer — are observability platforms: they **count** tokens via a cloud service. token-lens is different in three ways:

| | token-lens | Cloud tools |
|---|---|---|
| **Data leaves your machine** | Never | Yes |
| **Setup** | One line of code | Account + API key + proxy/SDK |
| **What it does** | Detects *why* tokens are wasted | Counts tokens that were spent |
| **Works offline** | Yes | No |
| **Enterprise deployment** | `pip install` on your server | Vendor agreement required |

---

## Supported providers

token-lens works with **any SDK that exposes a `chat.completions.create()` interface**, plus a dedicated adapter for the native Anthropic SDK.

| Provider | SDK | Wrapper |
|---|---|---|
| OpenAI | `openai` | `TokenLens` |
| OpenRouter | `openai` (compat) | `TokenLens` |
| Groq | `groq` | `TokenLens` |
| Together AI | `openai` (compat) | `TokenLens` |
| Azure OpenAI | `openai` | `TokenLens` |
| Ollama | `openai` (compat) | `TokenLens` |
| Perplexity | `openai` (compat) | `TokenLens` |
| Mistral | `openai` (compat) | `TokenLens` |
| Anthropic | `anthropic` (native) | `AnthropicTokenLens` |
| LangGraph / LangChain | any via callbacks | `TokenLensCallbackHandler` |

---

## Installation

### From PyPI (recommended)

```bash
pip install llm-token-lens
```

For accurate token counting (highly recommended):

```bash
pip install "token-lens[accurate-counting]"
```

For LangGraph / LangChain callback support:

```bash
pip install "token-lens[langgraph]"
```

Install everything at once:

```bash
pip install "token-lens[accurate-counting,langgraph]"
```

### From source

```bash
git clone https://github.com/nikhilbahalkar/llm-token-lens.git
cd llm-token-lens
pip install -e ".[accurate-counting,dev]"
```

---

## Quick start

### OpenAI / OpenAI-compatible providers

Change one line — everything else stays identical:

```python
from openai import OpenAI
from token_lens import TokenLens       # ← add this import

# Before:
# client = OpenAI(api_key="...", base_url="...")

# After:
client = TokenLens(OpenAI(api_key="...", base_url="..."))  # ← wrap it

# All existing call sites are unchanged:
response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Hello!"}],
    max_tokens=256,
)
```

Works identically for **Groq, OpenRouter, Together AI, Azure OpenAI, Ollama**, and any other provider with an OpenAI-compatible SDK — just wrap the client.

### Anthropic

```python
import anthropic
from token_lens import AnthropicTokenLens   # ← use the dedicated adapter

client = AnthropicTokenLens(anthropic.Anthropic(api_key="..."))

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=256,
    messages=[{"role": "user", "content": "Hello!"}],
)
```

### LangGraph / LangChain

If you use `ChatOpenAI` or `init_chat_model` (rather than the raw OpenAI SDK), use the callback handler:

```python
from token_lens import TokenLensCallbackHandler

handler = TokenLensCallbackHandler()

# Pass as a callback to any LangGraph or LangChain invocation:
result = app.invoke(state, config={"callbacks": [handler]})

# Print the session summary manually (or it fires automatically at process exit):
handler.session_report()
```

---

## Configuration

Pass a `Config` object to tune or silence any rule:

```python
from token_lens import TokenLens, Config

client = TokenLens(
    OpenAI(...),
    Config(
        # Raise the system-prompt-repeat threshold from 3 to 5
        static_prompt_repeat_threshold=5,

        # Disable specific rules by ID
        disabled_rules={"TL007"},

        # Turn off ANSI colors (e.g. in CI)
        no_color=True,

        # Disable the automatic session summary at process exit
        auto_report_on_exit=False,

        # Turn off all analysis entirely (e.g. in production)
        enabled=False,
    ),
)
```

### Config reference

| Field | Default | Description |
|---|---|---|
| `enabled` | `True` | Master switch — set `False` in production |
| `no_color` | `False` | Disable ANSI colors in output |
| `auto_report_on_exit` | `True` | Print session summary when the process exits |
| `static_prompt_repeat_threshold` | `3` | Calls before TL001 fires |
| `history_message_threshold` | `20` | Non-system messages before TL002 fires |
| `high_tier_models` | (see below) | Model names considered "high tier" for TL004 |
| `simple_task_completion_token_threshold` | `80` | Completion tokens below which TL004 fires |
| `system_prompt_token_threshold` | `500` | Tokens above which TL005 fires |
| `redundant_context_jaccard_threshold` | `0.70` | Overlap ratio above which TL007 fires |
| `redundant_context_min_words` | `50` | Minimum message length for TL007 to apply |
| `pii_check_roles` | `{"user","system","tool"}` | Message roles to scan for PII (TL008) |
| `tool_result_token_threshold` | `500` | Token count above which TL011 fires |
| `max_tools_per_call` | `15` | Tool count above which TL012 fires |
| `spike_min_calls` | `5` | Minimum baseline calls before TL014 activates |
| `spike_multiplier` | `3.0` | Multiplier of session mean above which TL014 fires |
| `disabled_rules` | `set()` | Set of rule IDs to skip (e.g. `{"TL004", "TL007"}`) |

### Environment variables

| Variable | Effect |
|---|---|
| `NO_COLOR` | Disable ANSI colors (community standard) |
| `TOKEN_LENS_NO_COLOR` | Same as above, token-lens specific |

---

## Detection rules

| ID | Name | Phase | What triggers it | Suggestion |
|---|---|---|---|---|
| **TL001** | Static system prompt | post | Same system prompt ≥ N consecutive calls | Use prompt caching (OpenAI auto-caches >1024 tokens; Anthropic: `cache_control`) |
| **TL002** | Unbounded history | post | Non-system messages > 20 and growing | Use `trim_messages()` or add a summarization node |
| **TL003** | Duplicate prompt | post | Exact same message list sent ≥ 2 times | Add a result cache keyed on prompt hash |
| **TL004** | Model overkill | post | High-tier model, completion < 80 tokens, single message | Switch to a smaller/cheaper model for simple tasks |
| **TL005** | Long system prompt | post | System prompt > 500 tokens | Move static facts to retrieval; compress the prompt |
| **TL006** | Missing max_tokens | pre | Neither `max_tokens` nor `max_completion_tokens` set | Add `max_tokens=<expected upper bound>` |
| **TL007** | Redundant context | post | Two messages share >70% word overlap (>50 words each) | Deduplicate into the system prompt |
| **TL008** | PII in prompt | pre | Email, phone, credit card, SSN, or IP address in user/system/tool message | Remove or anonymize PII before sending to provider (GDPR/CCPA) |
| **TL009** | Secret in prompt | pre | API key, Bearer token, or PEM key detected in any message | Remove credential immediately; rotate any exposed key |
| **TL010** | Unversioned model | post | Unversioned model alias used (e.g. `gpt-4o`, `claude-3-5-sonnet`) | Pin to a dated version to prevent silent behavior changes |
| **TL011** | Tool result bloat | post | Tool/function result exceeds token threshold | Summarize or filter the result before returning to the model |
| **TL012** | Excessive tools | pre | More than N tools registered in one call | Filter tools to only those relevant to current context |
| **TL013** | Missing response_format | pre | System prompt requests JSON but `response_format` not set | Add `response_format={"type": "json_object"}` to guarantee valid JSON |
| **TL014** | Cost spike | post | Call tokens ≥ 3× session mean (after ≥5 baseline calls) | Investigate large tool results, unbounded history, or runaway prompts |
| **TL015** | n>1 completions | pre | `n > 1` passed in kwargs | Use `n=1`; vary temperature or prompt for diversity instead |

All rules fire to **stderr** only — your `stdout` pipeline is never interrupted.

---

## Privacy & data handling

**token-lens never sends any data anywhere.**

- All analysis runs in-process, in memory.
- No network connections are made by token-lens itself.
- No logs are written to disk.
- No telemetry, no analytics, no callbacks to external services.
- Your prompts, completions, and API keys are never touched by token-lens — they pass through to your SDK untouched.

This makes token-lens safe to deploy on enterprise servers and air-gapped environments.

---

## Enterprise / server deployment

For teams who want to enforce token efficiency standards across all services:

1. Add `token-lens` to your shared `requirements.txt` or `pyproject.toml`
2. Wrap your shared LLM client factory with `TokenLens`
3. Configure via `Config(enabled=os.getenv("TOKEN_LENS_ENABLED", "true") == "true")` to disable in production while keeping it active in staging/dev

```python
# shared_llm.py — your team's central LLM client module
import os
from openai import OpenAI
from token_lens import TokenLens, Config

_base_client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

client = TokenLens(
    _base_client,
    Config(enabled=os.getenv("ENV", "dev") != "prod"),
)
```

Every service that imports `client` from this module gets token-lens monitoring automatically — no per-service changes needed.

---

## Running the tests

```bash
# Install dev dependencies
pip install -e ".[accurate-counting,dev]"

# Run the full test suite
pytest

# With coverage
pytest --cov=token_lens --cov-report=term-missing
```

---

## Project structure

```
token_lens/
├── __init__.py                  # Public API: TokenLens, AnthropicTokenLens, Config, TokenLensCallbackHandler
├── _wrapper.py                  # TokenLens — OpenAI-compatible SDK wrapper
├── _anthropic_wrapper.py        # AnthropicTokenLens — native Anthropic SDK wrapper
├── _chat.py                     # Intercepts chat.completions.create()
├── _anthropic_messages.py       # Intercepts messages.create()
├── _session.py                  # Session state, CallRecord, NormalizedUsage
├── _analyzer.py                 # Runs detection rules pre- and post-call
├── _reporter.py                 # ANSI terminal output and session summary
├── _tokenizer.py                # Token counting (tiktoken or 4-char fallback)
├── _config.py                   # Config dataclass
├── langgraph_integration.py     # TokenLensCallbackHandler for LangGraph/LangChain
└── rules/
    ├── _base.py                 # Rule ABC, Finding dataclass, Severity enum
    ├── static_system_prompt.py  # TL001
    ├── unbounded_history.py     # TL002
    ├── duplicate_prompt.py      # TL003
    ├── model_overkill.py        # TL004
    ├── long_system_prompt.py    # TL005
    ├── missing_max_tokens.py    # TL006
    ├── redundant_context.py     # TL007
    ├── pii_in_prompt.py         # TL008
    ├── secret_in_prompt.py      # TL009
    ├── unversioned_model.py     # TL010
    ├── tool_result_bloat.py     # TL011
    ├── excessive_tools.py       # TL012
    ├── missing_response_format.py  # TL013
    ├── cost_spike.py            # TL014
    └── n_completions.py         # TL015
```

---

## Contributing

Contributions welcome. To add a new rule:

1. Create `token_lens/rules/tl00N_your_rule_name.py` implementing the `Rule` ABC
2. Add it to `token_lens/rules/__init__.py`
3. Register it in `_analyzer.py` `_build_rules()`
4. Add tests in `token_lens/tests/rules/test_tl00N_your_rule_name.py`

---

## License

MIT — see [LICENSE](LICENSE).
