# Capstone: Build and Publish a Python Library

> Source: <https://zyvop.com/capstone-build-and-publish-a-python-library-qnc3x>
> Published: 2026-12-06 06:05:46+00:00

**Recommendation:** Inject your tokenizer's counting function into contextkit's count parameter rather than trusting the 4-characters-per-token default when budgeting context or estimating cost.
More in the playbook "Controlling LLM cost": <https://wpnews.pro/playbooks/llm-cost>

You've built a tool and a service. A library is different, because other people's code depends on it. In this capstone you'll build `contextkit`, a small library for LLM apps, and package it so anyone can install it with `pip`.

This is the last big project of Phase 1, so it pulls in a lot: clean functions, tests, type hints, packaging, Git, and CI. I did everything except the final upload. I built the package, looked inside it, installed it into a clean environment, and ran all 39 tests against that installed copy. I couldn't upload to PyPI, because I have no internet access or account here. The upload steps and the two GitHub workflows (which do parse as valid YAML) come from my knowledge and weren't run. As in the earlier projects, I ran the tests with a small stand-in for `pytest`.

## What we're building

LLM apps keep running into three small, boring problems. Roughly how many tokens is this text? How do I split a long document into pieces that fit? How do I trim a long chat so it still fits the budget? (The cost of an ever-growing history came up in Post 18, and chunking in Post 17.) `contextkit` solves those and nothing else:

| Name | What it does | 
|---|---|
| `estimate_tokens(text)` | A rough token count, at about 4 characters per token | 
| `estimate_cost(tokens, price)` | Dollars for some tokens, given a price per million | 
| `chunk_text(text, max_tokens, overlap_tokens)` | Splits text into chunks that fit, with optional overlap | 
| `trim_messages(messages, max_tokens)` | Drops the oldest messages until a chat fits | 
| `contextkit` command | `count` and`chunk` for a text file | 

Here's the library in use, run from a clean environment where only the installed package exists:

``` python
from contextkit import chunk_text, estimate_tokens, trim_messages

print(estimate_tokens("How do generators work?"))
print(chunk_text("one two three four five six", max_tokens=3))

chat = [
    {"role": "system", "content": "Be brief."},
    {"role": "user", "content": "First question, quite a long one."},
    {"role": "assistant", "content": "First answer."},
    {"role": "user", "content": "Second question?"},
]
print([m["content"] for m in trim_messages(chat, max_tokens=12)])
6
['one two', 'three four', 'five six']
['Be brief.', 'First answer.', 'Second question?']
```

Every function that counts tokens takes a `count` argument, so you can pass in a real tokenizer's counting function instead of the built-in estimate. That's deliberate, because the four-characters rule is crude (Post 19 showed how characters, bytes, and tokens differ). The library gives you a sensible default, and an easy way out of it.

## A library is not an app

Almost everything about the job changes when strangers will import your code:

| An app | A library | 
|---|---|
| You control every caller | Strangers call it in ways you never imagined | 
| Change anything, any time | The public API is a promise. Changing it can break other people | 
| Many dependencies are fine | Each dependency becomes your users' dependency, so keep few | 
| Docs are for teammates | The README and docstrings are the product's face | 
| One Python version | You declare a range of versions, and test it | 
| Deploy, and fix forward | A published version is permanent and can't be changed | 

That leads to the design rules we'll follow:

- **A small public surface.** Four functions, listed in`__all__` . Anything else is private.
- **Never change what you're given.** Functions return new values. A test checks it.
- **Raise clear errors** (`ValueError` with a message that says what's wrong), and document the edge cases.
- **No dependencies.** The package installs instantly, and can't conflict with anything.
- **Accept the counter as a parameter,** the dependency injection from Post 24, so the library works with any tokenizer.
- **Ship type hints,** plus a marker file that tells type checkers to use them.

## The plan

```
contextkit-demo/
├── pyproject.toml
├── README.md
├── LICENSE
├── CHANGELOG.md
├── .gitignore
├── .github/workflows/
│   ├── ci.yml            # test on several Python versions, build, check the wheel
│   └── publish.yml       # build, check, and publish when you make a release
├── scripts/check_wheel.py
├── src/contextkit/
│   ├── __init__.py       # the public API and the version
│   ├── tokens.py
│   ├── chunking.py
│   ├── messages.py
│   ├── cli.py
│   └── py.typed          # an empty file: "this package has type hints"
└── tests/test_contextkit.py
```

A note on names, because it matters later. PyPI has two kinds: the **distribution name** you `pip install` (here `contextkit-demo`) and the **import name** you write in code (` contextkit`). They don't have to match, but two packages that provide the same import name will overwrite each other's files. I haven't checked either name on PyPI, since I can't reach it, so **pick your own distinctive names for both** before you publish. The distribution name appears in two places, `pyproject.toml` and `__init__.py`.

## Step 0: set up

```
mkdir contextkit-demo && cd contextkit-demo
git init -b main
python -m venv .venv
source .venv/bin/activate
mkdir -p src/contextkit tests scripts
```

We use the `src/` layout from Post 12. It keeps the code you import in tests honest: you can't accidentally import the folder next to you instead of the installed package.

## Step 1: token estimates

`src/contextkit/tokens.py`:

``` php
import math

def estimate_tokens(text: str, chars_per_token: float = 4.0) -> int:
    """Estimate how many tokens a piece of text will use.

    This is a rough rule of thumb for English: about one token per four characters.
    Real tokenizers differ, so leave some headroom, or pass your own counter to the
    other functions in this package.

    >>> estimate_tokens("How do generators work?")
    6
    >>> estimate_tokens("")
    0
    >>> estimate_tokens("abcdefgh", chars_per_token=2)
    4
    """
    if chars_per_token <= 0:
        raise ValueError("chars_per_token must be positive")
    return math.ceil(len(text) / chars_per_token)

def estimate_cost(tokens: int, price_per_million: float) -> float:
    """The cost in dollars of some tokens, at a price per million tokens.

    >>> estimate_cost(500_000, 3.0)
    1.5
    """
    if tokens < 0 or price_per_million < 0:
        raise ValueError("tokens and price_per_million must not be negative")
    return tokens / 1_000_000 * price_per_million
```

The examples inside the docstrings, the lines starting with `>>>`, are real tests. Python's `doctest` module runs them and compares the output. That gives you documentation that can't go stale: if the code changes and the example doesn't, the check fails. I ran them for all three modules, and our test suite runs them too:

```
contextkit.tokens      examples run: 4, failed: 0
contextkit.chunking    examples run: 4, failed: 0
contextkit.messages    examples run: 3, failed: 0
```

## Step 2: chunking

`src/contextkit/chunking.py`:

``` python
from collections.abc import Callable

from contextkit.tokens import estimate_tokens

TokenCounter = Callable[[str], int]

def _overlap_tail(words: list[str], budget: int, count: TokenCounter) -> list[str]:
    """The most recent words that fit in `budget` tokens."""
    tail: list[str] = []
    for word in reversed(words):
        candidate = [word, *tail]
        if count(" ".join(candidate)) > budget:
            break
        tail = candidate
    return tail

def chunk_text(
    text: str,
    max_tokens: int,
    overlap_tokens: int = 0,
    count: TokenCounter = estimate_tokens,
) -> list[str]:
    """Split text into chunks that fit in max_tokens, breaking only between words.

    Neighbouring chunks share up to overlap_tokens of text, so a sentence that is cut
    at a boundary still appears whole in one of them. Pass `count` to use a real
    tokenizer instead of the built-in estimate.

    A single word that is longer than max_tokens becomes a chunk of its own, so that
    chunk can be over the limit.

    >>> chunk_text("one two three four five six", max_tokens=3)
    ['one two', 'three four', 'five six']
    >>> chunk_text("one two three four five six", max_tokens=3, overlap_tokens=1)
    ['one two', 'two three', 'four five', 'five six']
    >>> chunk_text("a b c d e", max_tokens=2, count=lambda s: len(s.split()))
    ['a b', 'c d', 'e']
    >>> chunk_text("", max_tokens=5)
    []
    """
    if max_tokens < 1:
        raise ValueError("max_tokens must be at least 1")
    if not 0 <= overlap_tokens < max_tokens:
        raise ValueError("overlap_tokens must be at least 0 and less than max_tokens")

    chunks: list[str] = []
    window: list[str] = []
    for word in text.split():
        if window and count(" ".join([*window, word])) > max_tokens:
            chunks.append(" ".join(window))
            window = _overlap_tail(window, overlap_tokens, count)
            # the overlap may leave too little room for the new word, so drop its oldest words
            while window and count(" ".join([*window, word])) > max_tokens:
                window.pop(0)
        window.append(word)
    if window:
        chunks.append(" ".join(window))
    return chunks
```

The idea is a **sliding window** (Post 17). Words go into a window until adding the next one would break the budget. Then the window becomes a chunk, and the next window starts with the last few words of the old one, as many as fit in `overlap_tokens`. Run the doctest example by hand to see it: with a budget of 3 tokens and an overlap of 1, `"one two three four five six"` becomes `['one two', 'two three', 'four five', 'five six']`, and each neighbouring pair shares a word.

Some details are worth a look:

- **The overlap can't crowd out the new word.** If the shared words plus the next word wouldn't fit, the`while` loop drops the oldest shared words until they do. Without it, a big overlap could produce chunks over the limit.
- **The settings are validated up front.**`overlap_tokens` must be less than`max_tokens` , or the window could never move forward.
- **The docstring admits a limitation:** a single word longer than the whole budget becomes its own, oversized chunk, since we only break between words. A test pins that behavior down. Documenting an edge case you chose not to solve is far better than leaving people to discover it.
- **It's simple and not the fastest.** It re-counts the window every time, which is fine for chunks of a few hundred tokens and would be slow for huge ones. That's a fair trade for code you can read in one sitting, and it works with any counting function.

## Step 3: trimming a chat

`src/contextkit/messages.py`:

``` python
from collections.abc import Sequence

from contextkit.chunking import TokenCounter
from contextkit.tokens import estimate_tokens

Message = dict[str, str]

def _check(message: object) -> None:
    if (
        not isinstance(message, dict)
        or not isinstance(message.get("role"), str)
        or not isinstance(message.get("content"), str)
    ):
        raise ValueError("each message must be a dict with string 'role' and 'content' fields")

def trim_messages(
    messages: Sequence[Message],
    max_tokens: int,
    count: TokenCounter = estimate_tokens,
    keep_system: bool = True,
) -> list[Message]:
    """Drop the oldest messages until the conversation fits in max_tokens.

    System messages are always kept (unless keep_system is False). Of the others, the
    newest are kept, with no gaps: once one message doesn't fit, every older one is
    dropped too. The result is a new list in the original order. The messages
    themselves are not copied or changed.

    If even the newest message doesn't fit, only the system messages are returned.
    Raises ValueError if the system messages alone use more than max_tokens.

    >>> chat = [
    ...     {"role": "system", "content": "Be brief."},
    ...     {"role": "user", "content": "First question, quite a long one."},
    ...     {"role": "assistant", "content": "First answer."},
    ...     {"role": "user", "content": "Second question?"},
    ... ]
    >>> [m["content"] for m in trim_messages(chat, max_tokens=12)]
    ['Be brief.', 'First answer.', 'Second question?']
    >>> [m["content"] for m in trim_messages(chat, max_tokens=100)] == [m["content"] for m in chat]
    True
    """
    for message in messages:
        _check(message)
    if max_tokens < 1:
        raise ValueError("max_tokens must be at least 1")

    is_kept_system = [keep_system and m["role"] == "system" for m in messages]
    budget = max_tokens - sum(count(m["content"]) for m, kept in zip(messages, is_kept_system) if kept)
    if budget < 0:
        raise ValueError(f"the system messages alone use more than max_tokens ({max_tokens})")

    keep = set(index for index, kept in enumerate(is_kept_system) if kept)
    for index in range(len(messages) - 1, -1, -1):
        if is_kept_system[index]:
            continue
        cost = count(messages[index]["content"])
        if cost > budget:
            break
        keep.add(index)
        budget -= cost
    return [message for index, message in enumerate(messages) if index in keep]
```

The rules are written into the docstring, because users will rely on them:

- **System messages are always kept,** since they carry the instructions. They count against the budget, and if they alone exceed it, you get a`ValueError` , not a silently broken chat.
- **Of the rest, the newest win, with no gaps.** Once one message doesn't fit, every older one is dropped too. Keeping a tiny old message while dropping a bigger newer one would leave a conversation with a hole in the middle, which confuses a model more than a shorter history does.
- **The input list is never modified,** and the result keeps the original order.
- **If even the newest message doesn't fit,** only the system messages come back. The caller can see that and decide what to do.

## Step 4: the public face

`src/contextkit/__init__.py` decides what the package *is*, from a user's point of view:

```
"""Small helpers for LLM apps: estimate tokens, chunk text, and trim chat history to a budget."""

from importlib.metadata import PackageNotFoundError, version

from contextkit.chunking import TokenCounter, chunk_text
from contextkit.messages import Message, trim_messages
from contextkit.tokens import estimate_cost, estimate_tokens

try:
    __version__ = version("contextkit-demo")
except PackageNotFoundError:    # running from a source folder that has not been installed
    __version__ = "0.0.0+unknown"

__all__ = [
    "Message",
    "TokenCounter",
    "__version__",
    "chunk_text",
    "estimate_cost",
    "estimate_tokens",
    "trim_messages",
]
```

Two things to notice. `__all__` lists the public names, so `from contextkit import *` and documentation tools only see those. And the **version lives in one place**, `pyproject.toml`. At runtime, `importlib.metadata.version` reads it from the installed package's metadata, so the number can't drift between the code and the package. When the package isn't installed, such as when you run straight from the source folder, we fall back to a clearly fake `0.0.0+unknown` instead of crashing.

The command line tool, `src/contextkit/cli.py`, follows the conventions from the first project: `main` returns an exit code, errors go to stderr, and bad usage exits with 2.

``` python
import argparse
import sys
from pathlib import Path

from contextkit import __version__
from contextkit.chunking import chunk_text
from contextkit.tokens import estimate_cost, estimate_tokens

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="contextkit", description="Count tokens and split text for LLM apps.")
    parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
    commands = parser.add_subparsers(dest="command", required=True, metavar="command")

    count = commands.add_parser("count", help="estimate the tokens (and cost) of a file")
    count.add_argument("file", help="path to a text file, or - to read standard input")
    count.add_argument("--price", type=float, help="price in dollars per million tokens")

    chunk = commands.add_parser("chunk", help="split a file into chunks that fit a token budget")
    chunk.add_argument("file", help="path to a text file, or - to read standard input")
    chunk.add_argument("--max-tokens", type=int, default=200, help="largest chunk size (default: 200)")
    chunk.add_argument("--overlap", type=int, default=0, help="tokens shared by neighbouring chunks (default: 0)")
    return parser

def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        text = sys.stdin.read() if args.file == "-" else Path(args.file).read_text(encoding="utf-8")
    except OSError as error:
        print(f"contextkit: error: {error}", file=sys.stderr)
        return 2

    if args.command == "count":
        tokens = estimate_tokens(text)
        print(f"characters: {len(text)}")
        print(f"words: {len(text.split())}")
        print(f"estimated tokens: {tokens}")
        if args.price is not None:
            print(f"estimated cost: ${estimate_cost(tokens, args.price):.4f}")
        return 0

    try:
        chunks = chunk_text(text, args.max_tokens, args.overlap)
    except ValueError as error:
        print(f"contextkit: error: {error}", file=sys.stderr)
        return 2
    for number, piece in enumerate(chunks, start=1):
        print(f"--- chunk {number} ({estimate_tokens(piece)} tokens) ---")
        print(piece)
    return 0

if __name__ == "__main__":
    sys.exit(main())
```

## Step 5: tests

`tests/test_contextkit.py` covers each function, every error, the command line, and the docstring examples:

``` python
import copy
import doctest
import io
import random

import pytest

import contextkit
from contextkit import chunk_text, chunking, estimate_cost, estimate_tokens, messages, tokens, trim_messages
from contextkit.cli import main

# ---- tokens ----

@pytest.mark.parametrize("text, expected", [
    ("", 0),
    ("a", 1),
    ("abcd", 1),
    ("abcde", 2),
    ("How do generators work?", 6),
])
def test_estimate_tokens_rounds_up(text, expected):
    assert estimate_tokens(text) == expected

def test_estimate_tokens_can_use_another_ratio():
    assert estimate_tokens("abcdefgh", chars_per_token=2) == 4

def test_estimate_tokens_rejects_a_bad_ratio():
    with pytest.raises(ValueError):
        estimate_tokens("text", chars_per_token=0)

def test_estimate_cost():
    assert estimate_cost(500_000, 3.0) == 1.5
    assert estimate_cost(0, 3.0) == 0
    with pytest.raises(ValueError):
        estimate_cost(-1, 3.0)
    with pytest.raises(ValueError):
        estimate_cost(10, -3.0)

# ---- chunking ----

def test_chunks_fit_the_budget():
    assert chunk_text("one two three four five six", max_tokens=3) == ["one two", "three four", "five six"]

def test_overlap_repeats_words_at_the_boundary():
    assert chunk_text("one two three four five six", max_tokens=3, overlap_tokens=1) == [
        "one two", "two three", "four five", "five six",
    ]

def test_empty_text_gives_no_chunks():
    assert chunk_text("", max_tokens=5) == []
    assert chunk_text("   \n  ", max_tokens=5) == []

@pytest.mark.parametrize("max_tokens, overlap", [(0, 0), (-1, 0), (3, 3), (3, 4), (3, -1)])
def test_bad_settings_are_rejected(max_tokens, overlap):
    with pytest.raises(ValueError):
        chunk_text("some text", max_tokens=max_tokens, overlap_tokens=overlap)

def test_a_custom_counter_is_used():
    count_words = lambda text: len(text.split())
    assert chunk_text("a b c d e", max_tokens=2, count=count_words) == ["a b", "c d", "e"]

def test_a_word_longer_than_the_budget_gets_its_own_chunk():
    long_word = "enormous" * 3
    assert chunk_text(f"tiny {long_word} tiny", max_tokens=2) == ["tiny", long_word, "tiny"]

def test_random_texts_keep_every_word_in_order_and_respect_the_budget():
    rng = random.Random(7)
    for _ in range(300):
        words = [f"w{i}" + "z" * rng.randint(0, 4) for i in range(rng.randint(1, 60))]
        max_tokens = rng.randint(3, 10)
        overlap = rng.randint(0, max_tokens - 1)
        chunks = chunk_text(" ".join(words), max_tokens, overlap)

        previous_start, previous_end = -1, 0
        for chunk in chunks:
            assert estimate_tokens(chunk) <= max_tokens
            pieces = chunk.split()
            start = words.index(pieces[0])
            assert pieces == words[start:start + len(pieces)]    # real, consecutive words
            assert start <= previous_end                          # no gap between chunks
            assert start > previous_start                         # always moving forward
            previous_start, previous_end = start, start + len(pieces)
        assert previous_end == len(words)                         # nothing was left off the end

# ---- trimming chat history ----

def make_chat():
    return [
        {"role": "system", "content": "Be brief."},
        {"role": "user", "content": "First question, quite a long one."},
        {"role": "assistant", "content": "First answer."},
        {"role": "user", "content": "Second question?"},
    ]

def contents(chat):
    return [m["content"] for m in chat]

def test_trim_keeps_the_system_message_and_the_newest_messages():
    assert contents(trim_messages(make_chat(), max_tokens=12)) == ["Be brief.", "First answer.", "Second question?"]

def test_nothing_is_dropped_when_everything_fits():
    assert trim_messages(make_chat(), max_tokens=1000) == make_chat()

def test_the_input_is_not_changed():
    chat = make_chat()
    before = copy.deepcopy(chat)
    result = trim_messages(chat, max_tokens=12)
    assert chat == before
    assert result is not chat

def test_there_are_no_gaps_in_what_is_kept():
    chat = [
        {"role": "user", "content": "ok"},            # 1 token: it would fit, but is older than a message that doesn't
        {"role": "assistant", "content": "x" * 40},   # 10 tokens: doesn't fit
        {"role": "user", "content": "hi"},            # 1 token
    ]
    assert contents(trim_messages(chat, max_tokens=3)) == ["hi"]

def test_system_messages_that_do_not_fit_raise_an_error():
    with pytest.raises(ValueError):
        trim_messages([{"role": "system", "content": "x" * 400}], max_tokens=10)

def test_when_even_the_newest_message_is_too_big_only_system_messages_remain():
    chat = [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "x" * 400}]
    assert trim_messages(chat, max_tokens=10) == [chat[0]]

def test_system_messages_can_be_treated_like_any_other():
    chat = make_chat()
    assert contents(trim_messages(chat, max_tokens=8, keep_system=False)) == ["First answer.", "Second question?"]

@pytest.mark.parametrize("bad", [
    {"role": "user"},
    {"content": "no role"},
    {"role": "user", "content": 42},
    "just a string",
])
def test_malformed_messages_are_rejected(bad):
    with pytest.raises(ValueError):
        trim_messages([bad], max_tokens=10)

def test_a_custom_counter_is_used_for_messages():
    chat = make_chat()
    one_each = lambda text: 1
    assert len(trim_messages(chat, max_tokens=3, count=one_each)) == 3

# ---- the package itself ----

def test_docstring_examples_still_work():
    for module in (tokens, chunking, messages):
        assert doctest.testmod(module).failed == 0

def test_version_looks_like_a_version():
    parts = contextkit.__version__.split(".")
    assert len(parts) >= 3 and parts[0].isdigit()

def test_every_public_name_exists():
    for name in contextkit.__all__:
        assert hasattr(contextkit, name)

# ---- the command line ----

def test_count_prints_the_estimates(tmp_path, capsys):
    path = tmp_path / "note.txt"
    path.write_text("How do generators work?", encoding="utf-8")
    assert main(["count", str(path), "--price", "3"]) == 0
    out = capsys.readouterr().out
    assert "words: 4" in out
    assert "estimated tokens: 6" in out
    assert "estimated cost: $0.0000" in out

def test_chunk_prints_numbered_chunks(tmp_path, capsys):
    path = tmp_path / "note.txt"
    path.write_text("one two three four five six", encoding="utf-8")
    assert main(["chunk", str(path), "--max-tokens", "3"]) == 0
    out = capsys.readouterr().out
    assert "--- chunk 1 (2 tokens) ---" in out
    assert "five six" in out

def test_standard_input_can_be_used(monkeypatch, capsys):
    monkeypatch.setattr("sys.stdin", io.StringIO("abcdefgh"))
    assert main(["count", "-"]) == 0
    assert "estimated tokens: 2" in capsys.readouterr().out

def test_a_missing_file_exits_with_2(tmp_path, capsys):
    assert main(["count", str(tmp_path / "nope.txt")]) == 2
    assert "error" in capsys.readouterr().err

def test_bad_chunk_settings_exit_with_2(tmp_path, capsys):
    path = tmp_path / "note.txt"
    path.write_text("some text", encoding="utf-8")
    assert main(["chunk", str(path), "--max-tokens", "3", "--overlap", "3"]) == 2
    assert "overlap_tokens" in capsys.readouterr().err
```

A few choices stand out. The test `test_random_texts_keep_every_word_in_order_and_respect_the_budget` is a hand-rolled version of the property-based idea from Post 13: 300 random texts, each checked against rules that must always hold (every chunk fits the budget, chunks are made of real consecutive words, there are no gaps, and nothing is left off the end). It uses a seeded random generator, so a failure is repeatable. `test_there_are_no_gaps_in_what_is_kept` has comments explaining the setup, because the scenario is subtle. And `test_docstring_examples_still_work` runs the `doctest` checks inside the suite.

There are 28 test functions, which become 39 cases with `parametrize`, and all 39 passed. Then I ran the check that decides whether tests are worth anything, and broke the code seven ways, one at a time:

| Deliberate bug | Tests that failed | 
|---|---|
| Round token estimates down instead of up | 8 | 
| Overlap tail stops one word early (`>` became`>=` ) | 2 | 
| Overlap setting no longer validated | 4 | 
| System messages no longer protected | 4 | 
| Gaps allowed when trimming (`break` became`continue` ) | 1 | 
| Negative prices accepted | 1 | 
| A missing file exits with 0 | 1 | 

Every bug was caught, and after restoring the code all 39 passed again.

## Step 6: the packaging files

This is the part that turns a folder of code into something `pip` can install. `pyproject.toml`:

```
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"

[project]
name = "contextkit-demo"
version = "0.1.0"
description = "Small helpers for LLM apps: estimate tokens, chunk text, and trim chat history to a budget"
readme = "README.md"
requires-python = ">=3.10"
authors = [{ name = "Your Name", email = "[email protected]" }]
keywords = ["llm", "tokens", "chunking", "prompts"]
classifiers = [
    "Development Status :: 3 - Alpha",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: MIT License",
    "Programming Language :: Python :: 3",
    "Typing :: Typed",
]
dependencies = []

[project.urls]
Homepage = "https://github.com/YOUR-NAME/contextkit-demo"
Issues = "https://github.com/YOUR-NAME/contextkit-demo/issues"
Changelog = "https://github.com/YOUR-NAME/contextkit-demo/blob/main/CHANGELOG.md"

[project.optional-dependencies]
dev = ["pytest>=8.0"]

[project.scripts]
contextkit = "contextkit.cli:main"

[tool.setuptools.package-data]
contextkit = ["py.typed"]

[tool.pytest.ini_options]
testpaths = ["tests"]
```

Going through it:

- `[build-system]` says how to build the package, using setuptools here. (Other tools, such as hatchling, work too.)
- `name` **and** `version` are what PyPI and`pip` use. The version number needs a plan, and we'll make one in Step 9.
- `readme = "README.md"` becomes the long description on the PyPI page, so the README is the first thing a visitor sees.
- `requires-python = ">=3.10"` tells`pip` not to install it on older Pythons. The code uses`X | Y` type syntax, which needs 3.10.
- `dependencies = []` is a feature. Nothing to install, and nothing to conflict.
- **Classifiers** are standard labels used for searching and filtering on PyPI. I listed only what I could stand behind. Add specific Python version classifiers once your CI matrix has proven them.
- `[project.urls]` puts links to the repository, the issue tracker, and the changelog on the PyPI page. The`YOUR-NAME` parts are placeholders.
- `[project.scripts]` creates the`contextkit` command, exactly as in Post 27.
- `[tool.setuptools.package-data]` makes sure the empty`py.typed` file ships inside the package. Without it, type checkers won't see your hints.

On the license: I chose MIT, a short, permissive license, and used the standard text from choosealicense.com unchanged, with a year and a name. You must choose one. Code with no license can't legally be used by anyone else, no matter how public it is. The classifier line `License :: OSI Approved :: MIT License` is the older way to declare it. Newer packaging standards prefer a plain `license = "MIT"` expression, which needs a recent setuptools. My environment had an older one, so I used the classifier, which still works. Check the current packaging guide when you publish.

The README, `LICENSE`, and `.gitignore` are the other files. The README should open with one sentence about what the library does, then `pip install`, a short example, and a link to the license. Keep it short and accurate, and make sure every example in it actually runs. The `.gitignore` needs `dist/` and `build/` now, because building creates them, and you never commit build output.

A `CHANGELOG.md` records what changed in each release, for humans:

```
# Changelog

All notable changes are listed here. The format follows
[Keep a Changelog](https://keepachangelog.com), and the project follows
[Semantic Versioning](https://semver.org).

## [0.1.0] - 2026-11-22

### Added
- `estimate_tokens` and `estimate_cost`.
- `chunk_text`, with optional overlap and a pluggable token counter.
- `trim_messages`, which fits a chat history into a token budget.
- The `contextkit` command line tool with `count` and `chunk` commands.
```

## Step 7: build it, and look inside

Building turns your project into the two files PyPI hosts. The usual command is `python -m build`, after `pip install build`. I used `uv build --no-build-isolation`, which does the same job with the tools already in my environment, since I was offline. Either one leaves two files in `dist/`:

```
8416 bytes  contextkit-demo-0.1.0.tar.gz
  7466 bytes  contextkit_demo-0.1.0-py3-none-any.whl
```

The **wheel** (`.whl`) is the ready-to-install form: a zip file whose name says it's pure Python (`py3-none-any`), so one wheel works on every platform. The **sdist** (`.tar.gz`) is the source package, which `pip` falls back on if no wheel is available. I also checked that the sdist can be turned back into a working wheel, and it can.

**Always look inside what you built.** A wheel is just a zip:

```
contextkit/__init__.py
contextkit/chunking.py
contextkit/cli.py
contextkit/messages.py
contextkit/py.typed
contextkit/tokens.py
contextkit_demo-0.1.0.dist-info/LICENSE
contextkit_demo-0.1.0.dist-info/METADATA
contextkit_demo-0.1.0.dist-info/WHEEL
contextkit_demo-0.1.0.dist-info/entry_points.txt
contextkit_demo-0.1.0.dist-info/top_level.txt
contextkit_demo-0.1.0.dist-info/RECORD
```

And the metadata that PyPI will display:

```
Metadata-Version: 2.1
Name: contextkit-demo
Version: 0.1.0
Summary: Small helpers for LLM apps: estimate tokens, chunk text, and trim chat history to a budget
Author-email: Your Name <[email protected]>
Project-URL: Homepage, https://github.com/YOUR-NAME/contextkit-demo
Project-URL: Issues, https://github.com/YOUR-NAME/contextkit-demo/issues
Project-URL: Changelog, https://github.com/YOUR-NAME/contextkit-demo/blob/main/CHANGELOG.md
Keywords: llm,tokens,chunking,prompts
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest >=8.0 ; extra == 'dev'
```

The wheel has the package code, the `py.typed` marker, the license, and the entry point for the `contextkit` command. Note too what's *not* in the wheel: the tests. They're in the sdist, though:

```
contextkit-demo-0.1.0
contextkit-demo-0.1.0/LICENSE
contextkit-demo-0.1.0/PKG-INFO
contextkit-demo-0.1.0/README.md
contextkit-demo-0.1.0/pyproject.toml
contextkit-demo-0.1.0/setup.cfg
contextkit-demo-0.1.0/src
contextkit-demo-0.1.0/src/contextkit
contextkit-demo-0.1.0/src/contextkit/__init__.py
contextkit-demo-0.1.0/src/contextkit/chunking.py
contextkit-demo-0.1.0/src/contextkit/cli.py
contextkit-demo-0.1.0/src/contextkit/messages.py
contextkit-demo-0.1.0/src/contextkit/py.typed
contextkit-demo-0.1.0/src/contextkit/tokens.py
contextkit-demo-0.1.0/src/contextkit_demo.egg-info
contextkit-demo-0.1.0/src/contextkit_demo.egg-info/PKG-INFO
contextkit-demo-0.1.0/src/contextkit_demo.egg-info/SOURCES.txt
contextkit-demo-0.1.0/src/contextkit_demo.egg-info/dependency_links.txt
contextkit-demo-0.1.0/src/contextkit_demo.egg-info/entry_points.txt
contextkit-demo-0.1.0/src/contextkit_demo.egg-info/requires.txt
contextkit-demo-0.1.0/src/contextkit_demo.egg-info/top_level.txt
contextkit-demo-0.1.0/tests
contextkit-demo-0.1.0/tests/test_contextkit.py
```

Notice that `CHANGELOG.md` isn't in the sdist. Setuptools includes some files by default (the README and the license) and not others. If you want the changelog to travel with the source, add a `MANIFEST.in` file containing `include CHANGELOG.md`. It's a tiny thing, but a good example of why you look.

### The empty wheel

Here's a story about why looking inside matters. While I was preparing this post, my first build produced a wheel with **no code in it at all**. The build printed `Successfully built`, the file had a perfectly good name, and the metadata was fine. But my shell had been sitting in the wrong folder, one without a `src/` directory, and the build tool didn't complain, because a package with nothing in it is still a valid package. Had I uploaded it, the world would have received a library that imports as nothing.

That's why the project has `scripts/check_wheel.py`:

``` python
"""Fail if the built wheel is missing something it should contain."""

import sys
import zipfile
from pathlib import Path

REQUIRED_FILES = [
    "contextkit/__init__.py",
    "contextkit/chunking.py",
    "contextkit/cli.py",
    "contextkit/messages.py",
    "contextkit/tokens.py",
    "contextkit/py.typed",
]

def main() -> int:
    wheels = sorted(Path("dist").glob("*.whl"))
    if len(wheels) != 1:
        print(f"expected exactly one wheel in dist/, found {len(wheels)}", file=sys.stderr)
        return 1
    with zipfile.ZipFile(wheels[0]) as wheel:
        names = set(wheel.namelist())
        entry_points = next((wheel.read(n).decode() for n in names if n.endswith("entry_points.txt")), "")

    missing = [name for name in REQUIRED_FILES if name not in names]
    if missing:
        print(f"{wheels[0].name} is missing: {', '.join(missing)}", file=sys.stderr)
        return 1
    if "contextkit = contextkit.cli:main" not in entry_points:
        print("the 'contextkit' command is not declared in the wheel", file=sys.stderr)
        return 1
    print(f"{wheels[0].name} looks complete ({len(names)} files)")
    return 0

if __name__ == "__main__":
    sys.exit(main())
```

It opens the wheel and fails if any of the expected files are missing, or if the command isn't declared. On the good build:

``` bash
$ python scripts/check_wheel.py
contextkit_demo-0.1.0-py3-none-any.whl looks complete (12 files)
(exit code 0)
```

And when I reproduced my mistake, by building in a folder that had the `pyproject.toml` and README but no source code:

```
Successfully built dist/contextkit-demo-0.1.0.tar.gz
Successfully built dist/contextkit_demo-0.1.0-py3-none-any.whl

files in that wheel:
  contextkit_demo-0.1.0.dist-info/LICENSE
  contextkit_demo-0.1.0.dist-info/METADATA
  contextkit_demo-0.1.0.dist-info/WHEEL
  contextkit_demo-0.1.0.dist-info/entry_points.txt
  contextkit_demo-0.1.0.dist-info/top_level.txt

$ python scripts/check_wheel.py
contextkit_demo-0.1.0-py3-none-any.whl is missing: contextkit/__init__.py, contextkit/chunking.py, contextkit/cli.py, contextkit/messages.py, contextkit/tokens.py, contextkit/py.typed
(exit code 1)
```

The build tool said "Successfully built" both times. Only the check told the truth. The CI workflow runs this script on every push, and so does the publish workflow, right before anything is uploaded.

## Step 8: test what you'll actually ship

Your tests have been importing the code from `src/`. That's not what your users will run. They'll run the *installed wheel*. So create a completely clean virtual environment, install only the wheel, and test that, from a different folder:

```
python -m venv clean-venv
clean-venv/bin/python -m pip install dist/contextkit_demo-0.1.0-py3-none-any.whl
cd ..                                  # leave the project, so its src/ folder can't be imported by accident
```

The environment contains exactly this:

```
Package         Version
--------------- -------
contextkit-demo 0.1.0
pip             24.0
```

The library works, and it's the installed copy that's being imported (the path is inside `site-packages`, not your source folder). The version printed by the code matches the metadata, and `py.typed` was shipped:

```
imported from: /path/to/clean-venv/lib/python3.12/site-packages/contextkit/__init__.py
__version__ = 0.1.0 | metadata version = 0.1.0
py.typed shipped: True
```

And the command line works too, using a small text file. Here's `notes.txt`:

```
A generator produces values one at a time instead of building a whole list first. That keeps memory small when a file is huge. Streaming replies from a model use the same idea, because each piece is handed over as soon as it exists.
bash
$ contextkit count notes.txt --price 3.0
characters: 233
words: 44
estimated tokens: 59
estimated cost: $0.0002
```

Chunking with a budget of 20 tokens and an overlap of 5 (look at the repeated words at the end of one chunk and the start of the next):

``` bash
$ contextkit chunk notes.txt --max-tokens 20 --overlap 5
--- chunk 1 (19 tokens) ---
A generator produces values one at a time instead of building a whole list
--- chunk 2 (19 tokens) ---
a whole list first. That keeps memory small when a file is huge. Streaming
--- chunk 3 (20 tokens) ---
is huge. Streaming replies from a model use the same idea, because each piece is
--- chunk 4 (12 tokens) ---
each piece is handed over as soon as it exists.
```

And the error paths, which exit with code 2:

``` bash
$ contextkit count missing.txt
contextkit: error: [Errno 2] No such file or directory: 'missing.txt'
(exit code 2)

$ contextkit chunk notes.txt --max-tokens 3 --overlap 3
contextkit: error: overlap_tokens must be at least 0 and less than max_tokens
(exit code 2)
```

Finally, I ran the whole test suite against the installed copy, with no source folder on the import path, and confirmed which copy the tests imported:

```
39 passed, 0 failed
tests imported contextkit from: /path/to/clean-venv/lib/python3.12/site-packages/contextkit/__init__.py
```

If a file had been left out of the wheel, this is the step where tests would have failed. It's the closest you can get to "works for users" without a user.

## Step 9: versions, and promises

A version number is a message to your users. **Semantic Versioning** gives the numbers a meaning: `MAJOR.MINOR.PATCH`.

| Change | Bump | Example | 
|---|---|---|
| A bug fix, nothing else changes | PATCH | 0.1.0 to 0.1.1 | 
| A new feature that doesn't break anything | MINOR | 0.1.1 to 0.2.0 | 
| A change that can break existing code | MAJOR | 1.4.2 to 2.0.0 | 

Versions below 1.0.0 mean "this is still settling, and things may change". That's the honest label for a first release, and it's why our classifier says `Alpha`. When you're ready to promise stability, release 1.0.0, and from then on, treat the public API as a contract.

**Renaming or removing something?** Don't just do it. Keep the old name working for a while and warn people, using a `DeprecationWarning`. Here's the pattern, run for real:

``` python
import warnings

def chunk_by_tokens(text, max_tokens):
    return [text]

def split_text(*args, **kwargs):
    """Deprecated alias for chunk_by_tokens."""
    warnings.warn(
        "split_text() is deprecated and will be removed in 1.0; use chunk_by_tokens()",
        DeprecationWarning,
        stacklevel=2,
    )
    return chunk_by_tokens(*args, **kwargs)

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    result = split_text("hello", 5)

print("still works:", result)
print("warning:", caught[0].category.__name__, "-", caught[0].message)
print("reported at line:", caught[0].lineno)
still works: ['hello']
warning: DeprecationWarning - split_text() is deprecated and will be removed in 1.0; use chunk_by_tokens()
reported at line: 20
```

The old function still works, and the warning says what to use instead and when the old one goes away. The last line shows what `stacklevel=2` does: the warning is reported at the line that *called* `split_text` (line 20 of this script), not at a line inside the function, which is where the user needs to make the change. Remove it in the next major version, and say so in the changelog.

A release checklist:

1. Update `CHANGELOG.md` , moving the notes to a new version heading with a date.
2. Change the version in `pyproject.toml` . That's the only place.
3. Run the tests, build, and run the wheel check.
4. Commit with a message like `Release 0.1.1` .
5. Tag it: `git tag -a v0.1.1 -m "Release 0.1.1"` , then`git push --tags` .
6. Publish (Step 10).

One rule has no exceptions: **you can never reuse a version number.** Once `0.1.0` is on PyPI, that exact file is fixed forever, even if you delete it. If it has a bug, you release `0.1.1`.

## Step 10: publishing

Everything from here on is from my knowledge. I couldn't reach PyPI or run any of it, so follow the current documentation at packaging.python.org, and treat my commands as a map and not a script.

**First, a safe rehearsal.** PyPI has a separate practice site, **TestPyPI**, at test.pypi.org. It's a different site with its own accounts and its own copy of the package index. Publish there first, and install your package from it, to catch mistakes cheaply.

**Accounts and security.** Create accounts on both sites. Turn on two-factor authentication, which PyPI requires for publishing. There are two ways to authenticate an upload:

- **An API token.** You create a token on the PyPI website, and the upload uses the username`__token__` with the token as the password. Treat it like a password: never commit it, never paste it into a chat, and revoke it if it leaks (Post 12).
- **Trusted publishing.** Better, because**there's no secret to leak** . You tell PyPI "uploads from this GitHub repository, from this workflow file, using this environment, are allowed". GitHub then proves its identity to PyPI on each run, with a short-lived credential. You set it up on the PyPI website (for a project that doesn't exist yet, as a "pending publisher"), and the workflow below does the rest.

**Uploading by hand to TestPyPI**, with twine (installed with `pip install twine`):

```
twine check dist/*
twine upload --repository testpypi dist/*
```

`twine check` makes sure the README will render properly. (`uv publish` is an alternative that does the upload.) Then install it from TestPyPI into a clean environment, and try it:

```
python -m venv try-it
try-it/bin/pip install --index-url https://test.pypi.org/simple/ contextkit-demo
try-it/bin/contextkit --version
```

(Our package has no dependencies. If yours had some, you'd add `--extra-index-url https://pypi.org/simple/`, because TestPyPI doesn't carry most real libraries.)

**The real thing** is the same, with `twine upload dist/*` going to the real PyPI. After it succeeds, your package lives at `https://pypi.org/project/<your-name>/`, and anyone can run `pip install <your-name>`. Install it yourself in a clean environment, run the same checks as in Step 8, and look at the project page to see that the README displays well.

**Automating it with a workflow.** This file, `.github/workflows/publish.yml`, builds, checks, and publishes whenever you publish a release on GitHub, using trusted publishing:

```
name: Publish

on:
  release:
    types: [published]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - name: Build the package
        run: |
          pip install build
          python -m build
      - name: Check what is inside the wheel
        run: python scripts/check_wheel.py
      - uses: actions/upload-artifact@v4
        with:
          name: dist
          path: dist/

  publish:
    needs: build
    runs-on: ubuntu-latest
    environment: pypi
    permissions:
      id-token: write
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/
      - uses: pypa/gh-action-pypi-publish@release/v1
```

There are two jobs, so that the job holding upload permission is as small as possible. `build` makes the files and runs our wheel check. `publish` downloads them and uploads, and it's the only job with `id-token: write`, the permission that lets GitHub vouch for it. The `environment: pypi` line matches the environment name you register with PyPI, and you can require a manual approval on it. The `uses:` version tags change over time, so check the current ones.

The CI workflow tests on three Python versions, then builds and checks the package:

```
name: CI

on:
  push:
    branches: [main]
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.10", "3.11", "3.12"]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}
      - name: Install
        run: pip install -e ".[dev]"
      - name: Run the tests
        run: pytest

  package:
    runs-on: ubuntu-latest
    needs: test
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - name: Build the package
        run: |
          pip install build
          python -m build
      - name: Check what is inside the wheel
        run: python scripts/check_wheel.py
```

**Mistakes and recovery.** You can't edit or re-upload a published version, but you can **yank** it. That marks it as "don't install this unless someone asked for exactly this version", and it's the right response to a broken release, followed by a fixed one with a new number. Deleting is rarely the answer.

**Supply-chain habits** (Post 12 again): a name on PyPI is first come, first served, and near-copies of popular names exist to trick people, so check spelling before you install anything. Use trusted publishing or narrowly scoped tokens, turn on two-factor authentication, keep your dependencies few (ours are zero), and pin or review the GitHub Actions you use.

## A clean history, and the tag

As in the other projects, I committed as I built. The release is a tagged commit:

``` php
f27f114 (HEAD -> main, tag: v0.1.0) Add changelog and CI and publish workflows
45b9c59 Add a check that the built wheel contains the package
bf1f139 Add tests, including doctests and randomized checks
f25f5ed Add the public API and the command line tool
1e6a386 Add chat history trimming
40f0479 Add text chunking with overlap and a pluggable counter
8d5d1a5 Add token and cost estimates
97e5b52 Set up project skeleton with metadata and license
```

`git tag -a v0.1.0` marks the exact commit the release was built from, so anyone can come back to it later (Post 22). Your GitHub release, and therefore the publish workflow, hangs off that tag.

## Where to take it next

1. **Plug in a real tokenizer.** Add an optional extra, so`pip install contextkit-demo[tiktoken]` pulls in a tokenizer library, and show in the README how to pass its counting function as`count=` . Keep the zero-dependency default.
2. **Add** `chunk_by_sentences` , which respects sentence boundaries, using the sentence idea from Post 54.
3. **Add a** `MANIFEST.in` , so the changelog travels in the sdist.
4. **Run a type checker** such as mypy in CI, so the hints you ship are checked.
5. **Add more Python versions** to the CI matrix as new ones come out, and add their classifiers when they pass.
6. **Publish a docs page** with MkDocs or Sphinx, built from your docstrings.
7. **Publish it for real.** Rehearse on TestPyPI, release`0.1.0` , ask a friend to install it from a clean environment, and open an issue if anything is unclear. Then answer it.

## A definition of done

- The library has a small, documented public API, with type hints and a `py.typed` marker.
- Every function has a docstring with a working example, and a test for each error.
- The tests pass, and at least one of them fails when you break the code on purpose.
- You've built the package, **looked inside it,** and installed the wheel into a clean environment.
- The tests also pass against the installed copy.
- The version lives in one place, the changelog is current, and the release is tagged.
- No secret appears anywhere in the repository.
- CI is green, and the publish workflow (or your upload steps) has been rehearsed on TestPyPI.

## What to take away

- A library is a promise to strangers. Keep the public surface small, don't change what you're given, raise clear errors, and document the edges.
- Fewer dependencies mean fewer problems for everyone. Accept a function as a parameter, like `count=` , so users can plug in what they already have.
- The `src/` layout,`pyproject.toml` , and a build tool are all you need to make an installable package. The README, license, and changelog are part of the product.
- Look inside what you build. A build can succeed and produce an empty package, and a ten-line script can catch it.
- Test the thing you'll ship: install the wheel into a clean environment, and run your tests against that.
- Semantic Versioning tells users what to expect. Deprecate before you remove, and never reuse a version number.
- Rehearse on TestPyPI. Prefer trusted publishing to long-lived tokens, and keep secrets out of the repository.

**Previous:** Post 28, *Mini Project 2: A REST API with Tests, Docker, and CI*

**Next in the series:** Post 30, *The 30-Day DSA Practice Plan*, with an honest look at how much LeetCode you actually need.
