Prompt compression in Python: a practical Trimwise walkthrough
Compress prompts in Python with Trimwise. Run a query-aware example, inspect source spans, and compare retained evidence with first-N truncation.

TL;DR: Give Trimwise a document, a query and a token ceiling. In this example, lexical trimming keeps two rollback facts in 77 tokens from a 181-token source. Keeping the first 80 tokens loses one of them. You can inspect the exact retained text and its source spans, run the example locally, and try a query that does worse too.
I spent quite a lot of the previous Trimwise post talking about benchmarks, source retention and why first N truncation came back to haunt us. Useful, yes. But if you want to try the library, you probably want to start with an import and see what actually comes out. 😄
So, let’s do that. One small document, one question and a token budget. No LLM call or embedding model needed for this walkthrough.
Trimwise selects excerpts from text you already have. The retained wording comes from the source. Here, prompt compression means making the evidence smaller before assembling the prompt.
Get it running
Download the runnable example and extract it. Open a terminal in the trimwise-walkthrough directory, then:
python3 -m venv .venv
. .venv/bin/activate
python -m pip install -r requirements.txt
python walkthrough.py
On Windows PowerShell, create the environment with py -m venv .venv and activate it with .venv\Scripts\Activate.ps1. The two remaining python commands are the same.
The example pins Trimwise 0.7.0 and tiktoken 0.14.0. I ran it with Python 3.14.6; Trimwise supports Python 3.10 and newer according to its package metadata. The download also contains the full outputs and a record of the installed package versions.
If you are following along without the download, the installation is:
python -m pip install "trimwise==0.7.0" "tiktoken==0.14.0"
Lexical mode doesn’t need an embedding model or an API key. Tiktoken may fetch its encoding data the first time it is used, so a fresh environment can still need network access during setup.
A document with two things we need
Save this as document.md. Lantern is a fictional service, and the command below is example source text:
# Lantern rollout notes
Lantern serves the public catalogue API. These notes cover the staged gateway rollout.
## Rollback trigger
Start rollback if the HTTP 5xx rate stays above 2% for five consecutive minutes.
## Design notes
The status page now uses a darker header and larger service badges. The dashboard groups requests by region and moves the latency chart above the traffic chart. Screenshots for the release announcement are ready, and the documentation team has reviewed the new navigation labels.
## Team update
The next planning meeting is on Thursday. The team will review the feedback board, assign owners to the remaining documentation tasks, and collect suggestions for the next dashboard update. None of these presentation changes alters gateway routing.
## Rollback command
Run `LANTERN_GATEWAY=v1 ./restart-gateway` to restore the previous gateway.
Keep the canary disabled until the incident review is complete.
We want to know the rollback trigger and the rollback command. The trigger is near the top, while the command is near the end. The design discussion and meeting notes sit between them.
Yes, I placed the facts apart deliberately. This is a small example of what a positional cutoff can miss. If both answers were in the opening paragraph, keeping the beginning could work perfectly well.
Give it a query and an 80-token ceiling
This is the trimming call used in the example. Run it from the directory containing document.md:
from pathlib import Path
from trimwise import TrimConfig, Trimmer
TOKEN_ENCODING = "o200k_base"
TOKEN_BUDGET = 80
QUERY = "What is the rollback trigger and the rollback command?"
document = Path("document.md").read_text(encoding="utf-8")
trimmer = Trimmer(TrimConfig(token_encoding=TOKEN_ENCODING))
result = trimmer.trim(
document,
limit=TOKEN_BUDGET,
strategy="lexical",
query=QUERY,
)
print(result.text)
print(f"{result.output_count}/{result.limit} tokens")
I’m making the tokenizer and strategy explicit so the comparison is easy to reproduce. The usual default, auto, also resolves to lexical mode when you supply a nonblank query. Without a query, it chooses structural mode. See the strategy guide for those choices.
The returned text in this run is:
Lantern serves the public catalogue API. These notes cover the staged gateway rollout.
## Rollback trigger
Start rollback if the HTTP 5xx rate stays above 2% for five consecutive minutes.
## Rollback command
Run `LANTERN_GATEWAY=v1 ./restart-gateway` to restore the previous gateway.
Keep the canary disabled until the incident review is complete.
That is 77/80 tokens, down from 181 tokens in the complete document. Both facts we wanted survived. Some surrounding context survived too, including the instruction to keep the canary disabled.
The limit is a ceiling. Trimwise can return less text when it cannot fit another useful unit. It measures the complete returned excerpt, including any headings, separators and omission markers it emits. The API guide documents the result fields and call arguments.
Where did that text come from?
This is the part I care about when the excerpt is going into another system. I want to keep the connection to the original document.
for span in result.spans:
print(f"[{span.start}:{span.end}]")
print(repr(document[span.start:span.end]))
The offsets are Python string positions, with an inclusive start and an exclusive end. They are not token positions or UTF-8 byte positions. The source-span contract explains this distinction.
For the supplied file, the spans are:
| Source slice | What it contains |
|---|---|
document[25:215] |
The opening description, rollback heading and trigger. |
document[780:941] |
The rollback command section and canary instruction. |
You can take those exact slices from the original string. The script checks that they occur in the returned excerpt and that the spans are ordered, valid and nonoverlapping.
Notice the gap between 215 and 780. The design notes and team update have gone. The original document didn’t have these two sections next to each other, even though the excerpt now does.
There is no omission marker between them in this particular output. Trimwise adds markers when they fit; retained source takes priority when the budget is tight. A missing marker therefore doesn’t establish that nothing was skipped. The spans still show the gap. This behavior is covered in the guarantees and limitations.
In an application, I’d keep the document’s identity and version alongside these offsets. If the document changes, the same numbers may point somewhere else. And if I want to display citations, I can reconnect each retained slice to the actual source instead of treating the compressed text as a new document with no history.
Compare it with first N truncation
Now, give a simple baseline the same 80-token ceiling and same tokenizer. No character-count shortcut:
import tiktoken
encoding = tiktoken.get_encoding(TOKEN_ENCODING)
source_tokens = encoding.encode(document, disallowed_special=())
prefix = encoding.decode(source_tokens[:TOKEN_BUDGET])
print(prefix)
print(len(encoding.encode(prefix, disallowed_special=())))
This uses the tiktoken encoding API for both approaches. On the supplied ASCII fixture, decoding that token prefix gives an exact source prefix; the downloadable script checks that too.
The first-N result is:
# Lantern rollout notes
Lantern serves the public catalogue API. These notes cover the staged gateway rollout.
## Rollback trigger
Start rollback if the HTTP 5xx rate stays above 2% for five consecutive minutes.
## Design notes
The status page now uses a darker header and larger service badges. The dashboard groups requests by region and moves the latency chart above the traffic chart. Screenshots
It uses 80/80 tokens. We still have the trigger, but the command is gone. We spent some of the allowance on dashboard presentation details and stopped in the middle of that paragraph.
For this document and the primary query, the comparison is:
| Method | Source-text tokens | Trigger retained? | Command retained? |
|---|---|---|---|
| Full document | 181 | Yes | Yes |
| First 80 tokens | 80 | Yes | No |
| Trimwise lexical | 77 | Yes | Yes |
These columns check the two known facts in this fixture. We haven’t asked an LLM to produce an answer, measured answer accuracy or run a latency benchmark. The existing benchmark article covers a much wider evaluation.
The query matters. Here is the run that missed a fact
The first query I tried was:
What triggers rollback, and which command restores the previous gateway?
With the same document, tokenizer, lexical strategy and 80-token limit, it returned 79 tokens from the single span [530:941]. That kept the team update and rollback command, while dropping the trigger.
Well, that is useful to see before wiring it into an agent. The text was readable and within budget. It also lacked one of the things we needed.
For the primary run above, I changed the query to ask explicitly for the document’s two concepts: rollback trigger and rollback command. The selection changed and both survived. The download includes weaker-query-output.txt and the command to reproduce this earlier result too.
Lexical ranking uses query-term relevance, with selection heuristics around it. Wording can change what it keeps. Having a hard budget and exact source spans doesn’t guarantee that the best evidence survived. When evaluating your actual application, keep the real queries in the test set, including the awkward ones.
If your questions and documents tend to use different vocabulary, semantic or hybrid strategies are worth evaluating. They need embeddings, supplied by your own callback or the optional model integration. I haven’t tested those strategies in this walkthrough, and I wouldn’t assume they repair this particular miss without running them.
Put the excerpt into a prompt
The field you normally pass onward is result.text. For example, continuing from the code above:
prompt = f"""Answer the question using the supplied source excerpts.
If they lack the information needed, say what is missing.
Question: {QUERY}
Source: document.md
<source>
{result.text}
</source>
"""
print(len(encoding.encode(prompt, disallowed_special=())))
Our 80-token allowance covers the excerpt. The instructions, question, source label, delimiters and the model’s answer need their own space. Measure the final prompt with the tokenizer appropriate to your target model before deciding how much evidence room you have. o200k_base is the explicit choice for this exercise; your application may need another encoding or a custom counter.
Also keep instructions that must survive intact outside the material being trimmed. The source spans let you trace retained wording; you still need to assess whether the source is trustworthy and whether the excerpt contains enough evidence for the task.
The downloadable script includes assertions for token accounting, source slices and the two expected facts. If you change the document, query or budget, revisit those fixture-specific expectations too. A smaller result passing the token check is only one part of a useful result.
If you try Trimwise on your own documents, I’d be interested in the source, query and budget combinations where it leaves out something important. Those give us concrete cases to reproduce and improve. Meanwhile, you now have a small example to run alongside the benchmark numbers. 😄