{"id":50884128,"url":"https://github.com/claylo/ah-ah-ah","last_synced_at":"2026-06-15T15:02:38.044Z","repository":{"id":345298602,"uuid":"1183778731","full_name":"claylo/ah-ah-ah","owner":"claylo","description":"VUN token! TWO tokens! Count all the beautiful tokens ... offline! Ah-ah-ah!","archived":false,"fork":false,"pushed_at":"2026-03-19T23:28:07.000Z","size":445,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-22T21:43:43.516Z","etag":null,"topics":["claude","llm","openai","token-counting","tokenizer"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/claylo.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE-APACHE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null},"funding":{"github":"lovelesslabs","buy_me_a_coffee":"claylo"}},"created_at":"2026-03-17T00:10:48.000Z","updated_at":"2026-03-19T23:44:29.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/claylo/ah-ah-ah","commit_stats":null,"previous_names":["claylo/ah-ah-ah"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/claylo/ah-ah-ah","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/claylo%2Fah-ah-ah","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/claylo%2Fah-ah-ah/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/claylo%2Fah-ah-ah/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/claylo%2Fah-ah-ah/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/claylo","download_url":"https://codeload.github.com/claylo/ah-ah-ah/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/claylo%2Fah-ah-ah/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34367696,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-15T02:00:07.085Z","response_time":63,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["claude","llm","openai","token-counting","tokenizer"],"created_at":"2026-06-15T15:02:37.345Z","updated_at":"2026-06-15T15:02:38.023Z","avatar_url":"https://github.com/claylo.png","language":"Rust","funding_links":["https://github.com/sponsors/lovelesslabs","https://buymeacoffee.com/claylo"],"categories":[],"sub_categories":[],"readme":"# ah-ah-ah\n\n[![CI](https://github.com/claylo/ah-ah-ah/actions/workflows/ci.yml/badge.svg)](https://github.com/claylo/ah-ah-ah/actions/workflows/ci.yml)\n[![Crates.io](https://img.shields.io/crates/v/ah-ah-ah.svg)](https://crates.io/crates/ah-ah-ah)\n[![docs.rs](https://docs.rs/ah-ah-ah/badge.svg)](https://docs.rs/ah-ah-ah)\n[![MSRV](https://img.shields.io/badge/MSRV-1.89.0-blue.svg)](https://github.com/claylo/ah-ah-ah)\n\nOffline token counting for Claude and OpenAI models. No API calls, no network, no latency.\n\n\u003e *VUN token! TWO tokens! Count all the beautiful tokens ... offline! Ah-ah-ah!*\n\n\u003cdiv align=\"center\"\u003e\n\n![ah-ah-ah](https://raw.githubusercontent.com/claylo/ah-ah-ah/main/assets/vun-token-sm.jpg)\n\n\u003c/div\u003e\n\n## Quick start\n\n```rust\nuse ah_ah_ah::{Backend, MarkdownDecomposer, count_tokens};\n\n// Raw counting.\nlet report = count_tokens(\"Hello, world!\", None, Backend::Claude, None);\nassert_eq!(report.count, 4);\n\n// With a token budget.\nlet report = count_tokens(\"Hello, world!\", Some(100), Backend::Claude, None);\nassert!(!report.over_budget);\n\n// Markdown-aware counting (respects table cell boundaries).\nlet md = MarkdownDecomposer;\nlet table = \"| A | B |\\n|---|---|\\n| 1 | 2 |\";\nlet report = count_tokens(table, None, Backend::Claude, Some(\u0026md));\n```\n\n## Backends\n\n### Claude (default)\n\nGreedy longest-match tokenizer built from 38,360 API-verified Claude 3+ token\nstrings, using an Aho-Corasick automaton. The vocabulary was reverse-engineered\nby probing the Anthropic `count_tokens` API ~485,000 times (see\n[ctoc](https://github.com/nichochar/ctoc) and the vocabulary recovery work in\n[the fork that produced this dataset](https://github.com/claylo/ctoc/tree/extended-vocab)).\n\n**No merge table** — just greedy leftmost-longest matching. This is surprisingly\neffective: BPE's merge rules tend to produce tokens that are also the longest\nmatches at each position.\n\n### OpenAI\n\nExact o200k_base BPE encoding via [bpe-openai](https://crates.io/crates/bpe-openai).\nThis is the tokenizer used by GPT-4o, GPT-4.5, and o-series models.\n\n## Accuracy\n\nMeasured against the Anthropic `count_tokens` API on 18 diverse test strings\n(English prose, source code, URLs, JSON, CJK, emoji, markdown):\n\n| Category | Behavior | Typical delta |\n|----------|----------|---------------|\n| ASCII text \u0026 code | Near-exact | 0 to -2 tokens |\n| Latin prose | Mild overcount | +5-10% |\n| CJK characters | Significant overcount | +50-80% |\n| Emoji | Significant overcount | +30-40% |\n\n### Why overcounting happens\n\nThe vocabulary contains 33,339 ASCII tokens but only 3,156 Unicode tokens.\nWhen the greedy tokenizer encounters a byte sequence not in the vocabulary, each\n**unmatched byte is counted as one token**. A single CJK character is 3 UTF-8\nbytes, so an unknown CJK character costs 3 tokens in our count vs 1 in the real\ntokenizer.\n\nThis is the **safe direction** for budget enforcement — you'll never accidentally\nexceed a context window. Your budget estimates will be conservative.\n\n### Why undercounting happens (rare)\n\nOn some ASCII inputs, greedy longest-match produces 1-2 *fewer* tokens than\nthe real BPE tokenizer. This happens when BPE's learned merge order splits text\ndifferently than left-to-right greedy — the greedy approach occasionally finds\na more compact segmentation that BPE's bottom-up merge rules don't.\n\nUndercounting is rare (typically -1 to -2 on strings of 20+ tokens) and\nconcentrated in:\n- Punctuation-heavy text (JSON, markdown tables, error messages)\n- Strings mixing digits with special characters (`$42.99`)\n\nFor budget enforcement, add a small safety margin (2-3%) if your content is\npunctuation-heavy.\n\n### Accuracy by content type\n\n| Content | Example | Delta |\n|---------|---------|-------|\n| English greeting | `Hello, world!` | 0 (exact) |\n| English sentence | `The quick brown fox...` | 0 (exact) |\n| Rust code | `fn main() { println!(...) }` | -1 |\n| SQL query | `SELECT u.name, COUNT(*)...` | 0 (exact) |\n| URL | `https://example.com/path/...` | 0 (exact) |\n| ISO timestamp | `2026-03-16T14:30:00.000Z` | 0 (exact) |\n| JWT fragment | `eyJhbGciOiJIUzI1NiIs...` | 0 (exact) |\n| Rust (complex) | `fn count(\u0026self, text: \u0026str...)` | +2 |\n| JSON | `{\"name\": \"test\", ...}` | -2 |\n| Latin prose | `Lorem ipsum dolor sit amet...` | +7 |\n| CJK | `こんにちは世界` | +6 |\n| Emoji | `🌍🚀✨` | +3 |\n\n## Decomposer\n\nStructured content like markdown tables can cause greedy tokenizers to match\ntokens spanning cell boundaries (e.g., matching `| A` as a single token when\n`|` and ` A` should be separate). The `Decomposer` trait lets you plug in\nboundary-aware counting.\n\n`MarkdownDecomposer` is included — it uses pulldown-cmark to find tables, splits\nrows on `|`, and counts each cell independently. A fast-path heuristic skips\nthe parser entirely for content without table separator rows (`|---|`), so source\ncode with pipes (match arms, closures, shell pipes) doesn't pay the parsing cost.\n\n```rust\nuse ah_ah_ah::{Backend, Decomposer, count_tokens};\n\n// Custom decomposer example.\nstruct CsvDecomposer;\n\nimpl Decomposer for CsvDecomposer {\n    fn count(\u0026self, text: \u0026str, raw_count: \u0026dyn Fn(\u0026str) -\u003e usize) -\u003e usize {\n        text.lines()\n            .map(|line| {\n                let commas = line.bytes().filter(|\u0026b| b == b',').count();\n                let cells: usize = line.split(',').map(|c| raw_count(c)).sum();\n                commas + cells\n            })\n            .sum()\n    }\n}\n```\n\n## Smoke testing against the API\n\n`scripts/gen-token-fixtures.sh` compares ah-ah-ah counts against the live\nAnthropic `count_tokens` API (via Claude Code CLI). It measures a baseline\noverhead, subtracts it, and prints a comparison table:\n\n```\nTEXT                                                          AH-AH     API  DELTA\nHello, world!                                                     4       4     0\nThe quick brown fox jumps over the lazy dog.                     11      11     0\nこんにちは世界                                                    13       7    +6\n```\n\nRequires: `claude` CLI with valid auth, `jq`, and a built `cargo build --example count`.\n\n## License\n\nLicensed under either of:\n\n- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE))\n- MIT license ([LICENSE-MIT](LICENSE-MIT))\n\nat your option.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fclaylo%2Fah-ah-ah","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fclaylo%2Fah-ah-ah","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fclaylo%2Fah-ah-ah/lists"}