This page documents Trimwise 0.2.0 directly from its public Python source. Signatures, type annotations, and descriptions therefore stay aligned with the installed API. Expand Source code under any entry to inspect its implementation and source line numbers.

Trimwise intentionally exports only the seven objects below. Internal segmentation, measurement, ranking, semantic-adapter, and orchestration helpers are not part of the compatibility promise.

Trimming

Use Trimmer for synchronous or asynchronous trimming.

Trimmer

Reuse trimming configuration and an optional semantic backend.

Source code in src/trimwise/trimmer.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
class Trimmer:
    """Reuse trimming configuration and an optional semantic backend."""

    def __init__(
        self,
        config: TrimConfig | None = None,
        *,
        embedding_callback: EmbeddingCallback | None = None,
        async_embedding_callback: AsyncEmbeddingCallback | None = None,
    ) -> None:
        """Create a trimmer with validated reusable dependencies.

        Args:
            config: Optional custom configuration.
            embedding_callback: Optional synchronous query-and-passage embedder.
            async_embedding_callback: Optional asynchronous query-and-passage embedder.

        Raises:
            TypeError: If a supplied callback is not callable.
            ValueError: If both callback execution models are supplied.
        """
        if embedding_callback is not None and not callable(embedding_callback):
            raise TypeError("embedding_callback must be callable or None")
        if async_embedding_callback is not None and not callable(async_embedding_callback):
            raise TypeError("async_embedding_callback must be callable or None")
        if embedding_callback is not None and async_embedding_callback is not None:
            raise ValueError("only one embedding callback may be supplied")
        self.config = config or TrimConfig()
        self._embedding_callback = embedding_callback
        self._async_embedding_callback = async_embedding_callback
        self._semantic = SemanticEmbedder(self.config)

    def trim(
        self,
        text: str,
        limit: int,
        *,
        unit: BudgetUnit | str = BudgetUnit.TOKENS,
        strategy: Strategy | str = Strategy.AUTO,
        query: str | None = None,
        token_counter: Callable[[str], int] | None = None,
    ) -> TrimResult:
        """Retain high-signal source fragments within an exact budget.

        Args:
            text: Whole source string to trim.
            limit: Maximum output size in ``unit``.
            unit: Token, whitespace-word, or code-point character budget.
            strategy: Structural, lexical, semantic, hybrid, or automatic ranking.
            query: Task or question required by query-aware strategies.
            token_counter: Optional synchronous token measurement callback.

        Returns:
            Measured extractive trimming result.

        Raises:
            TypeError: If an argument is invalid or only an async embedder is available.
            ValueError: If an argument value or strategy/query combination is invalid.
            SemanticBackendError: If an explicitly requested semantic backend fails.
        """
        return self._trim(_TrimArguments(text, limit, unit, strategy, query, token_counter))

    async def atrim(
        self,
        text: str,
        limit: int,
        *,
        unit: BudgetUnit | str = BudgetUnit.TOKENS,
        strategy: Strategy | str = Strategy.AUTO,
        query: str | None = None,
        token_counter: Callable[[str], int] | None = None,
    ) -> TrimResult:
        """Run CPU and synchronous work outside the event loop.

        A configured asynchronous embedding callback is awaited on the calling event loop.
        Cancellation propagates to that callback, but cannot stop a worker thread already running.

        Args:
            text: Whole source string to trim.
            limit: Maximum output size in ``unit``.
            unit: Token, whitespace-word, or code-point character budget.
            strategy: Structural, lexical, semantic, hybrid, or automatic ranking.
            query: Task or question required by query-aware strategies.
            token_counter: Optional synchronous token measurement callback.

        Returns:
            Measured extractive trimming result.

        Raises:
            TypeError: If an argument has an unsupported type.
            ValueError: If an argument value or strategy/query combination is invalid.
            SemanticBackendError: If an explicitly requested semantic backend fails.
        """
        arguments = _TrimArguments(text, limit, unit, strategy, query, token_counter)
        callback = self._async_embedding_callback
        if callback is None:
            return await asyncio.to_thread(self._trim, arguments)

        prepared = await asyncio.to_thread(self._prepare, arguments)
        if isinstance(prepared, TrimResult):
            return prepared
        if prepared.request.strategy not in {Strategy.SEMANTIC, Strategy.HYBRID}:
            return await asyncio.to_thread(self._complete, prepared)

        query_text = prepared.request.query or ""
        passages = await asyncio.to_thread(_contextual_ranking_texts, prepared.segments)
        output = await invoke_async_embedding_callback(callback, query_text, passages)
        return await asyncio.to_thread(self._complete_with_embedding_output, prepared, output)

    def _trim(self, arguments: _TrimArguments) -> TrimResult:
        """Run one synchronous call through preparation, ranking, and selection.

        Args:
            arguments: Unvalidated public call values.

        Returns:
            Measured extractive trimming result.
        """
        prepared = self._prepare(arguments)
        if isinstance(prepared, TrimResult):
            return prepared
        return self._complete(prepared)

    def _prepare(self, arguments: _TrimArguments) -> TrimResult | _PreparedTrim:
        """Validate, measure, and segment without invoking a semantic backend.

        Args:
            arguments: Unvalidated public call values.

        Returns:
            An early result or prepared long input awaiting ranking.
        """
        resolved_unit = _parse_unit(arguments.unit)
        resolved_strategy, normalized_query = _resolve_strategy(
            _parse_strategy(arguments.strategy),
            arguments.query,
        )
        request = _TrimRequest(
            arguments.text,
            arguments.limit,
            resolved_unit,
            resolved_strategy,
            normalized_query,
            arguments.token_counter,
        )
        _validate_request(request)
        measurer = Measurer(
            resolved_unit,
            self.config.token_encoding,
            arguments.token_counter,
        )
        input_count = measurer.count(arguments.text)
        if arguments.limit == 0:
            return _result(
                _ComposedOutput("", ()), input_count, request, resolved_strategy, measurer
            )
        if input_count <= arguments.limit:
            spans = (SourceSpan(0, len(arguments.text)),) if arguments.text else ()
            output = _ComposedOutput(arguments.text, spans)
            return _result(output, input_count, request, resolved_strategy, measurer)

        segments = segment_text(arguments.text)
        if resolved_strategy is Strategy.STRUCTURAL:
            segments = _expand_structural_plaintext(segments)
        return _PreparedTrim(request, input_count, segments, measurer)

    def _complete(self, prepared: _PreparedTrim) -> TrimResult:
        """Rank and select one prepared input through a synchronous backend.

        Args:
            prepared: Validated, measured, and segmented input.

        Returns:
            Measured extractive trimming result.
        """
        request = _ranking_request(prepared)
        return self._select(prepared, self._rank(request))

    def _complete_with_embedding_output(
        self,
        prepared: _PreparedTrim,
        output: EmbeddingOutput,
    ) -> TrimResult:
        """Normalize asynchronous callback output before ranking and selection.

        Args:
            prepared: Validated, measured, and segmented input.
            output: Caller-provided query and passage vectors.

        Returns:
            Measured extractive trimming result.
        """
        vectors = normalize_callback_output(output, len(prepared.segments))
        ranking = _rank_with_semantic_vectors(_ranking_request(prepared), vectors)
        return self._select(prepared, ranking)

    def _rank(self, request: _RankingRequest) -> CandidateRanking:
        """Dispatch to the resolved ranking algorithm without a strategy hierarchy.

        Args:
            request: Segments and resolved ranking inputs.

        Returns:
            Strategy-specific candidate ranking.
        """
        if request.strategy is Strategy.STRUCTURAL:
            return rank_structural(request.segments, request.measurer)
        if request.strategy is Strategy.LEXICAL:
            return rank_lexical(request.segments, request.query or "", request.measurer)

        if self._async_embedding_callback is not None:
            raise TypeError("trim() cannot use async_embedding_callback; use atrim()")
        query = request.query or ""
        passages = _contextual_ranking_texts(request.segments)
        if self._embedding_callback is not None:
            vectors = embed_with_callback(self._embedding_callback, query, passages)
        else:
            vectors = self._semantic.embed(query, passages)
        return _rank_with_semantic_vectors(request, vectors)

    def _select(
        self,
        prepared: _PreparedTrim,
        ranking: CandidateRanking,
    ) -> TrimResult:
        """Select, compose, and measure ranked source fragments.

        Args:
            prepared: Validated, measured, and segmented input.
            ranking: Strategy-specific candidate scores and similarity behavior.

        Returns:
            Final measured extractive result.
        """
        request = prepared.request
        context = _SelectionContext(
            request.text,
            prepared.segments,
            ranking,
            prepared.measurer,
            request.limit,
            self.config.omission_marker,
            self.config.mmr_lambda,
        )
        output = (
            _select_structural(context)
            if request.strategy is Strategy.STRUCTURAL
            else _select_query_aware(context)
        )
        if output is None:
            output = _fallback_output(context)
        return _result(
            output,
            prepared.input_count,
            request,
            request.strategy,
            prepared.measurer,
        )

__init__

__init__(config: TrimConfig | None = None, *, embedding_callback: EmbeddingCallback | None = None, async_embedding_callback: AsyncEmbeddingCallback | None = None) -> None

Create a trimmer with validated reusable dependencies.

Parameters:

Name Type Description Default
config TrimConfig | None

Optional custom configuration.

None
embedding_callback EmbeddingCallback | None

Optional synchronous query-and-passage embedder.

None
async_embedding_callback AsyncEmbeddingCallback | None

Optional asynchronous query-and-passage embedder.

None

Raises:

Type Description
TypeError

If a supplied callback is not callable.

ValueError

If both callback execution models are supplied.

Source code in src/trimwise/trimmer.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def __init__(
    self,
    config: TrimConfig | None = None,
    *,
    embedding_callback: EmbeddingCallback | None = None,
    async_embedding_callback: AsyncEmbeddingCallback | None = None,
) -> None:
    """Create a trimmer with validated reusable dependencies.

    Args:
        config: Optional custom configuration.
        embedding_callback: Optional synchronous query-and-passage embedder.
        async_embedding_callback: Optional asynchronous query-and-passage embedder.

    Raises:
        TypeError: If a supplied callback is not callable.
        ValueError: If both callback execution models are supplied.
    """
    if embedding_callback is not None and not callable(embedding_callback):
        raise TypeError("embedding_callback must be callable or None")
    if async_embedding_callback is not None and not callable(async_embedding_callback):
        raise TypeError("async_embedding_callback must be callable or None")
    if embedding_callback is not None and async_embedding_callback is not None:
        raise ValueError("only one embedding callback may be supplied")
    self.config = config or TrimConfig()
    self._embedding_callback = embedding_callback
    self._async_embedding_callback = async_embedding_callback
    self._semantic = SemanticEmbedder(self.config)

trim

trim(text: str, limit: int, *, unit: BudgetUnit | str = TOKENS, strategy: Strategy | str = AUTO, query: str | None = None, token_counter: Callable[[str], int] | None = None) -> TrimResult

Retain high-signal source fragments within an exact budget.

Parameters:

Name Type Description Default
text str

Whole source string to trim.

required
limit int

Maximum output size in unit.

required
unit BudgetUnit | str

Token, whitespace-word, or code-point character budget.

TOKENS
strategy Strategy | str

Structural, lexical, semantic, hybrid, or automatic ranking.

AUTO
query str | None

Task or question required by query-aware strategies.

None
token_counter Callable[[str], int] | None

Optional synchronous token measurement callback.

None

Returns:

Type Description
TrimResult

Measured extractive trimming result.

Raises:

Type Description
TypeError

If an argument is invalid or only an async embedder is available.

ValueError

If an argument value or strategy/query combination is invalid.

SemanticBackendError

If an explicitly requested semantic backend fails.

Source code in src/trimwise/trimmer.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def trim(
    self,
    text: str,
    limit: int,
    *,
    unit: BudgetUnit | str = BudgetUnit.TOKENS,
    strategy: Strategy | str = Strategy.AUTO,
    query: str | None = None,
    token_counter: Callable[[str], int] | None = None,
) -> TrimResult:
    """Retain high-signal source fragments within an exact budget.

    Args:
        text: Whole source string to trim.
        limit: Maximum output size in ``unit``.
        unit: Token, whitespace-word, or code-point character budget.
        strategy: Structural, lexical, semantic, hybrid, or automatic ranking.
        query: Task or question required by query-aware strategies.
        token_counter: Optional synchronous token measurement callback.

    Returns:
        Measured extractive trimming result.

    Raises:
        TypeError: If an argument is invalid or only an async embedder is available.
        ValueError: If an argument value or strategy/query combination is invalid.
        SemanticBackendError: If an explicitly requested semantic backend fails.
    """
    return self._trim(_TrimArguments(text, limit, unit, strategy, query, token_counter))

atrim async

atrim(text: str, limit: int, *, unit: BudgetUnit | str = TOKENS, strategy: Strategy | str = AUTO, query: str | None = None, token_counter: Callable[[str], int] | None = None) -> TrimResult

Run CPU and synchronous work outside the event loop.

A configured asynchronous embedding callback is awaited on the calling event loop. Cancellation propagates to that callback, but cannot stop a worker thread already running.

Parameters:

Name Type Description Default
text str

Whole source string to trim.

required
limit int

Maximum output size in unit.

required
unit BudgetUnit | str

Token, whitespace-word, or code-point character budget.

TOKENS
strategy Strategy | str

Structural, lexical, semantic, hybrid, or automatic ranking.

AUTO
query str | None

Task or question required by query-aware strategies.

None
token_counter Callable[[str], int] | None

Optional synchronous token measurement callback.

None

Returns:

Type Description
TrimResult

Measured extractive trimming result.

Raises:

Type Description
TypeError

If an argument has an unsupported type.

ValueError

If an argument value or strategy/query combination is invalid.

SemanticBackendError

If an explicitly requested semantic backend fails.

Source code in src/trimwise/trimmer.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
async def atrim(
    self,
    text: str,
    limit: int,
    *,
    unit: BudgetUnit | str = BudgetUnit.TOKENS,
    strategy: Strategy | str = Strategy.AUTO,
    query: str | None = None,
    token_counter: Callable[[str], int] | None = None,
) -> TrimResult:
    """Run CPU and synchronous work outside the event loop.

    A configured asynchronous embedding callback is awaited on the calling event loop.
    Cancellation propagates to that callback, but cannot stop a worker thread already running.

    Args:
        text: Whole source string to trim.
        limit: Maximum output size in ``unit``.
        unit: Token, whitespace-word, or code-point character budget.
        strategy: Structural, lexical, semantic, hybrid, or automatic ranking.
        query: Task or question required by query-aware strategies.
        token_counter: Optional synchronous token measurement callback.

    Returns:
        Measured extractive trimming result.

    Raises:
        TypeError: If an argument has an unsupported type.
        ValueError: If an argument value or strategy/query combination is invalid.
        SemanticBackendError: If an explicitly requested semantic backend fails.
    """
    arguments = _TrimArguments(text, limit, unit, strategy, query, token_counter)
    callback = self._async_embedding_callback
    if callback is None:
        return await asyncio.to_thread(self._trim, arguments)

    prepared = await asyncio.to_thread(self._prepare, arguments)
    if isinstance(prepared, TrimResult):
        return prepared
    if prepared.request.strategy not in {Strategy.SEMANTIC, Strategy.HYBRID}:
        return await asyncio.to_thread(self._complete, prepared)

    query_text = prepared.request.query or ""
    passages = await asyncio.to_thread(_contextual_ranking_texts, prepared.segments)
    output = await invoke_async_embedding_callback(callback, query_text, passages)
    return await asyncio.to_thread(self._complete_with_embedding_output, prepared, output)

Configuration

Use TrimConfig to configure token encoding, managed embeddings, MMR, and omission markers.

TrimConfig dataclass

Configure reusable measurement, ranking, and omission behavior.

Attributes:

Name Type Description
token_encoding str

Tiktoken encoding used for token budgets and lexical ranking.

embedding_model str

FastEmbed model used by semantic strategies.

fastembed_options Mapping[str, Any]

Additional keyword arguments for TextEmbedding.

embedding_batch_size int

Passage batch size used during inference.

mmr_lambda float

Balance between relevance and diversity.

omission_marker str

Text inserted where source content was omitted.

Source code in src/trimwise/models.py
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
@dataclass(frozen=True, slots=True)
class TrimConfig:
    """Configure reusable measurement, ranking, and omission behavior.

    Attributes:
        token_encoding: Tiktoken encoding used for token budgets and lexical ranking.
        embedding_model: FastEmbed model used by semantic strategies.
        fastembed_options: Additional keyword arguments for ``TextEmbedding``.
        embedding_batch_size: Passage batch size used during inference.
        mmr_lambda: Balance between relevance and diversity.
        omission_marker: Text inserted where source content was omitted.
    """

    token_encoding: str = "o200k_base"
    embedding_model: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
    fastembed_options: Mapping[str, Any] = field(default_factory=dict)
    embedding_batch_size: int = 256
    mmr_lambda: float = 0.7
    omission_marker: str = "[…omitted…]"

    def __post_init__(self) -> None:
        """Validate configuration and freeze a defensive options copy.

        Raises:
            TypeError: If FastEmbed options are not a mapping.
            ValueError: If a configured value is outside its supported domain.
        """
        if not isinstance(self.token_encoding, str):
            raise TypeError("token_encoding must be a string")
        if not self.token_encoding.strip():
            raise ValueError("token_encoding must not be blank")
        if not isinstance(self.embedding_model, str):
            raise TypeError("embedding_model must be a string")
        if not self.embedding_model.strip():
            raise ValueError("embedding_model must not be blank")
        if not isinstance(self.omission_marker, str):
            raise TypeError("omission_marker must be a string")
        if not self.omission_marker.strip():
            raise ValueError("omission_marker must not be blank")
        if (
            isinstance(self.embedding_batch_size, bool)
            or not isinstance(self.embedding_batch_size, int)
            or self.embedding_batch_size <= 0
        ):
            raise ValueError("embedding_batch_size must be a positive integer")
        if (
            isinstance(self.mmr_lambda, bool)
            or not isinstance(self.mmr_lambda, (int, float))
            or not 0 <= self.mmr_lambda <= 1
        ):
            raise ValueError("mmr_lambda must be between 0 and 1")
        if not isinstance(self.fastembed_options, Mapping):
            raise TypeError("fastembed_options must be a mapping")

        options = dict(self.fastembed_options)
        if any(not isinstance(key, str) for key in options):
            raise ValueError("fastembed_options keys must be strings")
        if "model_name" in options:
            raise ValueError("model_name belongs in embedding_model")
        object.__setattr__(self, "fastembed_options", MappingProxyType(options))

__post_init__

__post_init__() -> None

Validate configuration and freeze a defensive options copy.

Raises:

Type Description
TypeError

If FastEmbed options are not a mapping.

ValueError

If a configured value is outside its supported domain.

Source code in src/trimwise/models.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def __post_init__(self) -> None:
    """Validate configuration and freeze a defensive options copy.

    Raises:
        TypeError: If FastEmbed options are not a mapping.
        ValueError: If a configured value is outside its supported domain.
    """
    if not isinstance(self.token_encoding, str):
        raise TypeError("token_encoding must be a string")
    if not self.token_encoding.strip():
        raise ValueError("token_encoding must not be blank")
    if not isinstance(self.embedding_model, str):
        raise TypeError("embedding_model must be a string")
    if not self.embedding_model.strip():
        raise ValueError("embedding_model must not be blank")
    if not isinstance(self.omission_marker, str):
        raise TypeError("omission_marker must be a string")
    if not self.omission_marker.strip():
        raise ValueError("omission_marker must not be blank")
    if (
        isinstance(self.embedding_batch_size, bool)
        or not isinstance(self.embedding_batch_size, int)
        or self.embedding_batch_size <= 0
    ):
        raise ValueError("embedding_batch_size must be a positive integer")
    if (
        isinstance(self.mmr_lambda, bool)
        or not isinstance(self.mmr_lambda, (int, float))
        or not 0 <= self.mmr_lambda <= 1
    ):
        raise ValueError("mmr_lambda must be between 0 and 1")
    if not isinstance(self.fastembed_options, Mapping):
        raise TypeError("fastembed_options must be a mapping")

    options = dict(self.fastembed_options)
    if any(not isinstance(key, str) for key in options):
        raise ValueError("fastembed_options keys must be strings")
    if "model_name" in options:
        raise ValueError("model_name belongs in embedding_model")
    object.__setattr__(self, "fastembed_options", MappingProxyType(options))

Result

Every call returns an immutable TrimResult containing the excerpt, measured counts, resolved strategy, and trimming status.

TrimResult dataclass

Describe the resolved strategy and measured truncation result.

Attributes:

Name Type Description
text str

Extractive output that fits the requested limit.

input_count int

Measured size of the original input.

output_count int

Measured size of the returned output.

limit int

Requested maximum output size.

unit BudgetUnit

Unit used for all counts.

strategy Strategy

Concrete strategy used after resolving auto.

trimmed bool

Whether the output differs from the input.

spans tuple[SourceSpan, ...]

Ordered, nonoverlapping ranges retained from the original input.

Source code in src/trimwise/models.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
@dataclass(frozen=True, slots=True)
class TrimResult:
    """Describe the resolved strategy and measured truncation result.

    Attributes:
        text: Extractive output that fits the requested limit.
        input_count: Measured size of the original input.
        output_count: Measured size of the returned output.
        limit: Requested maximum output size.
        unit: Unit used for all counts.
        strategy: Concrete strategy used after resolving ``auto``.
        trimmed: Whether the output differs from the input.
        spans: Ordered, nonoverlapping ranges retained from the original input.
    """

    text: str
    input_count: int
    output_count: int
    limit: int
    unit: BudgetUnit
    strategy: Strategy
    trimmed: bool
    spans: tuple[SourceSpan, ...] = ()

SourceSpan identifies one retained range in the original input.

SourceSpan dataclass

Identify a retained range in the original input string.

Attributes:

Name Type Description
start int

Inclusive Python-string offset.

end int

Exclusive Python-string offset.

Source code in src/trimwise/models.py
34
35
36
37
38
39
40
41
42
43
44
@dataclass(frozen=True, slots=True)
class SourceSpan:
    """Identify a retained range in the original input string.

    Attributes:
        start: Inclusive Python-string offset.
        end: Exclusive Python-string offset.
    """

    start: int
    end: int

Strategies

Strategy selects structural, lexical, semantic, hybrid, or automatic ranking behavior.

Strategy

Bases: str, Enum

Select the evidence-ranking method used during truncation.

Source code in src/trimwise/models.py
12
13
14
15
16
17
18
19
class Strategy(str, Enum):
    """Select the evidence-ranking method used during truncation."""

    AUTO = "auto"
    STRUCTURAL = "structural"
    LEXICAL = "lexical"
    SEMANTIC = "semantic"
    HYBRID = "hybrid"

Budget units

BudgetUnit chooses token, word, or character measurement.

BudgetUnit

Bases: str, Enum

Define how an input and output budget is measured.

Source code in src/trimwise/models.py
22
23
24
25
26
27
class BudgetUnit(str, Enum):
    """Define how an input and output budget is measured."""

    TOKENS = "tokens"
    WORDS = "words"
    CHARACTERS = "characters"

Semantic backend errors

SemanticBackendError reports embedding import, initialization, callback, and inference failures without silently changing strategy.

SemanticBackendError

Bases: RuntimeError

Report an optional semantic backend failure without hiding its cause.

Source code in src/trimwise/models.py
30
31
class SemanticBackendError(RuntimeError):
    """Report an optional semantic backend failure without hiding its cause."""