Capstone: Build and Publish a Python Library A tutorial capstone walks readers through building and packaging contextkit, a dependency-free Python library for LLM apps that provides estimate_tokens, estimate_cost, chunk_text and trim_messages plus a CLI with count and chunk commands. The author built the package, installed it into a clean environment and ran all 39 tests against that installed copy, but did not upload to PyPI because of no internet access or account, and the two GitHub workflows were not executed. The library accepts a count argument so callers can substitute a real tokenizer for the built-in four-characters-per-token estimate. 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/