ctxbudgeter 0.2.0__tar.gz
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.
- ctxbudgeter-0.2.0/.gitignore +44 -0
- ctxbudgeter-0.2.0/LICENSE +21 -0
- ctxbudgeter-0.2.0/PKG-INFO +570 -0
- ctxbudgeter-0.2.0/README.md +506 -0
- ctxbudgeter-0.2.0/pyproject.toml +133 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/__init__.py +90 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/adapters/__init__.py +24 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/adapters/anthropic.py +124 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/adapters/langchain.py +68 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/adapters/openai.py +130 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/adapters/pydantic_ai.py +75 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/cli.py +449 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/compiler.py +1184 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/content.py +79 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/item.py +116 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/loaders.py +100 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/memory.py +171 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/pack.py +357 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/py.typed +0 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/pytest_plugin.py +60 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/reference.py +79 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/report.py +150 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/scoring.py +55 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/spec.py +307 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/testing.py +233 -0
- ctxbudgeter-0.2.0/src/ctxbudgeter/tokenizer.py +97 -0
- ctxbudgeter-0.2.0/tests/__init__.py +0 -0
- ctxbudgeter-0.2.0/tests/conftest.py +33 -0
- ctxbudgeter-0.2.0/tests/test_adapters.py +145 -0
- ctxbudgeter-0.2.0/tests/test_async.py +100 -0
- ctxbudgeter-0.2.0/tests/test_budget.py +68 -0
- ctxbudgeter-0.2.0/tests/test_cli.py +149 -0
- ctxbudgeter-0.2.0/tests/test_cli_v2.py +127 -0
- ctxbudgeter-0.2.0/tests/test_compiler.py +278 -0
- ctxbudgeter-0.2.0/tests/test_fork.py +59 -0
- ctxbudgeter-0.2.0/tests/test_item.py +72 -0
- ctxbudgeter-0.2.0/tests/test_memory.py +85 -0
- ctxbudgeter-0.2.0/tests/test_multimodal.py +73 -0
- ctxbudgeter-0.2.0/tests/test_openai_cache.py +59 -0
- ctxbudgeter-0.2.0/tests/test_pytest_plugin.py +63 -0
- ctxbudgeter-0.2.0/tests/test_reference.py +146 -0
- ctxbudgeter-0.2.0/tests/test_report.py +76 -0
- ctxbudgeter-0.2.0/tests/test_round_trip.py +48 -0
- ctxbudgeter-0.2.0/tests/test_scoring.py +46 -0
- ctxbudgeter-0.2.0/tests/test_sensitivity.py +60 -0
- ctxbudgeter-0.2.0/tests/test_spec.py +163 -0
- ctxbudgeter-0.2.0/tests/test_testing_api.py +154 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
__pycache__/
|
|
2
|
+
*.py[cod]
|
|
3
|
+
*$py.class
|
|
4
|
+
*.so
|
|
5
|
+
.Python
|
|
6
|
+
build/
|
|
7
|
+
develop-eggs/
|
|
8
|
+
dist/
|
|
9
|
+
downloads/
|
|
10
|
+
eggs/
|
|
11
|
+
.eggs/
|
|
12
|
+
lib/
|
|
13
|
+
lib64/
|
|
14
|
+
parts/
|
|
15
|
+
sdist/
|
|
16
|
+
var/
|
|
17
|
+
wheels/
|
|
18
|
+
*.egg-info/
|
|
19
|
+
.installed.cfg
|
|
20
|
+
*.egg
|
|
21
|
+
MANIFEST
|
|
22
|
+
|
|
23
|
+
.venv/
|
|
24
|
+
venv/
|
|
25
|
+
env/
|
|
26
|
+
ENV/
|
|
27
|
+
|
|
28
|
+
.pytest_cache/
|
|
29
|
+
.coverage
|
|
30
|
+
htmlcov/
|
|
31
|
+
.mypy_cache/
|
|
32
|
+
.ruff_cache/
|
|
33
|
+
.tox/
|
|
34
|
+
|
|
35
|
+
.idea/
|
|
36
|
+
.vscode/
|
|
37
|
+
*.swp
|
|
38
|
+
.DS_Store
|
|
39
|
+
|
|
40
|
+
# Marketing / promo material — not part of the PyPI package
|
|
41
|
+
marketing/
|
|
42
|
+
|
|
43
|
+
# Local agent-generated golden snapshot fixtures
|
|
44
|
+
.ctxbudgeter/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ctxbudgeter contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ctxbudgeter
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Context compiler for agentic AI: compile clean, cheap, auditable context under a token budget. Framework-agnostic. Local-first. Deterministic.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Kayariyan28/ctxbudgeter
|
|
6
|
+
Project-URL: Documentation, https://github.com/Kayariyan28/ctxbudgeter#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/Kayariyan28/ctxbudgeter
|
|
8
|
+
Project-URL: Issues, https://github.com/Kayariyan28/ctxbudgeter/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/Kayariyan28/ctxbudgeter/blob/main/CHANGELOG.md
|
|
10
|
+
Author-email: Karan Chandra Dey <karandey3@outlook.com>
|
|
11
|
+
Maintainer-email: Karan Chandra Dey <karandey3@outlook.com>
|
|
12
|
+
License: MIT
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Keywords: agents,ai,anthropic,context,context-engineering,crewai,langchain,langgraph,llm,openai,prompt,prompt-caching,prompt-engineering,pydantic-ai,rag,token-budget
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Framework :: Pytest
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: Intended Audience :: Information Technology
|
|
19
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Classifier: Programming Language :: Python
|
|
22
|
+
Classifier: Programming Language :: Python :: 3
|
|
23
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
27
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
28
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
29
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
30
|
+
Classifier: Topic :: Software Development :: Testing
|
|
31
|
+
Classifier: Typing :: Typed
|
|
32
|
+
Requires-Python: >=3.10
|
|
33
|
+
Requires-Dist: pydantic<3.0,>=2.5
|
|
34
|
+
Requires-Dist: rich>=13.0
|
|
35
|
+
Requires-Dist: typer>=0.9
|
|
36
|
+
Provides-Extra: all
|
|
37
|
+
Requires-Dist: anthropic>=0.30; extra == 'all'
|
|
38
|
+
Requires-Dist: langchain-core>=0.1; extra == 'all'
|
|
39
|
+
Requires-Dist: openai>=1.0; extra == 'all'
|
|
40
|
+
Requires-Dist: pyyaml>=6.0; extra == 'all'
|
|
41
|
+
Requires-Dist: requests>=2.28; extra == 'all'
|
|
42
|
+
Requires-Dist: tiktoken>=0.5; extra == 'all'
|
|
43
|
+
Provides-Extra: anthropic
|
|
44
|
+
Requires-Dist: anthropic>=0.30; extra == 'anthropic'
|
|
45
|
+
Provides-Extra: dev
|
|
46
|
+
Requires-Dist: mypy>=1.5; extra == 'dev'
|
|
47
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
|
|
48
|
+
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
|
|
49
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
50
|
+
Requires-Dist: pyyaml>=6.0; extra == 'dev'
|
|
51
|
+
Requires-Dist: ruff>=0.1; extra == 'dev'
|
|
52
|
+
Requires-Dist: tiktoken>=0.5; extra == 'dev'
|
|
53
|
+
Provides-Extra: http
|
|
54
|
+
Requires-Dist: requests>=2.28; extra == 'http'
|
|
55
|
+
Provides-Extra: langchain
|
|
56
|
+
Requires-Dist: langchain-core>=0.1; extra == 'langchain'
|
|
57
|
+
Provides-Extra: openai
|
|
58
|
+
Requires-Dist: openai>=1.0; extra == 'openai'
|
|
59
|
+
Provides-Extra: tiktoken
|
|
60
|
+
Requires-Dist: tiktoken>=0.5; extra == 'tiktoken'
|
|
61
|
+
Provides-Extra: yaml
|
|
62
|
+
Requires-Dist: pyyaml>=6.0; extra == 'yaml'
|
|
63
|
+
Description-Content-Type: text/markdown
|
|
64
|
+
|
|
65
|
+
# ctxbudgeter
|
|
66
|
+
|
|
67
|
+
[](https://pypi.org/project/ctxbudgeter/)
|
|
68
|
+
[](https://pypi.org/project/ctxbudgeter/)
|
|
69
|
+
[](https://opensource.org/licenses/MIT)
|
|
70
|
+
[](https://github.com/Kayariyan28/ctxbudgeter/actions/workflows/test.yml)
|
|
71
|
+
|
|
72
|
+
> Compile clean, cheap, auditable context for AI agents.
|
|
73
|
+
|
|
74
|
+
`ctxbudgeter` is a framework-agnostic **context engineering toolkit** for agentic AI. Hand it the raw materials — system rules, docs, code, memory notes, tool results, the latest user request — and it decides what enters the model, what gets dropped, what gets compressed, what should be cached, and **why**. Every decision is auditable. Every compilation is deterministic. Tests can gate on context the same way they gate on code.
|
|
75
|
+
|
|
76
|
+
**Use any agent framework.** ctxbudgeter sits in front of LangGraph, CrewAI, OpenAI Agents SDK, PydanticAI, Microsoft Agent Framework, or your own loop. It does one thing: make the context you send to the model cleaner, cheaper, and assertable.
|
|
77
|
+
|
|
78
|
+
```text
|
|
79
|
+
Webpack for agent context • pytest for prompt/context quality • token budget manager
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## What you get
|
|
83
|
+
|
|
84
|
+
- **Token budget compiler** — deterministic, explainable selection with full inclusion/exclusion reasons
|
|
85
|
+
- **Just-in-time `Reference`s** — lazy pointers (file paths, URLs, queries) that only load if they fit
|
|
86
|
+
- **Eval / assert layer + pytest plugin** — `assert_includes`, `assert_health_at_least`, golden snapshots
|
|
87
|
+
- **Cache-aware adapters** — Anthropic `cache_control` placement, OpenAI `prompt_cache_key`, LangChain & PydanticAI
|
|
88
|
+
- **Multi-modal attachments** — images and structured tool schemas flow through to OpenAI/Anthropic payloads
|
|
89
|
+
- **Sensitivity enforcement** — `allow` | `warn` | `refuse` | `redact` for items tagged `secret`
|
|
90
|
+
- **Memory store** (Write strategy) — persist agent notes between turns, query them back into context
|
|
91
|
+
- **Isolation** (Isolate strategy) — `pack.fork()` builds a subagent-scoped pack with its own budget
|
|
92
|
+
- **Async compile** — concurrent resolution of async References, async-aware compressor hook
|
|
93
|
+
- **Declarative YAML/JSON specs** — check pack configuration into git, CI-friendly
|
|
94
|
+
- **CLI** — `scan`, `compile`, `pack`, `validate`, `report` for Claude Code and CI workflows
|
|
95
|
+
- **Zero LLM calls in the core** — local-first, deterministic, fast
|
|
96
|
+
|
|
97
|
+
## Install
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
pip install ctxbudgeter
|
|
101
|
+
|
|
102
|
+
# Optional extras
|
|
103
|
+
pip install "ctxbudgeter[tiktoken]" # accurate OpenAI/Anthropic-proxy tokenization
|
|
104
|
+
pip install "ctxbudgeter[yaml]" # YAML pack specs
|
|
105
|
+
pip install "ctxbudgeter[http]" # http_get loader for References
|
|
106
|
+
pip install "ctxbudgeter[anthropic,openai,langchain]"
|
|
107
|
+
pip install "ctxbudgeter[all]" # everything
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Python 3.10+. Adapters are lazy-imported — you only pay for the SDKs you actually use.
|
|
111
|
+
|
|
112
|
+
## Quick start
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from ctxbudgeter import ContextPack
|
|
116
|
+
|
|
117
|
+
pack = ContextPack(
|
|
118
|
+
model="claude-sonnet-4.6",
|
|
119
|
+
token_budget=24_000,
|
|
120
|
+
reserved_output_tokens=4_000,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
pack.add(
|
|
124
|
+
name="system_rules",
|
|
125
|
+
content="You are a careful coding agent...",
|
|
126
|
+
kind="system",
|
|
127
|
+
priority=100,
|
|
128
|
+
cache_policy="stable",
|
|
129
|
+
required=True,
|
|
130
|
+
)
|
|
131
|
+
pack.add_file("README.md", kind="project_doc", priority=80)
|
|
132
|
+
pack.add(
|
|
133
|
+
name="task",
|
|
134
|
+
content="Build the referral packet UI.",
|
|
135
|
+
kind="task",
|
|
136
|
+
priority=95,
|
|
137
|
+
required=True,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
compiled = pack.compile()
|
|
141
|
+
print(compiled.report())
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
```text
|
|
145
|
+
Included:
|
|
146
|
+
- system_rules: 312 tokens, required, stable cache prefix, system
|
|
147
|
+
- README.md: 1,420 tokens, stable cache prefix, project_doc
|
|
148
|
+
- task: 19 tokens, required, task
|
|
149
|
+
|
|
150
|
+
Excluded:
|
|
151
|
+
- old_notes.md: token-heavy and low priority — 8,400 tokens, score 41
|
|
152
|
+
- debug.log: token-heavy and low priority — 14,200 tokens, score 12
|
|
153
|
+
|
|
154
|
+
Estimated input tokens: 1,751
|
|
155
|
+
Reserved output tokens: 4,000
|
|
156
|
+
Cacheable prefix: 1,732 tokens
|
|
157
|
+
Token budget: 24,000 (utilization 8.8%)
|
|
158
|
+
Context health score: 87/100
|
|
159
|
+
breakdown: cacheable_prefix_bonus: +5, under_utilized: -5
|
|
160
|
+
Tokenizer: tiktoken
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Just-in-time References
|
|
164
|
+
|
|
165
|
+
Don't load context you'll never use. References are lightweight pointers that load only when they could plausibly fit the budget — Anthropic's "JIT" pattern, built in.
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
from ctxbudgeter import ContextPack
|
|
169
|
+
from ctxbudgeter.loaders import file_loader, http_get_loader, register_loader
|
|
170
|
+
|
|
171
|
+
pack = ContextPack(token_budget=24_000)
|
|
172
|
+
pack.add(name="task", content="Refactor auth", kind="task", required=True)
|
|
173
|
+
|
|
174
|
+
# File reference — only opened if it would fit
|
|
175
|
+
pack.add_reference(
|
|
176
|
+
name="auth_module",
|
|
177
|
+
location="src/auth.py",
|
|
178
|
+
loader=file_loader,
|
|
179
|
+
estimated_tokens=1200,
|
|
180
|
+
kind="code",
|
|
181
|
+
priority=70,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
# HTTP reference — never fetched unless budget allows
|
|
185
|
+
pack.add_reference(
|
|
186
|
+
name="api_docs",
|
|
187
|
+
location="https://example.com/docs/api.json",
|
|
188
|
+
loader=http_get_loader,
|
|
189
|
+
estimated_tokens=2000,
|
|
190
|
+
kind="retrieval",
|
|
191
|
+
priority=60,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
# Or register your own loader
|
|
195
|
+
@register_loader("vector_search")
|
|
196
|
+
def vector_search(ref):
|
|
197
|
+
return my_vector_store.search(ref.location, k=3)
|
|
198
|
+
|
|
199
|
+
pack.add_reference(name="docs_hit", location="referral packet UI", loader=vector_search, estimated_tokens=500)
|
|
200
|
+
|
|
201
|
+
compiled = pack.compile()
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Async loaders work too — use `await pack.acompile()`:
|
|
205
|
+
|
|
206
|
+
```python
|
|
207
|
+
async def fetch_user_profile(ref):
|
|
208
|
+
async with httpx.AsyncClient() as c:
|
|
209
|
+
r = await c.get(ref.location)
|
|
210
|
+
return r.text
|
|
211
|
+
|
|
212
|
+
pack.add_reference(name="profile", location="https://api.example.com/me", loader=fetch_user_profile, estimated_tokens=300)
|
|
213
|
+
compiled = await pack.acompile() # async references resolved concurrently
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
## Eval / assert layer — "pytest for prompts"
|
|
217
|
+
|
|
218
|
+
```python
|
|
219
|
+
from ctxbudgeter.testing import (
|
|
220
|
+
assert_includes, assert_excludes,
|
|
221
|
+
assert_health_at_least, assert_cacheable_prefix_at_least,
|
|
222
|
+
assert_no_secret_items, assert_used_tokens_at_most,
|
|
223
|
+
GoldenPack,
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
def test_prod_pack():
|
|
227
|
+
compiled = build_prod_pack().compile()
|
|
228
|
+
assert_includes(compiled, "system_rules", "task")
|
|
229
|
+
assert_excludes(compiled, "debug.log")
|
|
230
|
+
assert_health_at_least(compiled, 80)
|
|
231
|
+
assert_cacheable_prefix_at_least(compiled, 1024)
|
|
232
|
+
assert_no_secret_items(compiled)
|
|
233
|
+
assert_used_tokens_at_most(compiled, 20_000)
|
|
234
|
+
|
|
235
|
+
def test_pack_golden(ctxbudgeter_golden):
|
|
236
|
+
# Provided by the installed pytest plugin.
|
|
237
|
+
# Stores a golden snapshot the first time, diffs against it after.
|
|
238
|
+
ctxbudgeter_golden().check(build_prod_pack().compile())
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Refresh goldens after intentional changes:
|
|
242
|
+
|
|
243
|
+
```bash
|
|
244
|
+
pytest --ctxbudgeter-update-golden
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
## Cache-aware adapters
|
|
248
|
+
|
|
249
|
+
```python
|
|
250
|
+
from ctxbudgeter.adapters import (
|
|
251
|
+
to_anthropic_request, # cache_control on last stable system block
|
|
252
|
+
to_openai_request, # prompt_cache_key derived from stable prefix hash
|
|
253
|
+
to_langchain_messages,
|
|
254
|
+
to_pydantic_ai_deps,
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
# Anthropic
|
|
258
|
+
import anthropic
|
|
259
|
+
client = anthropic.Anthropic()
|
|
260
|
+
resp = client.messages.create(**to_anthropic_request(compiled, user_message="next step?"))
|
|
261
|
+
|
|
262
|
+
# OpenAI — explicit cache key for prompt-prefix caching
|
|
263
|
+
from openai import OpenAI
|
|
264
|
+
oa = OpenAI()
|
|
265
|
+
resp = oa.chat.completions.create(**to_openai_request(compiled, user_message="what now?"))
|
|
266
|
+
|
|
267
|
+
# LangChain
|
|
268
|
+
from langchain_anthropic import ChatAnthropic
|
|
269
|
+
msgs = to_langchain_messages(compiled, user_message="continue")
|
|
270
|
+
ChatAnthropic(model=compiled.model).invoke(msgs)
|
|
271
|
+
|
|
272
|
+
# PydanticAI
|
|
273
|
+
deps = to_pydantic_ai_deps(compiled)
|
|
274
|
+
agent.run(deps["system_prompt"], message_history=deps["message_history"])
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
## Multi-modal attachments
|
|
278
|
+
|
|
279
|
+
```python
|
|
280
|
+
from ctxbudgeter import ContextPack, ImageBlock, StructuredBlock
|
|
281
|
+
|
|
282
|
+
pack = ContextPack(token_budget=24_000)
|
|
283
|
+
pack.add(
|
|
284
|
+
name="screenshot",
|
|
285
|
+
content="Describe what's wrong in this screenshot.",
|
|
286
|
+
kind="user_message",
|
|
287
|
+
attachments=[
|
|
288
|
+
ImageBlock(url="https://example.com/bug.png", estimated_tokens=400),
|
|
289
|
+
],
|
|
290
|
+
)
|
|
291
|
+
pack.add(
|
|
292
|
+
name="tools",
|
|
293
|
+
content="",
|
|
294
|
+
kind="tool_def",
|
|
295
|
+
cache_policy="stable",
|
|
296
|
+
priority=85,
|
|
297
|
+
attachments=[
|
|
298
|
+
StructuredBlock(schema_name="search_db", data={"args": ["query"], "returns": "list[Doc]"}),
|
|
299
|
+
],
|
|
300
|
+
)
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
Image and structured blocks flow through to OpenAI's `image_url` / Anthropic's `image` / `tool_result` formats automatically.
|
|
304
|
+
|
|
305
|
+
## Sensitivity enforcement
|
|
306
|
+
|
|
307
|
+
```python
|
|
308
|
+
pack.add(name="api_key", content="sk-DEADBEEF...", sensitivity="secret")
|
|
309
|
+
|
|
310
|
+
pack.set_secret_policy("warn") # include but flag in report + health penalty (default)
|
|
311
|
+
pack.set_secret_policy("refuse") # raise SecretContentError at compile time
|
|
312
|
+
pack.set_secret_policy("redact") # replace content with [REDACTED — sensitivity=secret]
|
|
313
|
+
pack.set_secret_policy("allow") # silently allow (escape hatch)
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
In CI you almost always want `refuse` or `redact`. The text/markdown reports flag `[!secret]` items so reviewers can catch leaks during PR review.
|
|
317
|
+
|
|
318
|
+
## Memory (Write strategy) + Isolation (Isolate strategy)
|
|
319
|
+
|
|
320
|
+
```python
|
|
321
|
+
from ctxbudgeter import ContextPack, InMemoryStore, JSONMemoryStore, MemoryNote
|
|
322
|
+
|
|
323
|
+
# Persist notes across turns
|
|
324
|
+
store = JSONMemoryStore(".ctxbudgeter/memory.json")
|
|
325
|
+
store.write(MemoryNote(key="auth_runbook", content="JWT rotation...", tags=["auth"]))
|
|
326
|
+
|
|
327
|
+
# Pull them back into a future pack
|
|
328
|
+
pack = ContextPack(token_budget=24_000)
|
|
329
|
+
pack.add(name="task", content="Fix auth bug", required=True)
|
|
330
|
+
pack.add_memory(store, tags=["auth"], limit=3, priority=70)
|
|
331
|
+
|
|
332
|
+
# Isolate a subagent's context — only frontend code, smaller budget
|
|
333
|
+
frontend_pack = pack.subset_by_kind("project_doc", "code").fork(
|
|
334
|
+
filter=lambda it: it.metadata.get("area") == "frontend",
|
|
335
|
+
token_budget=8_000,
|
|
336
|
+
)
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
## Declarative YAML pack specs
|
|
340
|
+
|
|
341
|
+
Check your pack into git like any other config:
|
|
342
|
+
|
|
343
|
+
```yaml
|
|
344
|
+
# pack.yaml
|
|
345
|
+
model: claude-sonnet-4.6
|
|
346
|
+
token_budget: 24000
|
|
347
|
+
reserved_output_tokens: 4000
|
|
348
|
+
secret_policy: refuse
|
|
349
|
+
|
|
350
|
+
items:
|
|
351
|
+
- name: system_rules
|
|
352
|
+
from_file: prompts/system.md
|
|
353
|
+
kind: system
|
|
354
|
+
priority: 100
|
|
355
|
+
required: true
|
|
356
|
+
cache_policy: stable
|
|
357
|
+
|
|
358
|
+
- name: task
|
|
359
|
+
content: "Fix the auth bug."
|
|
360
|
+
kind: task
|
|
361
|
+
priority: 95
|
|
362
|
+
required: true
|
|
363
|
+
|
|
364
|
+
references:
|
|
365
|
+
- name: api_docs
|
|
366
|
+
location: "https://example.com/docs.json"
|
|
367
|
+
loader: http_get
|
|
368
|
+
estimated_tokens: 1500
|
|
369
|
+
priority: 60
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
Then compile from the CLI:
|
|
373
|
+
|
|
374
|
+
```bash
|
|
375
|
+
ctxbudgeter validate pack.yaml
|
|
376
|
+
ctxbudgeter pack pack.yaml --format markdown -o report.md
|
|
377
|
+
ctxbudgeter pack pack.yaml --fail-below 80 # exit non-zero on low health for CI
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
Or from Python:
|
|
381
|
+
|
|
382
|
+
```python
|
|
383
|
+
from ctxbudgeter.spec import load_pack
|
|
384
|
+
pack = load_pack("pack.yaml")
|
|
385
|
+
compiled = pack.compile()
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
## CLI
|
|
389
|
+
|
|
390
|
+
```bash
|
|
391
|
+
# Scan a directory, suggest priorities + cache policies
|
|
392
|
+
ctxbudgeter scan . --max-files 50
|
|
393
|
+
|
|
394
|
+
# Scan + emit a starter pack.yaml you can commit and iterate on
|
|
395
|
+
ctxbudgeter scan . --emit-pack pack.yaml --task "ship feature X"
|
|
396
|
+
|
|
397
|
+
# Ad-hoc compile from a directory + task
|
|
398
|
+
ctxbudgeter compile . --task "fix auth bug" --budget 12000 --secret-policy refuse
|
|
399
|
+
|
|
400
|
+
# Compile from a declarative spec
|
|
401
|
+
ctxbudgeter pack pack.yaml --format markdown -o context-report.md
|
|
402
|
+
|
|
403
|
+
# Re-render a saved compiled pack
|
|
404
|
+
ctxbudgeter compile . --task "..." --save-pack pack.json
|
|
405
|
+
ctxbudgeter report pack.json --format markdown
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
## Wire it into CI
|
|
409
|
+
|
|
410
|
+
### GitHub Actions
|
|
411
|
+
|
|
412
|
+
```yaml
|
|
413
|
+
# .github/workflows/context-check.yml
|
|
414
|
+
name: Context budget check
|
|
415
|
+
on: [pull_request]
|
|
416
|
+
|
|
417
|
+
jobs:
|
|
418
|
+
ctxbudget:
|
|
419
|
+
runs-on: ubuntu-latest
|
|
420
|
+
steps:
|
|
421
|
+
- uses: actions/checkout@v4
|
|
422
|
+
- uses: actions/setup-python@v5
|
|
423
|
+
with:
|
|
424
|
+
python-version: "3.11"
|
|
425
|
+
- run: pip install "ctxbudgeter[all]"
|
|
426
|
+
- name: Validate and compile pack
|
|
427
|
+
run: |
|
|
428
|
+
ctxbudgeter validate pack.yaml
|
|
429
|
+
ctxbudgeter pack pack.yaml --format markdown --fail-below 80 -o report.md
|
|
430
|
+
- name: Comment report on PR
|
|
431
|
+
uses: marocchino/sticky-pull-request-comment@v2
|
|
432
|
+
with:
|
|
433
|
+
path: report.md
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
### pre-commit
|
|
437
|
+
|
|
438
|
+
```yaml
|
|
439
|
+
# .pre-commit-config.yaml
|
|
440
|
+
repos:
|
|
441
|
+
- repo: local
|
|
442
|
+
hooks:
|
|
443
|
+
- id: ctxbudgeter-validate
|
|
444
|
+
name: ctxbudgeter validate pack.yaml
|
|
445
|
+
entry: ctxbudgeter validate pack.yaml
|
|
446
|
+
language: system
|
|
447
|
+
pass_filenames: false
|
|
448
|
+
files: ^pack\.yaml$
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
### pytest
|
|
452
|
+
|
|
453
|
+
```python
|
|
454
|
+
# tests/test_context.py
|
|
455
|
+
from ctxbudgeter.testing import (
|
|
456
|
+
assert_health_at_least, assert_no_secret_items, assert_includes,
|
|
457
|
+
)
|
|
458
|
+
from my_app.context import build_pack
|
|
459
|
+
|
|
460
|
+
def test_production_pack_quality():
|
|
461
|
+
compiled = build_pack(task="fix auth bug").compile()
|
|
462
|
+
assert_includes(compiled, "system_rules", "task")
|
|
463
|
+
assert_health_at_least(compiled, 80)
|
|
464
|
+
assert_no_secret_items(compiled)
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
## How it works
|
|
468
|
+
|
|
469
|
+
### Compiler algorithm
|
|
470
|
+
|
|
471
|
+
1. Resolve `Reference`s — load only those whose estimated cost could fit. Loader failures → excluded with reason.
|
|
472
|
+
2. Required items go in first; compress (via your hook) or truncate if they don't fit.
|
|
473
|
+
3. Optional items ranked by `score_item`, packed greedily.
|
|
474
|
+
4. Sensitivity policy applied (warn / refuse / redact / allow).
|
|
475
|
+
5. Final prompt order: stable → dynamic → ephemeral, deterministic tie-breaks.
|
|
476
|
+
6. Cacheable prefix = consecutive stable items at the top.
|
|
477
|
+
|
|
478
|
+
```text
|
|
479
|
+
score = priority*0.5 + relevance*100*0.3 + freshness*100*0.1 + cache_value*100*0.1 - token_cost_penalty
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
`token_cost_penalty` grows up to ~30 points as an item approaches the full budget — a 50k-token debug log doesn't beat your README on priority alone.
|
|
483
|
+
|
|
484
|
+
### Health score breakdown
|
|
485
|
+
|
|
486
|
+
A 0–100 score with explicit, auditable deductions. Each pack reports its breakdown:
|
|
487
|
+
|
|
488
|
+
```json
|
|
489
|
+
{
|
|
490
|
+
"health_score": 87,
|
|
491
|
+
"health_breakdown": {
|
|
492
|
+
"cacheable_prefix_bonus": 5,
|
|
493
|
+
"under_utilized": -5,
|
|
494
|
+
"high_priority_excluded": -10,
|
|
495
|
+
"secrets_included": -10
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
If you'd rather not show "health" — treat it as `BudgetCheckScore`: a determinstic, explainable signal, not a quality oracle.
|
|
501
|
+
|
|
502
|
+
### Compression hook
|
|
503
|
+
|
|
504
|
+
`ctxbudgeter` never calls an LLM for you. Provide a function — sync or async, your choice:
|
|
505
|
+
|
|
506
|
+
```python
|
|
507
|
+
async def my_summarizer(item, target_tokens):
|
|
508
|
+
return await anthropic_client.summarize(item.content, max_tokens=target_tokens)
|
|
509
|
+
|
|
510
|
+
pack.set_compressor(my_summarizer)
|
|
511
|
+
compiled = await pack.acompile() # async path; sync compressors also work with .compile()
|
|
512
|
+
```
|
|
513
|
+
|
|
514
|
+
If your compressor returns content larger than `target_tokens`, the compiler retries once with a tighter target before giving up.
|
|
515
|
+
|
|
516
|
+
## Round-trip + tooling
|
|
517
|
+
|
|
518
|
+
```python
|
|
519
|
+
import json
|
|
520
|
+
from ctxbudgeter import compiled_pack_from_dict
|
|
521
|
+
|
|
522
|
+
# Compile, save, share
|
|
523
|
+
compiled = pack.compile()
|
|
524
|
+
Path("compiled.json").write_text(json.dumps(compiled.to_dict()))
|
|
525
|
+
|
|
526
|
+
# Reload later for reporting / diffing / assertions
|
|
527
|
+
restored = compiled_pack_from_dict(json.loads(Path("compiled.json").read_text()))
|
|
528
|
+
print(restored.report("markdown"))
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
## Positioning
|
|
532
|
+
|
|
533
|
+
Most agent frameworks ask: *"which agent runs next?"*
|
|
534
|
+
ctxbudgeter asks: *"what exact information should this agent see right now — and why?"*
|
|
535
|
+
|
|
536
|
+
| Layer | Existing | What ctxbudgeter adds |
|
|
537
|
+
| ---------------- | ----------------------------------------- | -------------------------------------------------- |
|
|
538
|
+
| Agent frameworks | LangGraph, CrewAI, OpenAI Agents SDK, PydanticAI | Decides the **context shape** before the call |
|
|
539
|
+
| RAG | LlamaIndex, LangChain retrievers | Retrieval ≠ final context; ctxbudgeter is the gate |
|
|
540
|
+
| Observability | LangSmith, AgentOps | They show what happened *after*; we prevent *before* |
|
|
541
|
+
| Context tools | ctxforge, contextkit, contextagent | We're the **assertable** + **deterministic** option |
|
|
542
|
+
|
|
543
|
+
## Design choices
|
|
544
|
+
|
|
545
|
+
- **Local-first.** No LLM API calls in the core. The compiler is pure Python.
|
|
546
|
+
- **Deterministic.** Same inputs → identical compiled pack. Same JSON output. Same health score. Always.
|
|
547
|
+
- **Explainable.** Every input item shows up in `decisions` with a status and a human-readable reason.
|
|
548
|
+
- **Framework-agnostic.** Core has zero hard dependencies on agent SDKs. Adapters are lazy-imported.
|
|
549
|
+
- **Composable.** Bring your own tokenizer, your own compressor, your own scoring weights, your own loaders, your own memory store.
|
|
550
|
+
- **Assertable.** Quality gates live in `pytest`, not in your head.
|
|
551
|
+
|
|
552
|
+
## Author
|
|
553
|
+
|
|
554
|
+
**Karan Chandra Dey** — `[K28]`
|
|
555
|
+
Founder and AI Product Builder @ **K28 Design Lab** · [k28art.space](https://k28art.space)
|
|
556
|
+
|
|
557
|
+
Helping SMEs ship their first AI MVP — from prompt engineering to context engineering to production-ready agents.
|
|
558
|
+
|
|
559
|
+
| | |
|
|
560
|
+
|---|---|
|
|
561
|
+
| Web | [k28art.space](https://k28art.space) |
|
|
562
|
+
| GitHub | [@Kayariyan28](https://github.com/Kayariyan28) |
|
|
563
|
+
| LinkedIn | [karan-chandra-dey](https://www.linkedin.com/in/karan-chandra-dey-23392b1b9) |
|
|
564
|
+
| Email | karandey3@outlook.com |
|
|
565
|
+
|
|
566
|
+
> "Use any agent framework. ctxbudgeter makes your context cleaner, cheaper, and assertable — before the model sees it."
|
|
567
|
+
|
|
568
|
+
## License
|
|
569
|
+
|
|
570
|
+
MIT © Karan Chandra Dey / K28 Design Lab.
|