Utilities for fitting content into AI context windows. Pure functions, no dependencies.

Functions

estimate-tokens

fn (text: Str): Int

Rough token estimate (~4 chars per token). Good enough for budget checks.

Example

::ai::context/estimate-tokens("hello world")  // 2
::ai::context/estimate-tokens("")  // 1

fit

fn (items: Vec, opts: Map): Vec

Drop items from the middle of a Vec until total tokens are under budget. Options: max-tokens, field.

Example

::ai::context/fit(["aaaa", "bbbb", "cccc", "dddd"], {max-tokens: 2})  // ["aaaa", "dddd"]

// Count one field of each item
::ai::context/fit([{text: "aaaa", id: 1}], {max-tokens: 10, field: "text"})  // [{text: "aaaa", id: 1}]

sample

fn (items: Vec, opts: Map): Vec

Sample a Vec down to max-items. Options: max-items (count), strategy (bookend/recent/even). Returns input unchanged if it fits.

Example

::ai::context/sample([1, 2, 3, 4, 5, 6], {max-items: 4})  // [1, 2, 5, 6]
::ai::context/sample([1, 2, 3, 4, 5, 6], {max-items: 2, strategy: "recent"})  // [5, 6]
::ai::context/sample([1, 2, 3, 4, 5, 6], {max-items: 3, strategy: "even"})  // [1, 3, 5]

sample-bookend

fn (items: Vec, max-items: Int): Vec

Keep max-items items from the two ends of a Vec, half from the start and the rest from the end. The bookend strategy of sample.

Example

::ai::context/sample-bookend([1, 2, 3, 4, 5, 6], 4)  // [1, 2, 5, 6]

sample-even

fn (items: Vec, max-items: Int): Vec

Pick up to max-items items at a fixed step from the start of a Vec. The even strategy of sample.

Example

::ai::context/sample-even([1, 2, 3, 4, 5, 6], 3)  // [1, 3, 5]

truncate

fn (text: Str, max-chars: Int, suffix: Str?): Str

Truncate text to a character limit. Appends suffix if truncated.

Example

::ai::context/truncate("Hello world", 5, "...")  // "Hello..."
::ai::context/truncate("Hello", 10, "...")  // "Hello"
::ai::context/truncate("Hello world", 5, null)  // "Hello"