Metadata-Version: 2.4
Name: tokenpak
Version: 1.5.0
Summary: Slash LLM costs with intelligent context compression, smart routing, and cost tracking
Home-page: https://github.com/tokenpak/tokenpak
Author: TokenPak
Author-email: Kevin Yang <hello@tokenpak.ai>
Maintainer-email: Kevin Yang <hello@tokenpak.ai>
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, whether in Source or
              Object form, 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 modifications
              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 any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              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 discussing and improving 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 individual or Legal Entity
              on behalf of whom a Contribution has been received by the Licensor and
              subsequently incorporated 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 combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated 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, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding any notices that do not
                  pertain to any part of the Derivative Works, 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 as an addendum 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 copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           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 redistributing 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 consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), 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 act 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 TokenPak Contributors
        
           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.
        
Project-URL: Homepage, https://github.com/tokenpak/tokenpak
Project-URL: Documentation, https://github.com/tokenpak/tokenpak/blob/main/README.md
Project-URL: Bug Reports, https://github.com/tokenpak/tokenpak/issues
Project-URL: Source Code, https://github.com/tokenpak/tokenpak
Project-URL: Changelog, https://github.com/tokenpak/tokenpak/blob/main/CHANGELOG.md
Keywords: llm,ai,proxy,token-optimization,openai,anthropic,compression,context,context-window,tokens,cost-tracking,routing
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: System :: Networking
Classifier: Topic :: Utilities
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: aiohttp>=3.9.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: click>=8.1.0
Requires-Dist: starlette>=0.36.0
Requires-Dist: uvicorn>=0.27.0
Requires-Dist: fastapi>=0.110.0
Requires-Dist: flask>=3.0.0
Requires-Dist: httpx>=0.26.0
Requires-Dist: h2<5,>=3
Requires-Dist: requests>=2.28.0
Requires-Dist: watchdog>=3.0.0
Requires-Dist: cryptography>=41.0.0
Requires-Dist: urllib3>=2.0.0
Requires-Dist: anthropic>=0.25.0
Requires-Dist: openai>=1.0.0
Requires-Dist: litellm>=1.0.0
Requires-Dist: llmlingua>=0.1.0
Requires-Dist: sentence-transformers>=2.2.0
Requires-Dist: tree-sitter-languages>=1.8.0; python_version < "3.13"
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pandas>=1.3.0
Requires-Dist: scipy>=1.10.0
Requires-Dist: rich>=13.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: pytest-benchmark>=4.0.0; extra == "dev"
Requires-Dist: pytest-mock>=3.12.0; extra == "dev"
Requires-Dist: black>=24.0.0; extra == "dev"
Requires-Dist: ruff>=0.2.0; extra == "dev"
Requires-Dist: import-linter>=2.0; extra == "dev"
Requires-Dist: tokenpak-tip-validator==0.1.1; extra == "dev"
Requires-Dist: bandit>=1.7; extra == "dev"
Provides-Extra: tokens
Requires-Dist: tiktoken>=0.5.0; extra == "tokens"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.5.0; extra == "docs"
Requires-Dist: mkdocs-material>=9.5.0; extra == "docs"
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.24.0; extra == "otel"
Requires-Dist: opentelemetry-sdk>=1.24.0; extra == "otel"
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.24.0; extra == "otel"
Requires-Dist: opentelemetry-exporter-otlp-proto-grpc>=1.24.0; extra == "otel"
Provides-Extra: crewai
Requires-Dist: crewai>=0.1.0; extra == "crewai"
Provides-Extra: autogen
Requires-Dist: pyautogen>=0.2.0; extra == "autogen"
Provides-Extra: llamaindex
Requires-Dist: llama-index-core>=0.10.0; extra == "llamaindex"
Provides-Extra: serve
Requires-Dist: uvicorn>=0.27.0; extra == "serve"
Requires-Dist: starlette>=0.36.0; extra == "serve"
Requires-Dist: pydantic>=2.0.0; extra == "serve"
Requires-Dist: fastapi>=0.100.0; extra == "serve"
Provides-Extra: telemetry
Requires-Dist: pydantic>=2.0.0; extra == "telemetry"
Requires-Dist: fastapi>=0.100.0; extra == "telemetry"
Requires-Dist: flask>=3.0.0; extra == "telemetry"
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# TokenPak — Up to 90%+ savings on direct API/CLI and other favorable uncached workloads. One command to configure your LLM proxy.

[![PyPI version](https://img.shields.io/pypi/v/tokenpak.svg)](https://pypi.org/project/tokenpak/)
[![Python 3.10+](https://img.shields.io/pypi/pyversions/tokenpak.svg)](https://pypi.org/project/tokenpak/)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
<!-- CI badge: pending initial workflow setup — add after .github/workflows/ lands -->

TokenPak is a local proxy that compresses your LLM context before it hits the API — fewer tokens, lower cost, same results. No code changes, no cloud, no credentials stored.

**Observed savings vary by integration path and provider-side cache behavior.** On direct API / CLI / uncached workloads the deterministic pipeline routinely lands in the 90%+ band. On provider-cached flows (Claude Code and similar) observed incremental savings can be much lower, because the provider's own cache already absorbs most of the token pool and TokenPak only optimizes the user-controlled portion. See [How we report savings](#how-we-report-savings) for the full framing.

> **Status: early preview.** Core compression engine and proxy are in place. `tokenpak setup` is the interactive wizard that detects your API keys, picks a compression profile, and starts the proxy. Per-client auto-integration (the forthcoming `tokenpak integrate` command) is not yet shipped — after `tokenpak setup` runs, point your client at `http://127.0.0.1:8766` via the one-line `export` below. See QUICKSTART at https://github.com/tokenpak/docs (rendered at tokenpak.ai/quickstart).

---

## Quick start

```bash
pip install tokenpak
tokenpak setup                      # interactive wizard — detects keys, picks a profile, starts the proxy
```

Then point your LLM client at the proxy with one env var. For the Anthropic SDK:

```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8766
```

Or for OpenAI-compatible clients:

```bash
export OPENAI_BASE_URL=http://127.0.0.1:8766
```

Then use your client normally. TokenPak compresses requests on the way out and logs savings to a local SQLite ledger.

If you prefer manual configuration (no wizard), `tokenpak start` brings the proxy up with defaults and you set `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` yourself.

Reproduce the savings floor locally: `make benchmark-headline` (asserts ≥30% reduction on a pinned agent-style fixture; the CI-enforced floor, not the ceiling).

See QUICKSTART at https://github.com/tokenpak/docs (rendered at tokenpak.ai/quickstart) for per-client setup (Claude Code, Cursor, Aider, and others).

---

## What savings look like

After a few proxied requests, `tokenpak savings` reports the cumulative reduction:

```
┌──────────────────────────────────────────────────────┐
│  TokenPak — Savings                                  │
├──────────────────────────────────────────────────────┤
│  Sample scenario       DevOps agent (config + logs)  │
│  Savings drivers                      dedup + alias  │
├──────────────────────────────────────────────────────┤
│  Original                                747 tokens  │
│  Compressed                              502 tokens  │
│  Saved                          245 tokens  (32.8%)  │
│  Cost saved (est.)                $0.00073 per call  │
├──────────────────────────────────────────────────────┤
│  Stages: dedup, alias, segmentize, directives        │
└──────────────────────────────────────────────────────┘
```

Actual numbers depend on your workload. Agent-style prompts with lots of repeated context see the biggest gains.

---

## Works with

Any LLM client that respects a custom base URL:

**Claude Code** · **Cursor** · **Cline** · **Continue.dev** · **Aider** · **OpenAI SDK** · **Anthropic SDK** · **LiteLLM** · **Codex**

Per-client configuration steps are in QUICKSTART at https://github.com/tokenpak/docs (rendered at tokenpak.ai/quickstart). Auto-wiring via a single `tokenpak integrate <client>` command is tracked for a future release.

---

## Install

```bash
pip install tokenpak
```

TokenPak's runtime dependencies include `anthropic`, `openai`, `fastapi`, `flask`, `litellm`, `llmlingua`, `pandas`, `pydantic`, `requests`, `rich`, `scipy`, `sentence-transformers`, `tree-sitter-languages`, `watchdog`, and a few others — all installed automatically. Note that `sentence-transformers` and `scipy` are large (several hundred MB of dependencies); expect `pip install` to take a few minutes on first install.

Requires Python 3.10+.

See QUICKSTART at https://github.com/tokenpak/docs (rendered at tokenpak.ai/quickstart) for virtual-env setup and first-run details.

---

## What's included

- **Context compression** — deterministic pipeline (dedup → alias → segmentize → directives). Up to 90%+ reduction on direct-API / uncached workloads; lower on provider-cached flows. CI-enforced ≥30% floor on the pinned agent-style fixture.
- **Local proxy** — runs at `127.0.0.1:8766`; zero cloud component.
- **Model routing** — configurable rules with fallback chains. Route-class policy presets ship under `tokenpak/services/policy_service/presets/` covering Claude Code (TUI/CLI/TMUX/SDK/IDE/CRON), Anthropic SDK, OpenAI SDK, and generic.
- **Cost & savings tracking** — per model, per session, per agent; local SQLite (`~/.tokenpak/monitor.db`).
- **Dashboard** — local web UI for visualizing savings at `http://127.0.0.1:8766/dashboard` (also reachable via `tokenpak dashboard`).
- **Vault indexing + semantic search** — index a directory; search without an LLM call.
- **A/B testing and request replay** — compare compression configs; re-run past requests.
- **Custom compression recipes** — author your own via `tokenpak recipe create/validate/test/benchmark`.

## How we report savings

TokenPak's savings aren't a single number because they shouldn't be. The real savings depend on where in your stack the compression runs:

- **Direct API calls, CLI tools, SDK integrations, and any uncached workload** — the compression pipeline operates on the full token pool. Observed savings routinely reach **90%+** on realistic agent-style prompts. The pinned CI benchmark measures this path; `make benchmark-headline` reproduces it.
- **Provider-cached flows (Claude Code and similar integrations)** — your client uses the provider's server-side prompt cache for most of the prompt (system prompt, tool definitions, historical turns). TokenPak only optimizes the **user-controlled portion** of the token pool. Observed incremental savings on these paths can be much lower — sometimes a few percent of total spend — because the provider cache already did the heavy lifting. This isn't TokenPak failing; it's an honest division of labor.

If you're evaluating TokenPak, start with a direct-API workload to see the compression pipeline's actual effectiveness, then layer in your cached flows to see the marginal contribution on top of the provider cache.

See QUICKSTART at https://github.com/tokenpak/docs (rendered at tokenpak.ai/quickstart) and API reference at https://github.com/tokenpak/docs (rendered at tokenpak.ai/api) to get started.

---

## Pro tier

**Pro** adds team-scale features on top of the OSS core. The OSS proxy, compression engine, client integrations, local dashboard, telemetry store, and route-class policy presets all stay in place — Pro layers the features a team running TokenPak at scale needs:

- **Team-scale cost attribution** — shared dashboard with multi-seat cost attribution: which workloads, which engineers, which tools drive spend, without wiring a BI pipeline.
- **Budget enforcement** — monthly budget caps map to hard `429 budget_exceeded` responses at request time. Not a passive dashboard: the proxy refuses to forward the request instead of silently burning through the rest of your budget.
- **Advanced routing policies** — cost-aware fallbacks, SLA-aware failover across providers, tiered routing by workload kind. OSS gives you the rule surface; Pro gives you the policy tooling that runs on top.
- **Enterprise credential management** — credential-rotation hooks, audit-log export, compliance rulesets that plug into the compression pipeline.
- **SSO, priority support, SLA** — dashboard SSO, priority support with an SLA, team onboarding.

Ships as the `tokenpak-paid` package via a private license-gated index at `pypi.tokenpak.ai`. See [tokenpak.ai/paid](https://tokenpak.ai/paid) to request access.

Installing the Pro package (after you have a license key):

```bash
pip install --index-url https://pypi.tokenpak.ai --extra-index-url https://pypi.org/simple tokenpak-paid
tokenpak activate <your-license-key>
```

Running `pip install tokenpak-paid-stub` from public PyPI fetches a discovery stub that prints these install instructions — so `pip` works as a learning path, not a dead end. The real paid code stays license-gated.

---

## Privacy + compliance

TokenPak is local-first by design. Every prompt, response, and API key stays on your machine. The only data that ever leaves your machine is the LLM request you were going to send anyway — forwarded to your configured provider using your own credentials.

- [**Privacy**](https://tokenpak.ai/compliance/privacy) — what's stored locally, what leaves, and every optional debug-logging escape hatch disclosed in full.
- [**Data Processing Agreement (template)**](https://tokenpak.ai/compliance/dpa) — IAPP-based template; marked pending legal review.
- [**Sub-processors**](https://tokenpak.ai/compliance/sub-processors) — Stripe / Cloudflare / Fly.io / GitHub / PyPI for the Pro-tier infrastructure; the OSS proxy has none.

For the runtime posture verification, run `tokenpak doctor --privacy` (plain-English summary) or `tokenpak doctor --conformance` (executes the TIP-1.0 self-conformance suite).

---

## Current limitations

Honest about what isn't ready yet:

- **No `tokenpak integrate <client>` auto-wire command** — configure clients by env var as shown above. Auto-wire is planned.
- **No published CI/CD** — releases are manual; automation is tracked in the release-workflow standards.
- **`tokenpak demo` is a compression-recipes demo** (shows recipes applied to a sample input), not the decorated savings panel above. The panel shows what `tokenpak savings` output can look like after real usage.

We'd rather ship an honest preview than an advertised product that doesn't match install-time reality.

---

## Non-localhost access

TokenPak's default is localhost-only. If you want to expose the proxy to other machines on your LAN, set an auth token:

```bash
export TOKENPAK_PROXY_AUTH_TOKEN=$(openssl rand -hex 32)
tokenpak start                # or tokenpak setup for first-time config
```

Clients then include the token on non-localhost requests:

```
X-TokenPak-Auth: <your-token>
```

Localhost (`127.0.0.1`, `::1`) traffic bypasses auth — your local tools keep working without changes. Non-localhost requests without the env var return `403 forbidden`; requests with a missing or wrong header return `401 unauthorized`. The token is stripped from the request before any upstream forward, so provider APIs (Anthropic, OpenAI, etc.) never see it.

---

## Support

- **Docs:** QUICKSTART at https://github.com/tokenpak/docs (rendered at tokenpak.ai/quickstart) · API reference at https://github.com/tokenpak/docs (rendered at tokenpak.ai/api) · FAQ at https://github.com/tokenpak/docs (rendered at tokenpak.ai/faq)
- **Issues:** [github.com/tokenpak/tokenpak/issues](https://github.com/tokenpak/tokenpak/issues)
- **Discussions:** [github.com/tokenpak/tokenpak/discussions](https://github.com/tokenpak/tokenpak/discussions)
- **Email:** hello@tokenpak.ai

---

## License

Apache 2.0. See [LICENSE](LICENSE).
