kazenai 0.1.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.
kazenai-0.1.0/LICENSE ADDED
@@ -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 [yyyy] [name of copyright owner]
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.
kazenai-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,267 @@
1
+ Metadata-Version: 2.4
2
+ Name: kazenai
3
+ Version: 0.1.0
4
+ Summary: Reliability infrastructure for AI agents: Local-first budget & loop enforcement.
5
+ Author-email: Dhavan Shah <founder@kazenai.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://kazenai.com
8
+ Project-URL: Repository, https://github.com/kazenai-ai/kazenai-core
9
+ Keywords: llm,agents,observability,finops,langchain
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: pydantic>=2.6.0
14
+ Requires-Dist: structlog>=24.1.0
15
+ Requires-Dist: aiohttp>=3.9.0
16
+ Requires-Dist: pydantic-settings>=2.1.0
17
+ Dynamic: license-file
18
+
19
+ # kazenai-core
20
+
21
+ > **Stop your AI agents from burning your budget. Catch loops before they catch you.**
22
+
23
+ [![PyPI version](https://badge.fury.io/py/kazenai-finops.svg)](https://badge.fury.io/py/kazenai-finops)
24
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
25
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
26
+ [![Status: Building in Public](https://img.shields.io/badge/status-building%20in%20public-orange.svg)](https://x.com/kazenai)
27
+
28
+ ---
29
+
30
+ ## What is KazenAI?
31
+
32
+ KazenAI is **reliability infrastructure for AI agents**.
33
+
34
+ When you run an AI agent in production, three things will eventually go wrong:
35
+
36
+ 1. **It loops** — and burns your entire monthly LLM budget in 40 minutes
37
+ 2. **It fails silently** — returns 200 OK but the business outcome is wrong
38
+ 3. **You can't debug it** — because AI agents are non-deterministic and single-trace debugging is meaningless
39
+
40
+ KazenAI intercepts every LLM and tool call your agent makes, enforces budget limits locally (no network required), detects loops before they become expensive, and gives you full observability — with one function call.
41
+
42
+ ```python
43
+ from kazenai import monitor
44
+
45
+ agent = monitor(
46
+ agent,
47
+ agent_id="support-agent",
48
+ api_key="kz_...",
49
+ max_budget_usd=5.00,
50
+ debug=True, # see cost per call in your terminal
51
+ )
52
+ ```
53
+
54
+ That's it. Your agent code doesn't change.
55
+
56
+ ---
57
+
58
+ ## The problem in one screenshot
59
+
60
+ ```
61
+ [KazenAI] step=1 gpt-4o-mini cost=$0.0043 total=$0.0043 proj=$0.21/$5.00 OK
62
+ [KazenAI] step=2 gpt-4o-mini cost=$0.0041 total=$0.0084 proj=$0.19/$5.00 OK
63
+ [KazenAI] step=8 gpt-4o-mini cost=$0.0039 total=$0.43 proj=$4.91/$5.00 WARN:budget_87pct
64
+ [KazenAI] step=9 gpt-4o-mini BLOCKED:budget spent=$5.00 limit=$5.00
65
+
66
+ KazenBudgetExceeded: Run agent-001: budget $5.00 exceeded (spent $4.97, attempted $5.42)
67
+ ```
68
+
69
+ No more waking up to a $47K bill.
70
+
71
+ ---
72
+
73
+ ## Features (MVP — shipping Week 1)
74
+
75
+ - **`monitor(agent, ...)`** — wraps LangChain, AutoGen, and CrewAI agents with one call
76
+ - **Local budget enforcement** — blocks calls before they're made, no network required, <1ms
77
+ - **Real-time debug output** — `debug=True` prints cost + status after every LLM call
78
+ - **Loop detection (H1)** — Jaccard similarity catches near-duplicate inputs before they spiral
79
+ - **Loop detection (H2)** — tool chain fingerprinting catches recursive tool patterns
80
+ - **Rate limiting** — `max_calls_per_minute` prevents runaway agents from moving too fast
81
+ - **Event sampling** — `sample_rate=0.3` to control backend traffic at scale
82
+ - **Offline resilience** — RetryQueue (SQLite) stores events locally if backend is down
83
+ - **Parent-child tracing** — `RunContext` with `parent_step_id` for multi-agent pipelines
84
+ - **Canonical event schema** — `KazenEvent` shared by SDK and backend (no field drift)
85
+ - **OpenAI patcher** — transparent monkey-patch, no code changes required
86
+ - **LangChain integration** — `KazenCallbackHandler` + `LangChainProxy`
87
+ - **AutoGen integration** — wraps `initiate_chat`
88
+ - **CrewAI integration** — wraps `kickoff()`
89
+
90
+ ## Planned Modules (Roadmap)
91
+
92
+ - **AgentLens P1** — step-level trace capture dashboard (Month 2)
93
+ - **AgentLens P2** — Probabilistic Replay Engine: run any trace N times, get statistical distribution of outcomes (Month 5) — *no competitor has built this*
94
+ - **AgentLens P3** — Semantic Drift Monitor: detect when your agent's behaviour changes after a model update (Month 6)
95
+ - **TypeScript SDK** — for Node.js agent frameworks (Month 6)
96
+
97
+ ---
98
+
99
+ ## Installation
100
+
101
+ ```bash
102
+ pip install kazenai-finops
103
+ ```
104
+
105
+ Python 3.10, 3.11, 3.12 supported. No C extensions. Installs in under 30 seconds.
106
+
107
+ ---
108
+
109
+ ## Quick Start
110
+
111
+ ### Raw OpenAI (no framework)
112
+
113
+ ```python
114
+ import openai
115
+ from kazenai import monitor, KazenBudgetExceeded
116
+
117
+ client = openai.OpenAI()
118
+
119
+ # monitor() patches the OpenAI client transparently
120
+ with_monitoring = monitor(
121
+ client,
122
+ agent_id="my-agent",
123
+ api_key="kz_...", # get yours at kazenai.com
124
+ max_budget_usd=0.50,
125
+ debug=True,
126
+ )
127
+
128
+ try:
129
+ for i in range(100): # simulated loop
130
+ response = client.chat.completions.create(
131
+ model="gpt-4o-mini",
132
+ messages=[{"role": "user", "content": f"Step {i}: do the thing"}],
133
+ )
134
+ except KazenBudgetExceeded as e:
135
+ print(f"Blocked at step {e.run_id}: spent ${e.spent:.4f}")
136
+ ```
137
+
138
+ ### LangChain
139
+
140
+ ```python
141
+ from kazenai import monitor
142
+
143
+ chain = your_langchain_chain # LCEL chain, agent, etc.
144
+ monitored = monitor(
145
+ chain,
146
+ agent_id="customer-support",
147
+ api_key="kz_...",
148
+ max_budget_usd=2.00,
149
+ debug=True,
150
+ )
151
+
152
+ result = monitored.invoke({"input": "help me with my order"})
153
+ ```
154
+
155
+ ### CrewAI
156
+
157
+ ```python
158
+ from kazenai import monitor
159
+
160
+ crew = YourCrew()
161
+ monitored = monitor(
162
+ crew,
163
+ agent_id="research-crew",
164
+ api_key="kz_...",
165
+ max_budget_usd=10.00,
166
+ h2_max_reps=3, # block if same tool chain repeats 3 times
167
+ )
168
+
169
+ result = monitored.kickoff(inputs={"topic": "AI trends"})
170
+ ```
171
+
172
+ ---
173
+
174
+ ## Why local enforcement matters
175
+
176
+ Most observability tools record what happened. **KazenAI blocks what's about to happen.**
177
+
178
+ ```
179
+ Traditional tools: LLM call → response → log cost → dashboard shows $47K
180
+ KazenAI: Pre-flight check → BLOCKED → LLM call never made
181
+ ```
182
+
183
+ Local enforcement means:
184
+ - **No network dependency** — works with `backend_url=None`
185
+ - **No latency added** — budget check completes in <1ms
186
+ - **No backend outage = no protection failure** — the agent doesn't need to reach our servers to be protected
187
+
188
+ ---
189
+
190
+ ## Repository Structure
191
+
192
+ ```
193
+ kazenai-core/
194
+ ├── kazenai/
195
+ │ ├── __init__.py # public API: monitor()
196
+ │ ├── schema.py # canonical KazenEvent (shared SDK + backend)
197
+ │ ├── context.py # RunContext with parent_step_id
198
+ │ ├── monitor.py # monitor() entry point
199
+ │ ├── interceptor.py # LLM/tool call interception
200
+ │ ├── enforcement.py # local budget + rate limit enforcement
201
+ │ ├── loop_detector.py # H1 (Jaccard) + H2 (chain fingerprint)
202
+ │ ├── cost_tracker.py # 14-model pricing table
203
+ │ ├── client.py # async API client + sampling
204
+ │ ├── retry_queue.py # SQLite retry queue for offline resilience
205
+ │ ├── debug.py # debug=True terminal output
206
+ │ ├── config.py # pydantic-settings
207
+ │ └── integrations/
208
+ │ ├── langchain.py
209
+ │ ├── autogen.py
210
+ │ ├── crewai.py
211
+ │ └── generic.py
212
+ ├── examples/
213
+ │ ├── basic_agent.py # raw OpenAI example
214
+ │ ├── langchain_example.py
215
+ │ ├── loop_example.py # trigger loop detection
216
+ │ └── benchmark_latency.py # verify <5ms overhead
217
+ ├── tests/
218
+ ├── pyproject.toml
219
+ └── README.md
220
+ ```
221
+
222
+ ---
223
+
224
+ ## Design principles
225
+
226
+ 1. **Local-first enforcement** — SDK must block without backend
227
+ 2. **Zero-blocking** — SDK overhead <5ms on hot path
228
+ 3. **Fail-open always** — internal errors never crash your agent
229
+ 4. **Canonical schema** — KazenEvent used by both SDK and backend (`extra='forbid'`)
230
+ 5. **DX over features** — `debug=True` gives value in 2 minutes
231
+
232
+ ---
233
+
234
+ ## Star this repo ⭐
235
+
236
+ If you've ever woken up to an unexpected LLM bill, or spent hours debugging an agent that returned 200 OK but did nothing useful — **star this repo**. It tells us this matters to you, and it helps us ship faster.
237
+
238
+ We're building in public. Follow [@kazenai](https://x.com/kazenai) for weekly progress updates.
239
+
240
+ ---
241
+
242
+ ## Status
243
+
244
+ **Week 1** — Building core SDK
245
+ **Week 2** — Design partner onboarding
246
+ **Week 3** — Hosted dashboard + paid tiers
247
+ **Week 4** — Public launch
248
+
249
+ Early access: [kazenai.com](https://kazenai.com) or email **founder@kazenai.com**
250
+
251
+ ---
252
+
253
+ ## Contributing
254
+
255
+ We're pre-1.0 and moving fast. The best way to contribute right now is:
256
+
257
+ 1. ⭐ Star the repo
258
+ 2. Open an issue describing a pain point you've hit with AI agent costs or loops
259
+ 3. Try the examples and report what breaks
260
+
261
+ Full contribution guide coming with v1.0.
262
+
263
+ ---
264
+
265
+ ## License
266
+
267
+ Apache 2.0 — use it for anything, attribution appreciated.
@@ -0,0 +1,249 @@
1
+ # kazenai-core
2
+
3
+ > **Stop your AI agents from burning your budget. Catch loops before they catch you.**
4
+
5
+ [![PyPI version](https://badge.fury.io/py/kazenai-finops.svg)](https://badge.fury.io/py/kazenai-finops)
6
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
8
+ [![Status: Building in Public](https://img.shields.io/badge/status-building%20in%20public-orange.svg)](https://x.com/kazenai)
9
+
10
+ ---
11
+
12
+ ## What is KazenAI?
13
+
14
+ KazenAI is **reliability infrastructure for AI agents**.
15
+
16
+ When you run an AI agent in production, three things will eventually go wrong:
17
+
18
+ 1. **It loops** — and burns your entire monthly LLM budget in 40 minutes
19
+ 2. **It fails silently** — returns 200 OK but the business outcome is wrong
20
+ 3. **You can't debug it** — because AI agents are non-deterministic and single-trace debugging is meaningless
21
+
22
+ KazenAI intercepts every LLM and tool call your agent makes, enforces budget limits locally (no network required), detects loops before they become expensive, and gives you full observability — with one function call.
23
+
24
+ ```python
25
+ from kazenai import monitor
26
+
27
+ agent = monitor(
28
+ agent,
29
+ agent_id="support-agent",
30
+ api_key="kz_...",
31
+ max_budget_usd=5.00,
32
+ debug=True, # see cost per call in your terminal
33
+ )
34
+ ```
35
+
36
+ That's it. Your agent code doesn't change.
37
+
38
+ ---
39
+
40
+ ## The problem in one screenshot
41
+
42
+ ```
43
+ [KazenAI] step=1 gpt-4o-mini cost=$0.0043 total=$0.0043 proj=$0.21/$5.00 OK
44
+ [KazenAI] step=2 gpt-4o-mini cost=$0.0041 total=$0.0084 proj=$0.19/$5.00 OK
45
+ [KazenAI] step=8 gpt-4o-mini cost=$0.0039 total=$0.43 proj=$4.91/$5.00 WARN:budget_87pct
46
+ [KazenAI] step=9 gpt-4o-mini BLOCKED:budget spent=$5.00 limit=$5.00
47
+
48
+ KazenBudgetExceeded: Run agent-001: budget $5.00 exceeded (spent $4.97, attempted $5.42)
49
+ ```
50
+
51
+ No more waking up to a $47K bill.
52
+
53
+ ---
54
+
55
+ ## Features (MVP — shipping Week 1)
56
+
57
+ - **`monitor(agent, ...)`** — wraps LangChain, AutoGen, and CrewAI agents with one call
58
+ - **Local budget enforcement** — blocks calls before they're made, no network required, <1ms
59
+ - **Real-time debug output** — `debug=True` prints cost + status after every LLM call
60
+ - **Loop detection (H1)** — Jaccard similarity catches near-duplicate inputs before they spiral
61
+ - **Loop detection (H2)** — tool chain fingerprinting catches recursive tool patterns
62
+ - **Rate limiting** — `max_calls_per_minute` prevents runaway agents from moving too fast
63
+ - **Event sampling** — `sample_rate=0.3` to control backend traffic at scale
64
+ - **Offline resilience** — RetryQueue (SQLite) stores events locally if backend is down
65
+ - **Parent-child tracing** — `RunContext` with `parent_step_id` for multi-agent pipelines
66
+ - **Canonical event schema** — `KazenEvent` shared by SDK and backend (no field drift)
67
+ - **OpenAI patcher** — transparent monkey-patch, no code changes required
68
+ - **LangChain integration** — `KazenCallbackHandler` + `LangChainProxy`
69
+ - **AutoGen integration** — wraps `initiate_chat`
70
+ - **CrewAI integration** — wraps `kickoff()`
71
+
72
+ ## Planned Modules (Roadmap)
73
+
74
+ - **AgentLens P1** — step-level trace capture dashboard (Month 2)
75
+ - **AgentLens P2** — Probabilistic Replay Engine: run any trace N times, get statistical distribution of outcomes (Month 5) — *no competitor has built this*
76
+ - **AgentLens P3** — Semantic Drift Monitor: detect when your agent's behaviour changes after a model update (Month 6)
77
+ - **TypeScript SDK** — for Node.js agent frameworks (Month 6)
78
+
79
+ ---
80
+
81
+ ## Installation
82
+
83
+ ```bash
84
+ pip install kazenai-finops
85
+ ```
86
+
87
+ Python 3.10, 3.11, 3.12 supported. No C extensions. Installs in under 30 seconds.
88
+
89
+ ---
90
+
91
+ ## Quick Start
92
+
93
+ ### Raw OpenAI (no framework)
94
+
95
+ ```python
96
+ import openai
97
+ from kazenai import monitor, KazenBudgetExceeded
98
+
99
+ client = openai.OpenAI()
100
+
101
+ # monitor() patches the OpenAI client transparently
102
+ with_monitoring = monitor(
103
+ client,
104
+ agent_id="my-agent",
105
+ api_key="kz_...", # get yours at kazenai.com
106
+ max_budget_usd=0.50,
107
+ debug=True,
108
+ )
109
+
110
+ try:
111
+ for i in range(100): # simulated loop
112
+ response = client.chat.completions.create(
113
+ model="gpt-4o-mini",
114
+ messages=[{"role": "user", "content": f"Step {i}: do the thing"}],
115
+ )
116
+ except KazenBudgetExceeded as e:
117
+ print(f"Blocked at step {e.run_id}: spent ${e.spent:.4f}")
118
+ ```
119
+
120
+ ### LangChain
121
+
122
+ ```python
123
+ from kazenai import monitor
124
+
125
+ chain = your_langchain_chain # LCEL chain, agent, etc.
126
+ monitored = monitor(
127
+ chain,
128
+ agent_id="customer-support",
129
+ api_key="kz_...",
130
+ max_budget_usd=2.00,
131
+ debug=True,
132
+ )
133
+
134
+ result = monitored.invoke({"input": "help me with my order"})
135
+ ```
136
+
137
+ ### CrewAI
138
+
139
+ ```python
140
+ from kazenai import monitor
141
+
142
+ crew = YourCrew()
143
+ monitored = monitor(
144
+ crew,
145
+ agent_id="research-crew",
146
+ api_key="kz_...",
147
+ max_budget_usd=10.00,
148
+ h2_max_reps=3, # block if same tool chain repeats 3 times
149
+ )
150
+
151
+ result = monitored.kickoff(inputs={"topic": "AI trends"})
152
+ ```
153
+
154
+ ---
155
+
156
+ ## Why local enforcement matters
157
+
158
+ Most observability tools record what happened. **KazenAI blocks what's about to happen.**
159
+
160
+ ```
161
+ Traditional tools: LLM call → response → log cost → dashboard shows $47K
162
+ KazenAI: Pre-flight check → BLOCKED → LLM call never made
163
+ ```
164
+
165
+ Local enforcement means:
166
+ - **No network dependency** — works with `backend_url=None`
167
+ - **No latency added** — budget check completes in <1ms
168
+ - **No backend outage = no protection failure** — the agent doesn't need to reach our servers to be protected
169
+
170
+ ---
171
+
172
+ ## Repository Structure
173
+
174
+ ```
175
+ kazenai-core/
176
+ ├── kazenai/
177
+ │ ├── __init__.py # public API: monitor()
178
+ │ ├── schema.py # canonical KazenEvent (shared SDK + backend)
179
+ │ ├── context.py # RunContext with parent_step_id
180
+ │ ├── monitor.py # monitor() entry point
181
+ │ ├── interceptor.py # LLM/tool call interception
182
+ │ ├── enforcement.py # local budget + rate limit enforcement
183
+ │ ├── loop_detector.py # H1 (Jaccard) + H2 (chain fingerprint)
184
+ │ ├── cost_tracker.py # 14-model pricing table
185
+ │ ├── client.py # async API client + sampling
186
+ │ ├── retry_queue.py # SQLite retry queue for offline resilience
187
+ │ ├── debug.py # debug=True terminal output
188
+ │ ├── config.py # pydantic-settings
189
+ │ └── integrations/
190
+ │ ├── langchain.py
191
+ │ ├── autogen.py
192
+ │ ├── crewai.py
193
+ │ └── generic.py
194
+ ├── examples/
195
+ │ ├── basic_agent.py # raw OpenAI example
196
+ │ ├── langchain_example.py
197
+ │ ├── loop_example.py # trigger loop detection
198
+ │ └── benchmark_latency.py # verify <5ms overhead
199
+ ├── tests/
200
+ ├── pyproject.toml
201
+ └── README.md
202
+ ```
203
+
204
+ ---
205
+
206
+ ## Design principles
207
+
208
+ 1. **Local-first enforcement** — SDK must block without backend
209
+ 2. **Zero-blocking** — SDK overhead <5ms on hot path
210
+ 3. **Fail-open always** — internal errors never crash your agent
211
+ 4. **Canonical schema** — KazenEvent used by both SDK and backend (`extra='forbid'`)
212
+ 5. **DX over features** — `debug=True` gives value in 2 minutes
213
+
214
+ ---
215
+
216
+ ## Star this repo ⭐
217
+
218
+ If you've ever woken up to an unexpected LLM bill, or spent hours debugging an agent that returned 200 OK but did nothing useful — **star this repo**. It tells us this matters to you, and it helps us ship faster.
219
+
220
+ We're building in public. Follow [@kazenai](https://x.com/kazenai) for weekly progress updates.
221
+
222
+ ---
223
+
224
+ ## Status
225
+
226
+ **Week 1** — Building core SDK
227
+ **Week 2** — Design partner onboarding
228
+ **Week 3** — Hosted dashboard + paid tiers
229
+ **Week 4** — Public launch
230
+
231
+ Early access: [kazenai.com](https://kazenai.com) or email **founder@kazenai.com**
232
+
233
+ ---
234
+
235
+ ## Contributing
236
+
237
+ We're pre-1.0 and moving fast. The best way to contribute right now is:
238
+
239
+ 1. ⭐ Star the repo
240
+ 2. Open an issue describing a pain point you've hit with AI agent costs or loops
241
+ 3. Try the examples and report what breaks
242
+
243
+ Full contribution guide coming with v1.0.
244
+
245
+ ---
246
+
247
+ ## License
248
+
249
+ Apache 2.0 — use it for anything, attribution appreciated.
File without changes
@@ -0,0 +1,267 @@
1
+ Metadata-Version: 2.4
2
+ Name: kazenai
3
+ Version: 0.1.0
4
+ Summary: Reliability infrastructure for AI agents: Local-first budget & loop enforcement.
5
+ Author-email: Dhavan Shah <founder@kazenai.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://kazenai.com
8
+ Project-URL: Repository, https://github.com/kazenai-ai/kazenai-core
9
+ Keywords: llm,agents,observability,finops,langchain
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: pydantic>=2.6.0
14
+ Requires-Dist: structlog>=24.1.0
15
+ Requires-Dist: aiohttp>=3.9.0
16
+ Requires-Dist: pydantic-settings>=2.1.0
17
+ Dynamic: license-file
18
+
19
+ # kazenai-core
20
+
21
+ > **Stop your AI agents from burning your budget. Catch loops before they catch you.**
22
+
23
+ [![PyPI version](https://badge.fury.io/py/kazenai-finops.svg)](https://badge.fury.io/py/kazenai-finops)
24
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
25
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
26
+ [![Status: Building in Public](https://img.shields.io/badge/status-building%20in%20public-orange.svg)](https://x.com/kazenai)
27
+
28
+ ---
29
+
30
+ ## What is KazenAI?
31
+
32
+ KazenAI is **reliability infrastructure for AI agents**.
33
+
34
+ When you run an AI agent in production, three things will eventually go wrong:
35
+
36
+ 1. **It loops** — and burns your entire monthly LLM budget in 40 minutes
37
+ 2. **It fails silently** — returns 200 OK but the business outcome is wrong
38
+ 3. **You can't debug it** — because AI agents are non-deterministic and single-trace debugging is meaningless
39
+
40
+ KazenAI intercepts every LLM and tool call your agent makes, enforces budget limits locally (no network required), detects loops before they become expensive, and gives you full observability — with one function call.
41
+
42
+ ```python
43
+ from kazenai import monitor
44
+
45
+ agent = monitor(
46
+ agent,
47
+ agent_id="support-agent",
48
+ api_key="kz_...",
49
+ max_budget_usd=5.00,
50
+ debug=True, # see cost per call in your terminal
51
+ )
52
+ ```
53
+
54
+ That's it. Your agent code doesn't change.
55
+
56
+ ---
57
+
58
+ ## The problem in one screenshot
59
+
60
+ ```
61
+ [KazenAI] step=1 gpt-4o-mini cost=$0.0043 total=$0.0043 proj=$0.21/$5.00 OK
62
+ [KazenAI] step=2 gpt-4o-mini cost=$0.0041 total=$0.0084 proj=$0.19/$5.00 OK
63
+ [KazenAI] step=8 gpt-4o-mini cost=$0.0039 total=$0.43 proj=$4.91/$5.00 WARN:budget_87pct
64
+ [KazenAI] step=9 gpt-4o-mini BLOCKED:budget spent=$5.00 limit=$5.00
65
+
66
+ KazenBudgetExceeded: Run agent-001: budget $5.00 exceeded (spent $4.97, attempted $5.42)
67
+ ```
68
+
69
+ No more waking up to a $47K bill.
70
+
71
+ ---
72
+
73
+ ## Features (MVP — shipping Week 1)
74
+
75
+ - **`monitor(agent, ...)`** — wraps LangChain, AutoGen, and CrewAI agents with one call
76
+ - **Local budget enforcement** — blocks calls before they're made, no network required, <1ms
77
+ - **Real-time debug output** — `debug=True` prints cost + status after every LLM call
78
+ - **Loop detection (H1)** — Jaccard similarity catches near-duplicate inputs before they spiral
79
+ - **Loop detection (H2)** — tool chain fingerprinting catches recursive tool patterns
80
+ - **Rate limiting** — `max_calls_per_minute` prevents runaway agents from moving too fast
81
+ - **Event sampling** — `sample_rate=0.3` to control backend traffic at scale
82
+ - **Offline resilience** — RetryQueue (SQLite) stores events locally if backend is down
83
+ - **Parent-child tracing** — `RunContext` with `parent_step_id` for multi-agent pipelines
84
+ - **Canonical event schema** — `KazenEvent` shared by SDK and backend (no field drift)
85
+ - **OpenAI patcher** — transparent monkey-patch, no code changes required
86
+ - **LangChain integration** — `KazenCallbackHandler` + `LangChainProxy`
87
+ - **AutoGen integration** — wraps `initiate_chat`
88
+ - **CrewAI integration** — wraps `kickoff()`
89
+
90
+ ## Planned Modules (Roadmap)
91
+
92
+ - **AgentLens P1** — step-level trace capture dashboard (Month 2)
93
+ - **AgentLens P2** — Probabilistic Replay Engine: run any trace N times, get statistical distribution of outcomes (Month 5) — *no competitor has built this*
94
+ - **AgentLens P3** — Semantic Drift Monitor: detect when your agent's behaviour changes after a model update (Month 6)
95
+ - **TypeScript SDK** — for Node.js agent frameworks (Month 6)
96
+
97
+ ---
98
+
99
+ ## Installation
100
+
101
+ ```bash
102
+ pip install kazenai-finops
103
+ ```
104
+
105
+ Python 3.10, 3.11, 3.12 supported. No C extensions. Installs in under 30 seconds.
106
+
107
+ ---
108
+
109
+ ## Quick Start
110
+
111
+ ### Raw OpenAI (no framework)
112
+
113
+ ```python
114
+ import openai
115
+ from kazenai import monitor, KazenBudgetExceeded
116
+
117
+ client = openai.OpenAI()
118
+
119
+ # monitor() patches the OpenAI client transparently
120
+ with_monitoring = monitor(
121
+ client,
122
+ agent_id="my-agent",
123
+ api_key="kz_...", # get yours at kazenai.com
124
+ max_budget_usd=0.50,
125
+ debug=True,
126
+ )
127
+
128
+ try:
129
+ for i in range(100): # simulated loop
130
+ response = client.chat.completions.create(
131
+ model="gpt-4o-mini",
132
+ messages=[{"role": "user", "content": f"Step {i}: do the thing"}],
133
+ )
134
+ except KazenBudgetExceeded as e:
135
+ print(f"Blocked at step {e.run_id}: spent ${e.spent:.4f}")
136
+ ```
137
+
138
+ ### LangChain
139
+
140
+ ```python
141
+ from kazenai import monitor
142
+
143
+ chain = your_langchain_chain # LCEL chain, agent, etc.
144
+ monitored = monitor(
145
+ chain,
146
+ agent_id="customer-support",
147
+ api_key="kz_...",
148
+ max_budget_usd=2.00,
149
+ debug=True,
150
+ )
151
+
152
+ result = monitored.invoke({"input": "help me with my order"})
153
+ ```
154
+
155
+ ### CrewAI
156
+
157
+ ```python
158
+ from kazenai import monitor
159
+
160
+ crew = YourCrew()
161
+ monitored = monitor(
162
+ crew,
163
+ agent_id="research-crew",
164
+ api_key="kz_...",
165
+ max_budget_usd=10.00,
166
+ h2_max_reps=3, # block if same tool chain repeats 3 times
167
+ )
168
+
169
+ result = monitored.kickoff(inputs={"topic": "AI trends"})
170
+ ```
171
+
172
+ ---
173
+
174
+ ## Why local enforcement matters
175
+
176
+ Most observability tools record what happened. **KazenAI blocks what's about to happen.**
177
+
178
+ ```
179
+ Traditional tools: LLM call → response → log cost → dashboard shows $47K
180
+ KazenAI: Pre-flight check → BLOCKED → LLM call never made
181
+ ```
182
+
183
+ Local enforcement means:
184
+ - **No network dependency** — works with `backend_url=None`
185
+ - **No latency added** — budget check completes in <1ms
186
+ - **No backend outage = no protection failure** — the agent doesn't need to reach our servers to be protected
187
+
188
+ ---
189
+
190
+ ## Repository Structure
191
+
192
+ ```
193
+ kazenai-core/
194
+ ├── kazenai/
195
+ │ ├── __init__.py # public API: monitor()
196
+ │ ├── schema.py # canonical KazenEvent (shared SDK + backend)
197
+ │ ├── context.py # RunContext with parent_step_id
198
+ │ ├── monitor.py # monitor() entry point
199
+ │ ├── interceptor.py # LLM/tool call interception
200
+ │ ├── enforcement.py # local budget + rate limit enforcement
201
+ │ ├── loop_detector.py # H1 (Jaccard) + H2 (chain fingerprint)
202
+ │ ├── cost_tracker.py # 14-model pricing table
203
+ │ ├── client.py # async API client + sampling
204
+ │ ├── retry_queue.py # SQLite retry queue for offline resilience
205
+ │ ├── debug.py # debug=True terminal output
206
+ │ ├── config.py # pydantic-settings
207
+ │ └── integrations/
208
+ │ ├── langchain.py
209
+ │ ├── autogen.py
210
+ │ ├── crewai.py
211
+ │ └── generic.py
212
+ ├── examples/
213
+ │ ├── basic_agent.py # raw OpenAI example
214
+ │ ├── langchain_example.py
215
+ │ ├── loop_example.py # trigger loop detection
216
+ │ └── benchmark_latency.py # verify <5ms overhead
217
+ ├── tests/
218
+ ├── pyproject.toml
219
+ └── README.md
220
+ ```
221
+
222
+ ---
223
+
224
+ ## Design principles
225
+
226
+ 1. **Local-first enforcement** — SDK must block without backend
227
+ 2. **Zero-blocking** — SDK overhead <5ms on hot path
228
+ 3. **Fail-open always** — internal errors never crash your agent
229
+ 4. **Canonical schema** — KazenEvent used by both SDK and backend (`extra='forbid'`)
230
+ 5. **DX over features** — `debug=True` gives value in 2 minutes
231
+
232
+ ---
233
+
234
+ ## Star this repo ⭐
235
+
236
+ If you've ever woken up to an unexpected LLM bill, or spent hours debugging an agent that returned 200 OK but did nothing useful — **star this repo**. It tells us this matters to you, and it helps us ship faster.
237
+
238
+ We're building in public. Follow [@kazenai](https://x.com/kazenai) for weekly progress updates.
239
+
240
+ ---
241
+
242
+ ## Status
243
+
244
+ **Week 1** — Building core SDK
245
+ **Week 2** — Design partner onboarding
246
+ **Week 3** — Hosted dashboard + paid tiers
247
+ **Week 4** — Public launch
248
+
249
+ Early access: [kazenai.com](https://kazenai.com) or email **founder@kazenai.com**
250
+
251
+ ---
252
+
253
+ ## Contributing
254
+
255
+ We're pre-1.0 and moving fast. The best way to contribute right now is:
256
+
257
+ 1. ⭐ Star the repo
258
+ 2. Open an issue describing a pain point you've hit with AI agent costs or loops
259
+ 3. Try the examples and report what breaks
260
+
261
+ Full contribution guide coming with v1.0.
262
+
263
+ ---
264
+
265
+ ## License
266
+
267
+ Apache 2.0 — use it for anything, attribution appreciated.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ ./kazenai/__init__.py
5
+ kazenai/__init__.py
6
+ kazenai.egg-info/PKG-INFO
7
+ kazenai.egg-info/SOURCES.txt
8
+ kazenai.egg-info/dependency_links.txt
9
+ kazenai.egg-info/requires.txt
10
+ kazenai.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ pydantic>=2.6.0
2
+ structlog>=24.1.0
3
+ aiohttp>=3.9.0
4
+ pydantic-settings>=2.1.0
@@ -0,0 +1 @@
1
+ kazenai
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kazenai" # Matches your README installation instructions
7
+ version = "0.1.0"
8
+ description = "Reliability infrastructure for AI agents: Local-first budget & loop enforcement."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10" # v4 TDD specifies 3.10+ for modern Typing/ContextVars
11
+ license = { text = "Apache-2.0" } # Explicitly state the license type here
12
+ authors = [{ name = "Dhavan Shah", email = "founder@kazenai.com" }]
13
+ keywords = ["llm", "agents", "observability", "finops", "langchain"]
14
+
15
+ dependencies = [
16
+ "pydantic>=2.6.0",
17
+ "structlog>=24.1.0",
18
+ "aiohttp>=3.9.0",
19
+ "pydantic-settings>=2.1.0", # Added: Necessary for your config.py logic
20
+ ]
21
+
22
+ [project.urls]
23
+ "Homepage" = "https://kazenai.com"
24
+ "Repository" = "https://github.com/kazenai-ai/kazenai-core"
25
+
26
+ [tool.setuptools]
27
+ # Ensure it only picks up the 'kazenai' folder, not 'tests' or 'examples'
28
+ packages = ["kazenai"]
29
+ package-dir = {"" = "."}
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+