Skip to main content

Trimwise

PyPI version

Query-aware compression within an exact budget.

Documentation · Getting started · API reference · PyPI

Trimwise selects useful exact source fragments and returns source-order output with original-input spans under an exact budget.

Trimwise is built for query-aware prompt assembly. Given a question, it selects the most useful exact source evidence from documents, blog posts, search results, logs, and tool output under an exact token, word, or character budget. Instead of keeping only text[:N], it can select complete fragments from across the source and reduce obvious repetition.

The result remains extractive: retained text comes from your input, keeps its original wording, and appears in source order. Trimwise does not search the web, retrieve documents, query a vector database, or rewrite your evidence.

When no question is available, it supports queryless mode which uses bounded structural trimming for readable source coverage.

Getting started

Installation

Trimwise supports Python 3.10 through 3.14.

What you need pip uv
Structural, lexical, or your own embedding callback python -m pip install trimwise uv add trimwise
Trimwise-managed semantic models on CPU python -m pip install "trimwise[semantic]" uv add "trimwise[semantic]"
Trimwise-managed semantic models on NVIDIA GPU python -m pip install "trimwise[semantic-gpu]" uv add "trimwise[semantic-gpu]"

The core installation includes Markdown parsing, token measurement, lexical ranking, and vector scoring. It does not install FastEmbed or download an embedding model.

Do not install the CPU and GPU semantic extras together. GPU use also requires compatible CUDA and cuDNN libraries. See Semantic Models and Async Use for callbacks, model loading, concurrency, and GPU details.

Basic usage

from trimwise import Trimmer

document = """\
# Incident report

The service became unavailable at 09:14. Initial checks focused on the network.

## Root cause

The team traced the failure to an expired credential.

## Decision

Credentials will now rotate automatically every 30 days.
"""

result = Trimmer().trim(
    document,
    limit=24,
    query="What caused the outage and how will it be prevented?",
)

print(result.text)
print(result.output_count)  # Always <= 24
print(result.strategy)  # Strategy.LEXICAL: auto resolved from the query
print(result.spans)  # Original-input Python-string offsets

Many sources, one shared limit

Use trim_context() when passages from several sources should compete for one budget. Add ContextSource wrapper text when source labels or closing delimiters must fit inside that same limit:

from trimwise import ContextSource, Trimmer

result = Trimmer().trim_context(
    [
        ContextSource(
            text=record["text"],
            prefix=f"--- Source: {record['title']} ({record['url']}) ---\n",
            suffix="\n--- End source ---",
        )
        for record in records
    ],
    limit=800,
    query="Which recommendations are supported by the reports?",
    separator="\n\n",
)

prompt_ready_context = result.text
assert result.output_count <= result.limit

The result keeps one row per input source, including empty excerpts. A source's prefix and suffix are emitted together only when that source contributes evidence, and result.text contains the fully measured rendering. Your surrounding instructions and answer space remain outside this limit. Plain string sources still use the original evidence-only accounting. See Many Sources, One Shared Limit for both modes and the difference from atrim_many().

Depending on the trimming strategy you want to use, find the corresponding starter code example - auto, structural, lexical, semantic and hyrbid.

Available trimming strategies

Strategy Use it when What it prioritizes
auto You want a safe default structural without a query; lexical with one
structural No question or task is available Document centrality, section coverage, and fitting beginning/end units
lexical Exact names, IDs, errors, URLs, or phrases matter BM25 matches between the query and source fragments
semantic The source may express the answer with different words or another supported language Embedding similarity between the query and candidates
hybrid Literal evidence and paraphrases both matter An equal blend of normalized BM25 and semantic scores

lexical, semantic, and hybrid require a nonblank query. Semantic and hybrid calls require either your own embedding callback or one of the FastEmbed extras.

Query-aware strategies may stop below the requested limit when the remaining candidates appear weakly related. The limit means “at most,” not “fill every token with progressively less useful text.”

Read Strategies for examples, scoring behavior, and practical tradeoffs.

How Trimwise compares with prompt compressors

Trimwise and model-based prompt compressors shorten text at different levels. Trimwise chooses complete source fragments before prompt assembly. Methods such as LLMLingua can remove individual tokens from an already assembled prompt, which can achieve much denser compression but may leave text that is harder for people to read or trace.

Approach What it keeps or removes Extra compression model Best fit
Prefix slicing Keeps only the beginning No Lowest possible overhead when missing later evidence is acceptable
Trimwise Selects complete source blocks, sentences, or lines and restores source order No for structural or lexical use Readable, source-backed excerpts with an exact final budget
LLMLingua family Removes tokens throughout a prompt; LongLLMLingua also uses the query and long-context position Yes Aggressive compression when downstream model performance matters more than human-readable excerpts
Selective Context Removes low-self-information tokens, phrases, or sentences Yes Pruning predictable language using a causal language model
RECOMP Selects sentences or generates a summary from retrieved documents Yes, with trained compressors Compressing RAG results for a downstream task, including abstractive synthesis when allowed

The LLMLingua family can preserve more task-relevant information per token at aggressive ratios. Its remaining tokens still come from the prompt, but complete sentence and block boundaries are not preserved. RECOMP's extractive path keeps selected sentences; its abstractive path can combine information across documents but no longer returns only original wording.

Choose Trimwise when evidence must stay readable, source fragments must remain verbatim and ordered, or adding another compression model is undesirable. Choose a model-based compressor when maximum compression density is more important and you can evaluate its effect on your own downstream task. The methods can also be chained: select broad evidence with Trimwise, then apply token-level compression. After the second step, Trimwise's whole-fragment and source-layout guarantees no longer describe the final prompt.

See the detailed research comparison for the differences among LLMLingua, LongLLMLingua, LLMLingua-2, Selective Context, and RECOMP.

Query-aware benchmark results

On a position-controlled 160-case benchmark, each method received the same source and question. The primary result is normalized contiguous required-span containment: every annotated source span must occur as one contiguous normalized passage, prohibited text must be absent, and the output must fit the budget. Trimwise Lexical leads at 128 tokens; Trimwise Hybrid leads from 256 through 1,024 tokens against the evaluated adapters.

Normalized contiguous required-span containment by output-token budget on 160 position-controlled cases. Trimwise Lexical leads at 128 tokens and Trimwise Hybrid leads at 256, 512, and 1,024 tokens against the three evaluated adapters.

Evaluated method or adapter 128 256 512 1,024
Trimwise Lexical 52.5% 60.0% 61.9% 66.2%
Trimwise Hybrid 49.4% 62.5% 66.9% 69.4%
RECOMP NQ extractive sentence adapter 27.5% 30.6% 35.0% 35.0%
LLMLingua GPT-2 token-pruning adapter 3.1% 7.5% 13.8% 22.5%
LongLLMLingua GPT-2 single-context adapter 0.6% 4.4% 6.9% 16.2%
Trimwise Hybrid at 512 tokens Observed result
Median warm compression at 512 tokens 42.8 ms
Median input-token reduction at 512 tokens 84.7%

The local ordered 80% and 90% sensitivity checks preserve the same ordering at every budget. This is a post-hoc robustness analysis over frozen outputs: it measures complete source-span survival, not semantic sufficiency, generated-answer quality, or every configuration in the compared method families. Latency is hardware-specific and excludes cold loading and thermal cooldown. The strict metric protocol, frozen manifest, and full sensitivity summary record the metric, inputs, and all results. The legacy bag-of-token case-pass result remains available as a historical diagnostic. The local benchmark environment resolves the published 0.2.0 release from PyPI.

An exploratory component study keeps Hybrid fixed while removing MMR, the adaptive evidence cutoff, or Markdown-aware segments. On this suite, the cutoff and structural segments help at 128 tokens; MMR shows no consistent strict-retention benefit. The full protocol, uncertainty intervals, and limits are in the benchmark documentation.

Documentation

Trimwise is available under the MIT License and maintained by AATBIT Labs.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

trimwise-0.6.0.tar.gz (39.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

trimwise-0.6.0-py3-none-any.whl (39.3 kB view details)

Uploaded Python 3

File details

Details for the file trimwise-0.6.0.tar.gz.

File metadata

  • Download URL: trimwise-0.6.0.tar.gz
  • Upload date:
  • Size: 39.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for trimwise-0.6.0.tar.gz
Algorithm Hash digest
SHA256 bb81aa73a43b123b69abd15326321219b15daceeb6ef887a5869b19abc83fe10
MD5 680fc8ee0d6731fdc916722c2269f292
BLAKE2b-256 c9781ce6ec2903f5171ed27239ee92aa4a7e4f7c3a7c6aeae62c574db2ffcd42

See more details on using hashes here.

Provenance

The following attestation bundles were made for trimwise-0.6.0.tar.gz:

Publisher: release.yml on tenwritehq/trimwise

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file trimwise-0.6.0-py3-none-any.whl.

File metadata

  • Download URL: trimwise-0.6.0-py3-none-any.whl
  • Upload date:
  • Size: 39.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for trimwise-0.6.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a56a99b5c8484830dc6d3bc02a541245ae1698e6f651d26f68e52dce8564fd67
MD5 9776bc098fc389c9133a53ead481d71f
BLAKE2b-256 1313ea25bc29b4802f47bfc734384875d5f838780fd8e0242352bc2e186827d7

See more details on using hashes here.

Provenance

The following attestation bundles were made for trimwise-0.6.0-py3-none-any.whl:

Publisher: release.yml on tenwritehq/trimwise

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

0.6.0 This release

2 files

0.5.0

2 files

0.4.1

2 files

0.4.0

2 files

0.3.0

2 files

0.2.0

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page