cendor-contextkit 0.6.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cendor/contextkit/__init__.py +747 -0
- cendor/contextkit/py.typed +0 -0
- cendor_contextkit-0.6.1.dist-info/METADATA +50 -0
- cendor_contextkit-0.6.1.dist-info/RECORD +7 -0
- cendor_contextkit-0.6.1.dist-info/WHEEL +4 -0
- cendor_contextkit-0.6.1.dist-info/licenses/LICENSE +201 -0
- cendor_contextkit-0.6.1.dist-info/licenses/NOTICE +7 -0
|
@@ -0,0 +1,747 @@
|
|
|
1
|
+
"""cendor.contextkit — assemble context within a token budget, with a receipt.
|
|
2
|
+
|
|
3
|
+
Treat the context window like a packed suitcase: declare ``Block``s with priority, pin, and a
|
|
4
|
+
per-block eviction rule; :meth:`Context.assemble` packs them to a token budget (deterministically)
|
|
5
|
+
and :meth:`Context.report` returns the receipt — what was kept, shrunk, or dropped, with the token
|
|
6
|
+
math. Depends only on ``cendor-core`` (``tokens`` + the ``Compressor``/``EvictionStrategy``
|
|
7
|
+
protocols). Tools never import each other; ``squeeze`` plugs in by shape via the
|
|
8
|
+
``contextkit[squeeze]`` extra.
|
|
9
|
+
|
|
10
|
+
The receipt is honest at the **message** level: budgeting charges the per-message framing overhead
|
|
11
|
+
that providers add around every turn (self-calibrated from ``core.tokens``), so ``report().used``
|
|
12
|
+
equals ``core.tokens.count(assemble(), model)`` for text content — what the model actually sees.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import inspect
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from typing import Any, Literal
|
|
21
|
+
|
|
22
|
+
from cendor.core import bus, protocols, tokens
|
|
23
|
+
|
|
24
|
+
__all__ = ["Block", "Context", "AssemblyReport", "BlockDecision", "BudgetError", "use_compressor"]
|
|
25
|
+
|
|
26
|
+
# Built-in string strategies; ``Block.evict`` also accepts any core EvictionStrategy object.
|
|
27
|
+
EvictStrategy = Literal["drop_oldest", "truncate", "summarize", "compress"]
|
|
28
|
+
|
|
29
|
+
# Optional process-wide default compressor for evict="compress" blocks. contextkit doesn't care
|
|
30
|
+
# *who* compresses — only that it matches core's Compressor protocol by shape. By default it
|
|
31
|
+
# auto-discovers cendor.squeeze (the deterministic, zero-dep backend) via contextkit[squeeze];
|
|
32
|
+
# set this to swap in any other backend (e.g. an ML-based compressor) globally.
|
|
33
|
+
_default_compressor: Any = None
|
|
34
|
+
|
|
35
|
+
# Per-model (priming, per_message) framing overhead, derived once from core.tokens' public API:
|
|
36
|
+
# count([one empty msg]) = priming + per_message; the delta to two empty msgs isolates per_message.
|
|
37
|
+
# This stays correct for any registered tokenizer without importing core internals.
|
|
38
|
+
_framing_cache: dict[str, tuple[int, int]] = {}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _framing(model: str) -> tuple[int, int]:
|
|
42
|
+
"""Return ``(priming, per_message)`` token overhead for ``model``, per ``core.tokens``."""
|
|
43
|
+
cached = _framing_cache.get(model)
|
|
44
|
+
if cached is not None:
|
|
45
|
+
return cached
|
|
46
|
+
one = tokens.count([{"role": "user", "content": ""}], model)
|
|
47
|
+
two = tokens.count([{"role": "user", "content": ""}, {"role": "user", "content": ""}], model)
|
|
48
|
+
per_message = max(0, two - one)
|
|
49
|
+
priming = max(0, one - per_message)
|
|
50
|
+
_framing_cache[model] = (priming, per_message)
|
|
51
|
+
return priming, per_message
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def use_compressor(compressor: Any) -> Any:
|
|
55
|
+
"""Set the default compressor for ``evict="compress"`` blocks; returns the previous one.
|
|
56
|
+
|
|
57
|
+
Accepts anything matching ``core.protocols.Compressor`` — a ``compress(content, *,
|
|
58
|
+
target_tokens, model, ...)`` object (e.g. ``squeeze.SqueezeCompressor()``) or a
|
|
59
|
+
``compress(text, target_tokens=)`` callable — so you can plug in an alternative backend without
|
|
60
|
+
touching call sites. Pass ``None`` to clear (falls back to auto-discovering ``squeeze``). A
|
|
61
|
+
per-``Context`` ``compressor=`` argument still overrides this default.
|
|
62
|
+
"""
|
|
63
|
+
global _default_compressor
|
|
64
|
+
previous, _default_compressor = _default_compressor, compressor
|
|
65
|
+
return previous
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class BudgetError(Exception):
|
|
69
|
+
"""Raised when pinned blocks alone exceed the budget (they are never evicted)."""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class Block:
|
|
74
|
+
"""A unit of context with packing intent. See docs/contextkit.md §6.
|
|
75
|
+
|
|
76
|
+
Provide **exactly one** of ``content`` (a single message, text or multimodal parts) or
|
|
77
|
+
``messages`` (a conversation segment — a list of ``{"role", "content"}`` turns that
|
|
78
|
+
``evict="drop_oldest"`` shrinks by peeling the *oldest* turns until it fits).
|
|
79
|
+
|
|
80
|
+
Attributes:
|
|
81
|
+
content: The block's content for a single-message block — text, or a list of multimodal
|
|
82
|
+
parts. Leave ``None`` when using ``messages``.
|
|
83
|
+
priority: Higher is admitted first; ties break by insertion order (deterministic).
|
|
84
|
+
pin: Pinned blocks are never evicted (assembly raises if pinned blocks alone overflow).
|
|
85
|
+
evict: Strategy when this block overflows the remaining budget — a built-in name
|
|
86
|
+
(:data:`EvictStrategy`) or any ``core.protocols.EvictionStrategy`` object.
|
|
87
|
+
role: Provider message role for a single-message block: ``system`` | ``user`` |
|
|
88
|
+
``assistant`` | ``tool``. Ignored for ``messages`` blocks (each turn carries its own).
|
|
89
|
+
summarizer: Callback ``(content, target_tokens) -> str`` used when ``evict="summarize"``.
|
|
90
|
+
keep: For ``evict="truncate"``, which end to keep — ``"head"`` (default) or ``"tail"``.
|
|
91
|
+
messages: A conversation segment as ``[{"role", "content"}, ...]``; mutually exclusive
|
|
92
|
+
with ``content``. Eviction peels the oldest turns (a sliding window of recent context).
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
content: str | list | None = None
|
|
96
|
+
priority: int = 0
|
|
97
|
+
pin: bool = False
|
|
98
|
+
evict: EvictStrategy | protocols.EvictionStrategy = "drop_oldest"
|
|
99
|
+
role: str = "user"
|
|
100
|
+
summarizer: Callable[[str, int], Any] | None = None
|
|
101
|
+
keep: Literal["head", "tail"] = "head"
|
|
102
|
+
messages: list[dict] | None = None
|
|
103
|
+
|
|
104
|
+
def __post_init__(self) -> None:
|
|
105
|
+
if (self.content is None) == (self.messages is None):
|
|
106
|
+
raise ValueError("Block requires exactly one of content= or messages=")
|
|
107
|
+
if self.keep not in ("head", "tail"):
|
|
108
|
+
raise ValueError(f"keep must be 'head' or 'tail', got {self.keep!r}")
|
|
109
|
+
if self.messages is not None and not all(
|
|
110
|
+
isinstance(t, dict) and "role" in t and "content" in t for t in self.messages
|
|
111
|
+
):
|
|
112
|
+
raise ValueError("each item in messages= must be a {'role', 'content'} dict")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass
|
|
116
|
+
class BlockDecision:
|
|
117
|
+
"""What happened to one block during assembly (a line on the receipt).
|
|
118
|
+
|
|
119
|
+
``tokens_before``/``tokens_after`` are *content* tokens (framing-exclusive); the report's
|
|
120
|
+
``used`` additionally accounts for per-message framing.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
role: str
|
|
124
|
+
action: str # "kept" | "truncated" | "summarized" | "compressed" | "dropped"
|
|
125
|
+
tokens_before: int
|
|
126
|
+
tokens_after: int
|
|
127
|
+
note: str = ""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass
|
|
131
|
+
class AssemblyReport:
|
|
132
|
+
"""The receipt: budget math + per-block decisions. See docs/contextkit.md §6.
|
|
133
|
+
|
|
134
|
+
``used`` is the message-level token count of the assembled prompt (content + framing), so it
|
|
135
|
+
equals ``core.tokens.count(messages, model)`` for text content; multimodal image budget is also
|
|
136
|
+
charged into ``used`` even though ``core.tokens`` can't see image parts.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
budget: int
|
|
140
|
+
used: int
|
|
141
|
+
reserved_output: int
|
|
142
|
+
model: str
|
|
143
|
+
decisions: list[BlockDecision] = field(default_factory=list)
|
|
144
|
+
order: str = "default"
|
|
145
|
+
|
|
146
|
+
def __str__(self) -> str:
|
|
147
|
+
lines = [
|
|
148
|
+
f"AssemblyReport(model={self.model}, order={self.order}) "
|
|
149
|
+
f"budget={self.budget} reserved_output={self.reserved_output} "
|
|
150
|
+
f"used={self.used}/{self.budget - self.reserved_output}",
|
|
151
|
+
]
|
|
152
|
+
for d in self.decisions:
|
|
153
|
+
arrow = f"{d.tokens_before}->{d.tokens_after}tok"
|
|
154
|
+
note = f" # {d.note}" if d.note else ""
|
|
155
|
+
lines.append(f" [{d.action:<10}] {d.role:<9} {arrow}{note}")
|
|
156
|
+
return "\n".join(lines)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
# Default render order: system first, history/context middle, the user turn last.
|
|
160
|
+
_ROLE_RANK = {"system": 0, "history": 1, "tool": 1, "assistant": 2, "user": 3}
|
|
161
|
+
_ORDERS = ("default", "attention", "cache")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _ord_role(block: Block) -> str:
|
|
165
|
+
"""The role a block is ordered by — ``"history"`` for a multi-turn (``messages``) block."""
|
|
166
|
+
return "history" if block.messages is not None else block.role
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@dataclass
|
|
170
|
+
class _PackState:
|
|
171
|
+
"""Running state threaded through one packing pass (shared by sync/async assembly)."""
|
|
172
|
+
|
|
173
|
+
used: int = 0
|
|
174
|
+
has_msgs: bool = False
|
|
175
|
+
decisions: list = field(default_factory=list)
|
|
176
|
+
kept: list = field(default_factory=list)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@dataclass
|
|
180
|
+
class _BlockPlan:
|
|
181
|
+
"""What to do with one single-message block, decided *before* any (a)sync eviction runs.
|
|
182
|
+
|
|
183
|
+
``status`` is ``"kept"`` | ``"dropped"`` | ``"evict"``. For ``"evict"`` the plan carries the
|
|
184
|
+
content budget so the caller runs the sync or async evictor — the one line that differs between
|
|
185
|
+
:meth:`Context._pack` and :meth:`Context._apack`.
|
|
186
|
+
"""
|
|
187
|
+
|
|
188
|
+
status: str
|
|
189
|
+
used: int = 0
|
|
190
|
+
message: dict | None = None
|
|
191
|
+
decision: BlockDecision | None = None
|
|
192
|
+
content_budget: int = 0
|
|
193
|
+
prim: int = 0
|
|
194
|
+
content_tokens: int = 0
|
|
195
|
+
text: str = "" # the str-narrowed content to evict (only set when status == "evict")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class Context:
|
|
199
|
+
"""A token-budgeted, declarative context assembler. See docs/contextkit.md §3, §5.
|
|
200
|
+
|
|
201
|
+
``order`` controls how kept blocks are arranged in the final messages (docs/contextkit.md §2):
|
|
202
|
+
|
|
203
|
+
- ``"default"`` — role-grouped: system → history/context → the user turn.
|
|
204
|
+
- ``"attention"`` — "lost-in-the-middle": highest-priority context blocks ride the edges
|
|
205
|
+
(just after system / just before the user turn), weakest in the dead center.
|
|
206
|
+
- ``"cache"`` — stable prefix first (pinned, high-priority blocks lead) to maximize provider
|
|
207
|
+
prompt-cache / KV-cache hits across calls.
|
|
208
|
+
"""
|
|
209
|
+
|
|
210
|
+
def __init__(
|
|
211
|
+
self,
|
|
212
|
+
budget_tokens: int,
|
|
213
|
+
model: str,
|
|
214
|
+
reserve_output: int = 0,
|
|
215
|
+
compressor: Any = None,
|
|
216
|
+
order: str = "default",
|
|
217
|
+
image_tokens: int | Callable[[dict], int] = 0,
|
|
218
|
+
) -> None:
|
|
219
|
+
if order not in _ORDERS:
|
|
220
|
+
raise ValueError(f"order must be one of {_ORDERS}, got {order!r}")
|
|
221
|
+
self.budget_tokens = budget_tokens
|
|
222
|
+
self.model = model
|
|
223
|
+
self.reserve_output = reserve_output
|
|
224
|
+
self._compressor = compressor
|
|
225
|
+
self.order = order
|
|
226
|
+
# Token cost per image part in multimodal blocks: a flat int, or a callable
|
|
227
|
+
# (part_dict -> tokens) for resolution-aware estimates.
|
|
228
|
+
self.image_tokens = image_tokens
|
|
229
|
+
self._blocks: list[Block] = []
|
|
230
|
+
self._report: AssemblyReport | None = None
|
|
231
|
+
self._messages: list[dict] = []
|
|
232
|
+
|
|
233
|
+
def add(self, block: Block) -> Context:
|
|
234
|
+
"""Add a block. Returns ``self`` for chaining."""
|
|
235
|
+
self._blocks.append(block)
|
|
236
|
+
return self
|
|
237
|
+
|
|
238
|
+
def assemble(self) -> list[dict]:
|
|
239
|
+
"""Pack blocks within the budget; return provider-ready messages (OpenAI/Foundry shape).
|
|
240
|
+
|
|
241
|
+
Deterministic: stable sort by ``(pinned, priority, insertion order)``. Emits the
|
|
242
|
+
:class:`AssemblyReport` onto core's bus so ``acttrace`` records what the model saw.
|
|
243
|
+
"""
|
|
244
|
+
messages, report = self._pack(self.budget_tokens, emit=True)
|
|
245
|
+
self._messages = messages
|
|
246
|
+
self._report = report
|
|
247
|
+
return messages
|
|
248
|
+
|
|
249
|
+
def report(self) -> AssemblyReport:
|
|
250
|
+
"""Return the receipt for the most recent :meth:`assemble`. Raises before the first one."""
|
|
251
|
+
if self._report is None:
|
|
252
|
+
raise RuntimeError("call assemble() before report()")
|
|
253
|
+
return self._report
|
|
254
|
+
|
|
255
|
+
def whatif(self, budget_tokens: int) -> AssemblyReport:
|
|
256
|
+
"""Preview the assembly at a different budget without committing (no bus emit)."""
|
|
257
|
+
_, report = self._pack(budget_tokens, emit=False)
|
|
258
|
+
return report
|
|
259
|
+
|
|
260
|
+
async def aassemble(self) -> list[dict]:
|
|
261
|
+
"""Async assemble — like :meth:`assemble` but awaits ``async`` summarize callbacks.
|
|
262
|
+
|
|
263
|
+
Use this when a block's ``summarizer`` is a coroutine (e.g. an LLM summarizer). The sync
|
|
264
|
+
:meth:`assemble` falls back to truncation for async summarizers.
|
|
265
|
+
"""
|
|
266
|
+
messages, report = await self._apack(self.budget_tokens, emit=True)
|
|
267
|
+
self._messages = messages
|
|
268
|
+
self._report = report
|
|
269
|
+
return messages
|
|
270
|
+
|
|
271
|
+
def for_anthropic(self) -> tuple[str, list[dict]]:
|
|
272
|
+
"""Anthropic adapter: split system blocks out (the Messages API takes ``system`` apart).
|
|
273
|
+
|
|
274
|
+
Returns ``(system_text, messages)`` from the most recent :meth:`assemble`. Multimodal
|
|
275
|
+
message content is passed through unchanged (Anthropic accepts content-block lists).
|
|
276
|
+
"""
|
|
277
|
+
if not self._messages:
|
|
278
|
+
self.assemble()
|
|
279
|
+
rest = [m for m in self._messages if m["role"] != "system"]
|
|
280
|
+
return self._system_text(), rest
|
|
281
|
+
|
|
282
|
+
def for_gemini(self) -> tuple[str, list[dict]]:
|
|
283
|
+
"""Gemini adapter: returns ``(system_instruction, contents)``.
|
|
284
|
+
|
|
285
|
+
``contents`` are ``{"role": "user"|"model", "parts": [...]}`` (Gemini uses ``model``, not
|
|
286
|
+
``assistant``); system blocks become the separate ``system_instruction``. Multimodal parts
|
|
287
|
+
are mapped to Gemini parts (``{"text": ...}`` for text; non-text parts pass through).
|
|
288
|
+
"""
|
|
289
|
+
if not self._messages:
|
|
290
|
+
self.assemble()
|
|
291
|
+
contents = [
|
|
292
|
+
{
|
|
293
|
+
"role": "model" if m["role"] == "assistant" else "user",
|
|
294
|
+
"parts": _parts_of(m["content"]),
|
|
295
|
+
}
|
|
296
|
+
for m in self._messages
|
|
297
|
+
if m["role"] != "system"
|
|
298
|
+
]
|
|
299
|
+
return self._system_text(), contents
|
|
300
|
+
|
|
301
|
+
def for_bedrock(self) -> tuple[list[dict], list[dict]]:
|
|
302
|
+
"""Bedrock Converse adapter: returns ``(system, messages)``.
|
|
303
|
+
|
|
304
|
+
``system`` is ``[{"text": ...}]`` (or empty); ``messages`` are
|
|
305
|
+
``{"role": "user"|"assistant", "content": [...]}`` — Bedrock allows only those two roles, so
|
|
306
|
+
non-user blocks map to ``assistant`` and content becomes a list of content blocks.
|
|
307
|
+
"""
|
|
308
|
+
if not self._messages:
|
|
309
|
+
self.assemble()
|
|
310
|
+
system_text = self._system_text()
|
|
311
|
+
system = [{"text": system_text}] if system_text else []
|
|
312
|
+
messages = [
|
|
313
|
+
{
|
|
314
|
+
"role": "user" if m["role"] == "user" else "assistant",
|
|
315
|
+
"content": _parts_of(m["content"]),
|
|
316
|
+
}
|
|
317
|
+
for m in self._messages
|
|
318
|
+
if m["role"] != "system"
|
|
319
|
+
]
|
|
320
|
+
return system, messages
|
|
321
|
+
|
|
322
|
+
# ------------------------------------------------------------------ internals
|
|
323
|
+
|
|
324
|
+
def _system_text(self) -> str:
|
|
325
|
+
"""Join the text of all assembled system messages (adapters split ``system`` out)."""
|
|
326
|
+
return "\n\n".join(_text_of(m["content"]) for m in self._messages if m["role"] == "system")
|
|
327
|
+
|
|
328
|
+
def _ordered_blocks(self) -> list[tuple[int, Block]]:
|
|
329
|
+
# (not pin) -> pinned (False) sorts first; then priority desc; then insertion order.
|
|
330
|
+
return sorted(
|
|
331
|
+
enumerate(self._blocks), key=lambda iv: (not iv[1].pin, -iv[1].priority, iv[0])
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
def _image_cost(self, part: dict) -> int:
|
|
335
|
+
it = self.image_tokens
|
|
336
|
+
return it(part) if callable(it) else it
|
|
337
|
+
|
|
338
|
+
def _content_tokens(self, content: Any) -> int:
|
|
339
|
+
"""Token cost of content, charging ``image_tokens`` per image part in multimodal lists."""
|
|
340
|
+
if isinstance(content, list):
|
|
341
|
+
text = "".join(
|
|
342
|
+
p.get("text", "") for p in content if isinstance(p, dict) and "text" in p
|
|
343
|
+
)
|
|
344
|
+
n = tokens.count(text, self.model) if text else 0
|
|
345
|
+
for p in content:
|
|
346
|
+
if isinstance(p, dict) and p.get("type") in ("image", "image_url"):
|
|
347
|
+
n += self._image_cost(p)
|
|
348
|
+
return n
|
|
349
|
+
return tokens.count(str(content), self.model)
|
|
350
|
+
|
|
351
|
+
def _finish(
|
|
352
|
+
self, budget_tokens: int, used: int, decisions: list, kept: list, *, emit: bool
|
|
353
|
+
) -> tuple[list[dict], AssemblyReport]:
|
|
354
|
+
ordered = _order_blocks(kept, self.order)
|
|
355
|
+
messages: list[dict] = []
|
|
356
|
+
for _idx, _block, block_messages in ordered:
|
|
357
|
+
messages.extend(block_messages)
|
|
358
|
+
report = AssemblyReport(
|
|
359
|
+
budget=budget_tokens,
|
|
360
|
+
used=used,
|
|
361
|
+
reserved_output=self.reserve_output,
|
|
362
|
+
model=self.model,
|
|
363
|
+
decisions=decisions,
|
|
364
|
+
order=self.order,
|
|
365
|
+
)
|
|
366
|
+
if emit:
|
|
367
|
+
bus.emit(report)
|
|
368
|
+
return messages, report
|
|
369
|
+
|
|
370
|
+
def _pack(self, budget_tokens: int, *, emit: bool) -> tuple[list[dict], AssemblyReport]:
|
|
371
|
+
"""Pack blocks within the budget (sync). Identical to :meth:`_apack` but for the evictor."""
|
|
372
|
+
priming, per_message = _framing(self.model)
|
|
373
|
+
effective = max(0, budget_tokens - self.reserve_output)
|
|
374
|
+
state = _PackState()
|
|
375
|
+
for idx, block in self._ordered_blocks():
|
|
376
|
+
if block.messages is not None:
|
|
377
|
+
self._pack_history_into(block, idx, effective, priming, per_message, state)
|
|
378
|
+
continue
|
|
379
|
+
plan = self._plan_block(block, effective, state, priming, per_message)
|
|
380
|
+
if plan.status == "evict":
|
|
381
|
+
new_text, action, note = self._evict(block, plan.text, plan.content_budget)
|
|
382
|
+
self._apply_evicted(idx, block, plan, per_message, new_text, action, note, state)
|
|
383
|
+
else:
|
|
384
|
+
self._apply_plan(idx, block, plan, state)
|
|
385
|
+
return self._finish(budget_tokens, state.used, state.decisions, state.kept, emit=emit)
|
|
386
|
+
|
|
387
|
+
async def _apack(self, budget_tokens: int, *, emit: bool) -> tuple[list[dict], AssemblyReport]:
|
|
388
|
+
"""Async packing — like :meth:`_pack`, but awaits the async evictor (async summarizers)."""
|
|
389
|
+
priming, per_message = _framing(self.model)
|
|
390
|
+
effective = max(0, budget_tokens - self.reserve_output)
|
|
391
|
+
state = _PackState()
|
|
392
|
+
for idx, block in self._ordered_blocks():
|
|
393
|
+
if block.messages is not None:
|
|
394
|
+
self._pack_history_into(block, idx, effective, priming, per_message, state)
|
|
395
|
+
continue
|
|
396
|
+
plan = self._plan_block(block, effective, state, priming, per_message)
|
|
397
|
+
if plan.status == "evict":
|
|
398
|
+
new_text, action, note = await self._aevict(block, plan.text, plan.content_budget)
|
|
399
|
+
self._apply_evicted(idx, block, plan, per_message, new_text, action, note, state)
|
|
400
|
+
else:
|
|
401
|
+
self._apply_plan(idx, block, plan, state)
|
|
402
|
+
return self._finish(budget_tokens, state.used, state.decisions, state.kept, emit=emit)
|
|
403
|
+
|
|
404
|
+
def _plan_block(
|
|
405
|
+
self, block: Block, effective: int, state: _PackState, priming: int, per_message: int
|
|
406
|
+
) -> _BlockPlan:
|
|
407
|
+
"""Decide a single-message block's fate up to (not performing) eviction.
|
|
408
|
+
|
|
409
|
+
Raises :class:`BudgetError` on pinned overflow. Shared by :meth:`_pack`/:meth:`_apack`, so
|
|
410
|
+
the only difference between them is which evictor runs for an ``"evict"`` plan.
|
|
411
|
+
"""
|
|
412
|
+
content_tokens = self._content_tokens(block.content)
|
|
413
|
+
prim = 0 if state.has_msgs else priming
|
|
414
|
+
if state.used + prim + per_message + content_tokens <= effective:
|
|
415
|
+
return _BlockPlan(
|
|
416
|
+
"kept",
|
|
417
|
+
used=state.used + prim + per_message + content_tokens,
|
|
418
|
+
message={"role": block.role, "content": block.content},
|
|
419
|
+
decision=BlockDecision(block.role, "kept", content_tokens, content_tokens),
|
|
420
|
+
)
|
|
421
|
+
if block.pin:
|
|
422
|
+
raise BudgetError(
|
|
423
|
+
f"pinned block(s) exceed budget: need {prim + per_message + content_tokens} "
|
|
424
|
+
f"tokens ({content_tokens} content + {prim + per_message} framing), "
|
|
425
|
+
f"{effective - state.used} of {effective} remaining "
|
|
426
|
+
f"(reserve_output={self.reserve_output})"
|
|
427
|
+
)
|
|
428
|
+
if not isinstance(block.content, str): # can't shrink a multimodal/list block
|
|
429
|
+
return _BlockPlan(
|
|
430
|
+
"dropped",
|
|
431
|
+
decision=BlockDecision(
|
|
432
|
+
block.role, "dropped", content_tokens, 0, "multimodal: too large"
|
|
433
|
+
),
|
|
434
|
+
)
|
|
435
|
+
content_budget = effective - state.used - prim - per_message
|
|
436
|
+
if content_budget <= 0:
|
|
437
|
+
return _BlockPlan(
|
|
438
|
+
"dropped",
|
|
439
|
+
decision=BlockDecision(
|
|
440
|
+
block.role, "dropped", content_tokens, 0, "no room (framing)"
|
|
441
|
+
),
|
|
442
|
+
)
|
|
443
|
+
return _BlockPlan(
|
|
444
|
+
"evict",
|
|
445
|
+
content_budget=content_budget,
|
|
446
|
+
prim=prim,
|
|
447
|
+
content_tokens=content_tokens,
|
|
448
|
+
text=block.content, # narrowed to str above
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
def _apply_plan(self, idx: int, block: Block, plan: _BlockPlan, state: _PackState) -> None:
|
|
452
|
+
"""Fold a non-evict plan (``"kept"`` / ``"dropped"``) into the running state."""
|
|
453
|
+
if plan.status == "kept":
|
|
454
|
+
state.used = plan.used
|
|
455
|
+
state.has_msgs = True
|
|
456
|
+
state.kept.append((idx, block, [plan.message]))
|
|
457
|
+
state.decisions.append(plan.decision)
|
|
458
|
+
|
|
459
|
+
def _apply_evicted(
|
|
460
|
+
self,
|
|
461
|
+
idx: int,
|
|
462
|
+
block: Block,
|
|
463
|
+
plan: _BlockPlan,
|
|
464
|
+
per_message: int,
|
|
465
|
+
new_text: str | None,
|
|
466
|
+
action: str,
|
|
467
|
+
note: str,
|
|
468
|
+
state: _PackState,
|
|
469
|
+
) -> None:
|
|
470
|
+
"""Fold an evictor's result back into the running state (shared sync/async)."""
|
|
471
|
+
if new_text is None:
|
|
472
|
+
state.decisions.append(
|
|
473
|
+
BlockDecision(block.role, "dropped", plan.content_tokens, 0, note)
|
|
474
|
+
)
|
|
475
|
+
return
|
|
476
|
+
after = self._content_tokens(new_text)
|
|
477
|
+
state.used += plan.prim + per_message + after
|
|
478
|
+
state.has_msgs = True
|
|
479
|
+
state.kept.append((idx, block, [{"role": block.role, "content": new_text}]))
|
|
480
|
+
state.decisions.append(BlockDecision(block.role, action, plan.content_tokens, after, note))
|
|
481
|
+
|
|
482
|
+
def _pack_history_into(
|
|
483
|
+
self,
|
|
484
|
+
block: Block,
|
|
485
|
+
idx: int,
|
|
486
|
+
effective: int,
|
|
487
|
+
priming: int,
|
|
488
|
+
per_message: int,
|
|
489
|
+
state: _PackState,
|
|
490
|
+
) -> None:
|
|
491
|
+
"""Pack a multi-turn block into ``state`` (the messages-block branch, shared sync/async)."""
|
|
492
|
+
turns, dec, state.used, state.has_msgs = self._pack_history(
|
|
493
|
+
block, effective, state.used, state.has_msgs, priming, per_message
|
|
494
|
+
)
|
|
495
|
+
if turns:
|
|
496
|
+
state.kept.append((idx, block, turns))
|
|
497
|
+
state.decisions.append(dec)
|
|
498
|
+
|
|
499
|
+
def _pack_history(
|
|
500
|
+
self,
|
|
501
|
+
block: Block,
|
|
502
|
+
effective: int,
|
|
503
|
+
used: int,
|
|
504
|
+
has_msgs: bool,
|
|
505
|
+
priming: int,
|
|
506
|
+
per_message: int,
|
|
507
|
+
) -> tuple[list[dict], BlockDecision, int, bool]:
|
|
508
|
+
"""Pack a multi-turn block: keep the newest turns that fit, peeling the oldest.
|
|
509
|
+
|
|
510
|
+
``evict="truncate"`` additionally tail-trims the surviving newest turn when even it
|
|
511
|
+
overflows. Other strategies fall back to peeling (with a note). Returns
|
|
512
|
+
``(kept_turns, decision, used, has_msgs)``.
|
|
513
|
+
"""
|
|
514
|
+
turns = block.messages or []
|
|
515
|
+
turn_tokens = [self._content_tokens(t.get("content", "")) for t in turns]
|
|
516
|
+
total_before = sum(turn_tokens)
|
|
517
|
+
is_truncate = block.evict == "truncate"
|
|
518
|
+
|
|
519
|
+
if block.pin:
|
|
520
|
+
full = (0 if has_msgs else priming) + per_message * len(turns) + total_before
|
|
521
|
+
if used + full > effective:
|
|
522
|
+
raise BudgetError(
|
|
523
|
+
f"pinned history block exceeds budget: needs {full} tokens, "
|
|
524
|
+
f"{effective - used} of {effective} remaining "
|
|
525
|
+
f"(reserve_output={self.reserve_output})"
|
|
526
|
+
)
|
|
527
|
+
|
|
528
|
+
kept: list[dict] = [] # built newest-first, reversed at the end
|
|
529
|
+
running = used
|
|
530
|
+
local_has = has_msgs
|
|
531
|
+
for i in range(len(turns) - 1, -1, -1):
|
|
532
|
+
prim = 0 if local_has else priming
|
|
533
|
+
if running + prim + per_message + turn_tokens[i] <= effective:
|
|
534
|
+
running += prim + per_message + turn_tokens[i]
|
|
535
|
+
local_has = True
|
|
536
|
+
kept.append(turns[i])
|
|
537
|
+
continue
|
|
538
|
+
if is_truncate and not kept: # newest turn alone overflows -> tail-trim it
|
|
539
|
+
budget_ct = effective - running - prim - per_message
|
|
540
|
+
if budget_ct > 0:
|
|
541
|
+
trimmed = _truncate_to_tokens(
|
|
542
|
+
str(turns[i].get("content", "")), budget_ct, self.model, keep="tail"
|
|
543
|
+
)
|
|
544
|
+
running += prim + per_message + self._content_tokens(trimmed)
|
|
545
|
+
local_has = True
|
|
546
|
+
kept.append({**turns[i], "content": trimmed})
|
|
547
|
+
break # older turns are dropped (we keep a contiguous suffix of recent turns)
|
|
548
|
+
kept.reverse()
|
|
549
|
+
|
|
550
|
+
n, k = len(turns), len(kept)
|
|
551
|
+
after = sum(self._content_tokens(t.get("content", "")) for t in kept)
|
|
552
|
+
if k == 0:
|
|
553
|
+
action, note = "dropped", f"history: dropped all {n} turns (no room)"
|
|
554
|
+
elif k < n:
|
|
555
|
+
action, note = "truncated", f"history: kept {k} of {n} turns"
|
|
556
|
+
if block.evict not in ("drop_oldest", "truncate"):
|
|
557
|
+
note += f"; '{block.evict}' n/a for message blocks, peeled oldest"
|
|
558
|
+
else:
|
|
559
|
+
action, note = "kept", ""
|
|
560
|
+
decision = BlockDecision("history", action, total_before, after, note)
|
|
561
|
+
return kept, decision, running, local_has
|
|
562
|
+
|
|
563
|
+
async def _aevict(
|
|
564
|
+
self, block: Block, text: str, content_budget: int
|
|
565
|
+
) -> tuple[str | None, str, str]:
|
|
566
|
+
"""Async eviction: await an async summarizer; delegate everything else to ``_evict``."""
|
|
567
|
+
if (
|
|
568
|
+
isinstance(block.evict, str)
|
|
569
|
+
and block.evict == "summarize"
|
|
570
|
+
and block.summarizer is not None
|
|
571
|
+
and inspect.iscoroutinefunction(block.summarizer)
|
|
572
|
+
):
|
|
573
|
+
summary = await block.summarizer(text, content_budget)
|
|
574
|
+
if tokens.count(summary, self.model) > content_budget:
|
|
575
|
+
summary = _truncate_to_tokens(summary, content_budget, self.model, keep=block.keep)
|
|
576
|
+
return summary, "summarized", ""
|
|
577
|
+
return self._evict(block, text, content_budget)
|
|
578
|
+
|
|
579
|
+
def _evict(self, block: Block, text: str, content_budget: int) -> tuple[str | None, str, str]:
|
|
580
|
+
"""Apply a block's eviction strategy. Returns ``(content_or_None, action, note)``.
|
|
581
|
+
|
|
582
|
+
``content_budget`` is the room for this block's *content* (framing already reserved) and is
|
|
583
|
+
always > 0 here.
|
|
584
|
+
"""
|
|
585
|
+
strategy = block.evict
|
|
586
|
+
|
|
587
|
+
if not isinstance(strategy, str): # a core.protocols.EvictionStrategy object
|
|
588
|
+
try:
|
|
589
|
+
new, action = strategy.evict(text, content_budget, self.model)
|
|
590
|
+
except Exception as exc: # noqa: BLE001 - a custom strategy must not break assembly
|
|
591
|
+
return None, "dropped", f"custom strategy raised: {exc!r}"
|
|
592
|
+
if new is None:
|
|
593
|
+
return None, "dropped", action or ""
|
|
594
|
+
if tokens.count(new, self.model) > content_budget:
|
|
595
|
+
new = _truncate_to_tokens(new, content_budget, self.model, keep=block.keep)
|
|
596
|
+
return new, action or "evicted", ""
|
|
597
|
+
|
|
598
|
+
if strategy == "drop_oldest":
|
|
599
|
+
return None, "dropped", "block dropped whole (use messages= for turn-level eviction)"
|
|
600
|
+
|
|
601
|
+
if strategy == "truncate":
|
|
602
|
+
return (
|
|
603
|
+
_truncate_to_tokens(text, content_budget, self.model, keep=block.keep),
|
|
604
|
+
"truncated",
|
|
605
|
+
"",
|
|
606
|
+
)
|
|
607
|
+
|
|
608
|
+
if strategy == "summarize":
|
|
609
|
+
if block.summarizer is not None and not inspect.iscoroutinefunction(block.summarizer):
|
|
610
|
+
summary = block.summarizer(text, content_budget)
|
|
611
|
+
if tokens.count(summary, self.model) > content_budget:
|
|
612
|
+
summary = _truncate_to_tokens(
|
|
613
|
+
summary, content_budget, self.model, keep=block.keep
|
|
614
|
+
)
|
|
615
|
+
return summary, "summarized", ""
|
|
616
|
+
note = (
|
|
617
|
+
"async summarizer needs aassemble()"
|
|
618
|
+
if block.summarizer is not None
|
|
619
|
+
else "no summarizer"
|
|
620
|
+
)
|
|
621
|
+
return (
|
|
622
|
+
_truncate_to_tokens(text, content_budget, self.model, keep=block.keep),
|
|
623
|
+
"truncated",
|
|
624
|
+
f"{note}; truncated",
|
|
625
|
+
)
|
|
626
|
+
|
|
627
|
+
if strategy == "compress":
|
|
628
|
+
compressor = self._get_compressor()
|
|
629
|
+
if compressor is not None:
|
|
630
|
+
small = _call_compressor(compressor, text, content_budget, self.model)
|
|
631
|
+
if tokens.count(small, self.model) > content_budget:
|
|
632
|
+
small = _truncate_to_tokens(small, content_budget, self.model, keep=block.keep)
|
|
633
|
+
return small, "compressed", ""
|
|
634
|
+
return (
|
|
635
|
+
_truncate_to_tokens(text, content_budget, self.model, keep=block.keep),
|
|
636
|
+
"truncated",
|
|
637
|
+
"squeeze not installed; fell back to truncate",
|
|
638
|
+
)
|
|
639
|
+
|
|
640
|
+
return None, "dropped", f"unknown evict strategy {strategy!r}"
|
|
641
|
+
|
|
642
|
+
def _get_compressor(self) -> Any:
|
|
643
|
+
if self._compressor is not None: # per-Context override wins
|
|
644
|
+
return self._compressor
|
|
645
|
+
if _default_compressor is not None: # process-wide default via use_compressor()
|
|
646
|
+
return _default_compressor
|
|
647
|
+
# Otherwise auto-discover squeeze at runtime (the contextkit[squeeze] extra).
|
|
648
|
+
import importlib
|
|
649
|
+
|
|
650
|
+
try:
|
|
651
|
+
return importlib.import_module("cendor.squeeze").compress
|
|
652
|
+
except ModuleNotFoundError:
|
|
653
|
+
return None
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def _order_blocks(
|
|
657
|
+
kept: list[tuple[int, Block, list[dict]]], mode: str
|
|
658
|
+
) -> list[tuple[int, Block, list[dict]]]:
|
|
659
|
+
"""Arrange kept blocks for rendering per the chosen strategy. Deterministic."""
|
|
660
|
+
if mode == "cache":
|
|
661
|
+
# Stable prefix: pinned, high-priority blocks lead so the prompt prefix is reused.
|
|
662
|
+
return sorted(kept, key=lambda k: (not k[1].pin, -k[1].priority, k[0]))
|
|
663
|
+
if mode == "attention":
|
|
664
|
+
systems = sorted(
|
|
665
|
+
(k for k in kept if _ord_role(k[1]) == "system"), key=lambda k: (-k[1].priority, k[0])
|
|
666
|
+
)
|
|
667
|
+
finals = sorted(
|
|
668
|
+
(k for k in kept if _ord_role(k[1]) == "user"), key=lambda k: (k[1].priority, k[0])
|
|
669
|
+
) # ascending -> highest-priority user turn ends up last (strongest end position)
|
|
670
|
+
middles = sorted(
|
|
671
|
+
(k for k in kept if _ord_role(k[1]) not in ("system", "user")),
|
|
672
|
+
key=lambda k: (-k[1].priority, k[0]),
|
|
673
|
+
)
|
|
674
|
+
return [*systems, *_edge_load(middles), *finals]
|
|
675
|
+
# default: role-grouped, insertion order within a role.
|
|
676
|
+
return sorted(kept, key=lambda k: (_ROLE_RANK.get(_ord_role(k[1]), 1), k[0]))
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def _edge_load(items: list) -> list:
|
|
680
|
+
"""Edge-load a priority-descending list: highest at both edges, lowest in the center."""
|
|
681
|
+
left: list = []
|
|
682
|
+
right: list = []
|
|
683
|
+
for i, item in enumerate(items):
|
|
684
|
+
(left if i % 2 == 0 else right).append(item)
|
|
685
|
+
return left + right[::-1]
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def _text_of(content: Any) -> str:
|
|
689
|
+
"""Plain text of message content — a string, or the text parts of a multimodal list."""
|
|
690
|
+
if isinstance(content, list):
|
|
691
|
+
return "".join(p.get("text", "") for p in content if isinstance(p, dict) and "text" in p)
|
|
692
|
+
return str(content)
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def _parts_of(content: Any) -> list[dict]:
|
|
696
|
+
"""Normalize content to a list of content-block parts (text parts as ``{"text": ...}``)."""
|
|
697
|
+
if isinstance(content, list):
|
|
698
|
+
return [{"text": p["text"]} if isinstance(p, dict) and "text" in p else p for p in content]
|
|
699
|
+
return [{"text": str(content)}]
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def _call_compressor(compressor: Any, text: str, target: int, model: str) -> str:
|
|
703
|
+
"""Call either a Compressor-protocol object or a ``squeeze.compress``-style callable."""
|
|
704
|
+
if hasattr(compressor, "compress"):
|
|
705
|
+
small, _handle = compressor.compress(text, target_tokens=target, model=model)
|
|
706
|
+
else:
|
|
707
|
+
small, _handle = compressor(text, target_tokens=target)
|
|
708
|
+
return small
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
# A short, honest marker appended (head) or prepended (tail) so a truncated block reads as cut.
|
|
712
|
+
_TRUNC_MARK = {"head": "\n…[truncated]", "tail": "[truncated]…\n"}
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def _hard_cut(text: str, target: int, model: str, keep: str) -> str:
|
|
716
|
+
"""Binary-search the longest head/tail slice of ``text`` that fits ``target`` tokens."""
|
|
717
|
+
if target <= 0:
|
|
718
|
+
return ""
|
|
719
|
+
if tokens.count(text, model) <= target:
|
|
720
|
+
return text
|
|
721
|
+
lo, hi, best = 0, len(text), ""
|
|
722
|
+
while lo <= hi:
|
|
723
|
+
mid = (lo + hi) // 2
|
|
724
|
+
cand = text[:mid] if keep == "head" else text[len(text) - mid :]
|
|
725
|
+
if tokens.count(cand, model) <= target:
|
|
726
|
+
best, lo = cand, mid + 1
|
|
727
|
+
else:
|
|
728
|
+
hi = mid - 1
|
|
729
|
+
return best
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def _truncate_to_tokens(text: str, target: int, model: str, keep: str = "head") -> str:
|
|
733
|
+
"""Trim ``text`` to at most ``target`` tokens, keeping the ``head`` or ``tail``, with a marker.
|
|
734
|
+
|
|
735
|
+
The marker is counted against ``target`` so the result never exceeds the budget; if there's no
|
|
736
|
+
room for both content and marker, the text is hard-cut without one.
|
|
737
|
+
"""
|
|
738
|
+
if target <= 0:
|
|
739
|
+
return ""
|
|
740
|
+
if tokens.count(text, model) <= target:
|
|
741
|
+
return text
|
|
742
|
+
marker = _TRUNC_MARK[keep]
|
|
743
|
+
body_budget = max(0, target - tokens.count(marker, model))
|
|
744
|
+
if body_budget == 0:
|
|
745
|
+
return _hard_cut(text, target, model, keep)
|
|
746
|
+
body = _hard_cut(text, body_budget, model, keep)
|
|
747
|
+
return body + marker if keep == "head" else marker + body
|
|
File without changes
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cendor-contextkit
|
|
3
|
+
Version: 0.6.1
|
|
4
|
+
Summary: Assemble: declare prioritized, pinnable context blocks; pack them to a token budget with an inspectable receipt.
|
|
5
|
+
Author: Raghav Mishra
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
License-File: NOTICE
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Requires-Dist: cendor-core<0.2,>=0.1
|
|
11
|
+
Provides-Extra: squeeze
|
|
12
|
+
Requires-Dist: cendor-squeeze<0.2,>=0.1; extra == 'squeeze'
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# cendor-contextkit
|
|
16
|
+
|
|
17
|
+
Treat the context window like a packed suitcase, not a string you concatenate. Declare blocks
|
|
18
|
+
with priorities and eviction rules; contextkit fits them to a token budget and tells you exactly
|
|
19
|
+
what it kept, shrank, and dropped.
|
|
20
|
+
|
|
21
|
+
**Every assembled prompt comes with a receipt.**
|
|
22
|
+
|
|
23
|
+
  · `pip install cendor-contextkit`
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from cendor.contextkit import Context, Block
|
|
27
|
+
|
|
28
|
+
ctx = Context(budget_tokens=8000, model="claude-opus-4-8", reserve_output=1000, order="attention")
|
|
29
|
+
ctx.add(Block(system_prompt, priority=10, pin=True, role="system"))
|
|
30
|
+
ctx.add(Block(retrieved_docs, priority=5, evict="compress")) # uses squeeze if installed
|
|
31
|
+
ctx.add(Block(messages=chat_history, priority=3, evict="drop_oldest")) # peels OLDEST turns
|
|
32
|
+
ctx.add(Block(user_msg, priority=9, pin=True, role="user"))
|
|
33
|
+
|
|
34
|
+
messages = ctx.assemble() # provider-ready, guaranteed within budget — including framing
|
|
35
|
+
print(ctx.report()) # the receipt: kept / truncated / dropped + token math
|
|
36
|
+
preview = ctx.whatif(budget_tokens=4000) # same inputs, tighter budget, no commit
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Highlights
|
|
40
|
+
|
|
41
|
+
- **Token-budgeted packing** — declare `Block`s with `priority` and `pin`; `assemble()` fits them into the budget deterministically. Pinned blocks are never evicted (raises `BudgetError` if they alone overflow).
|
|
42
|
+
- **Per-block eviction** — `drop_oldest` · `truncate` (keep head/tail, with a `…[truncated]` marker) · `summarize` (sync, or async via `aassemble()`) · `compress` (via squeeze) · or any custom `EvictionStrategy`.
|
|
43
|
+
- **Real chat-history** — `Block(messages=[…])` peels the *oldest turns* to fit (a sliding window) — never mangling a turn.
|
|
44
|
+
- **An honest receipt** — `report().used == tokens.count(assemble(), model)`: packing charges the per-message framing providers add, so a "full" prompt never quietly overflows once sent.
|
|
45
|
+
- **Attention-aware ordering** — `order="default"` · `"attention"` (lost-in-the-middle) · `"cache"` (stable prefix for prompt-cache hits).
|
|
46
|
+
- **Provider adapters & multimodal** — `for_anthropic()` / `for_gemini()` / `for_bedrock()`; per-image `image_tokens` (int or resolution-aware callable); `whatif(budget)` previews; `use_compressor()` swaps the compression backend.
|
|
47
|
+
|
|
48
|
+
**Inbound** — call it *before* the model call; `report()` flows onto core's bus, so `acttrace` records what the model actually saw.
|
|
49
|
+
|
|
50
|
+
See [`docs/contextkit.md`](https://github.com/PowerAI-Labs/Cendor/blob/main/docs/contextkit.md) · [CHANGELOG](https://github.com/PowerAI-Labs/Cendor/blob/main/packages/cendor-contextkit/CHANGELOG.md). *Part of the Cendor stack — [github.com/PowerAI-Labs/Cendor](https://github.com/PowerAI-Labs/Cendor). Powered by PowerAI Labs. Apache-2.0; provided "as is", without warranty — use at your own risk (LICENSE §7–8).*
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
cendor/contextkit/__init__.py,sha256=6E__bf7Hr1DEYC7FgJJi2Cy7GvowPZtXyrOd_SFAwSg,32973
|
|
2
|
+
cendor/contextkit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
cendor_contextkit-0.6.1.dist-info/METADATA,sha256=4pfPCO0XyXv75x2lOv_mmN1eidBQJq3LIdwXRlTrtLM,3369
|
|
4
|
+
cendor_contextkit-0.6.1.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
5
|
+
cendor_contextkit-0.6.1.dist-info/licenses/LICENSE,sha256=rWd-5vQbNwLV-BXHAMGdYtO9C_qmH_CJRYguqs5VFew,11358
|
|
6
|
+
cendor_contextkit-0.6.1.dist-info/licenses/NOTICE,sha256=X9hofg62ar1nYcEJKv6QxqFj6_Yw_nYZEJ6ioOtznj0,222
|
|
7
|
+
cendor_contextkit-0.6.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Raghav Mishra (PowerAI Labs)
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|