cendor-core 0.1.12__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.
- cendor_core-0.1.12/.gitignore +19 -0
- cendor_core-0.1.12/CHANGELOG.md +93 -0
- cendor_core-0.1.12/LICENSE +201 -0
- cendor_core-0.1.12/NOTICE +7 -0
- cendor_core-0.1.12/PKG-INFO +61 -0
- cendor_core-0.1.12/README.md +41 -0
- cendor_core-0.1.12/pyproject.toml +22 -0
- cendor_core-0.1.12/src/cendor/core/__init__.py +22 -0
- cendor_core-0.1.12/src/cendor/core/bus.py +66 -0
- cendor_core-0.1.12/src/cendor/core/instrument.py +578 -0
- cendor_core-0.1.12/src/cendor/core/otel.py +81 -0
- cendor_core-0.1.12/src/cendor/core/prices.json +23 -0
- cendor_core-0.1.12/src/cendor/core/prices.py +340 -0
- cendor_core-0.1.12/src/cendor/core/protocols.py +63 -0
- cendor_core-0.1.12/src/cendor/core/py.typed +0 -0
- cendor_core-0.1.12/src/cendor/core/tokens.py +175 -0
- cendor_core-0.1.12/src/cendor/core/types.py +128 -0
- cendor_core-0.1.12/tests/test_bus.py +33 -0
- cendor_core-0.1.12/tests/test_bus_threadsafety.py +68 -0
- cendor_core-0.1.12/tests/test_core_properties.py +25 -0
- cendor_core-0.1.12/tests/test_instrument.py +152 -0
- cendor_core-0.1.12/tests/test_otel.py +9 -0
- cendor_core-0.1.12/tests/test_prices.py +246 -0
- cendor_core-0.1.12/tests/test_protocols.py +27 -0
- cendor_core-0.1.12/tests/test_providers.py +89 -0
- cendor_core-0.1.12/tests/test_reasoning.py +119 -0
- cendor_core-0.1.12/tests/test_streaming.py +153 -0
- cendor_core-0.1.12/tests/test_tokens.py +97 -0
- cendor_core-0.1.12/tests/test_tools_and_replay.py +103 -0
- cendor_core-0.1.12/tests/test_types.py +42 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
__pycache__/
|
|
2
|
+
*.py[cod]
|
|
3
|
+
*.egg-info/
|
|
4
|
+
build/
|
|
5
|
+
dist/
|
|
6
|
+
.venv/
|
|
7
|
+
.uv/
|
|
8
|
+
.ruff_cache/
|
|
9
|
+
.pytest_cache/
|
|
10
|
+
.mypy_cache/
|
|
11
|
+
.coverage
|
|
12
|
+
htmlcov/
|
|
13
|
+
.idea/
|
|
14
|
+
.vscode/
|
|
15
|
+
.DS_Store
|
|
16
|
+
*.log
|
|
17
|
+
|
|
18
|
+
# MkDocs build output (local preview only)
|
|
19
|
+
site/
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# Changelog — cendor-core
|
|
2
|
+
|
|
3
|
+
All notable changes to this package. Format: [Keep a Changelog](https://keepachangelog.com).
|
|
4
|
+
Consumers pin `cendor-core>=0.1,<0.2`, so the `0.1.x` line stays additive and backward-compatible.
|
|
5
|
+
|
|
6
|
+
## [0.1.12] — 2026-07-01
|
|
7
|
+
### Added
|
|
8
|
+
- **Reasoning-token accounting.** `Usage` gains a `reasoning_tokens` field — the portion of the output a reasoning/thinking model spent on internal reasoning. `instrument()` populates it from every adapter that reports it: OpenAI's `completion_tokens_details.reasoning_tokens` and Gemini's `thoughts_token_count` (both non-streaming and streaming). It's a **subset of** `output_tokens` (like `cached_tokens` is a subset of input), so it's a breakdown, not extra tokens — `total_tokens` and cost are unchanged (reasoning is already billed inside `output_tokens` at the output rate). Anthropic/Bedrock/Ollama fold thinking into `output_tokens` with no separate count, so `reasoning_tokens` stays `0` there. Flows automatically into `acttrace` audit records.
|
|
9
|
+
### Fixed
|
|
10
|
+
- **Gemini reasoning-model under-count.** Gemini reports `thoughts_token_count` **separately** from `candidates_token_count`, and both are billed as output. `_extract_usage` previously read only `candidates_token_count`, so thinking-model calls were under-counted (and under-costed). Thoughts are now folded into the output total and surfaced as `reasoning_tokens`. Non-thinking Gemini calls are unaffected (no `thoughts_token_count` → `0`).
|
|
11
|
+
|
|
12
|
+
All additive and backward-compatible — `reasoning_tokens` defaults to `0`, so existing `Usage(...)` construction and equality are unchanged.
|
|
13
|
+
|
|
14
|
+
## [0.1.11] — 2026-06-27
|
|
15
|
+
### Added
|
|
16
|
+
- **Live price-source adapters.** `prices.refresh(source="litellm"|"openrouter"|"azure")` pulls current rates from unauthenticated static-JSON sources — a community aggregator (LiteLLM), a gateway (OpenRouter), and the Azure Retail Prices catalog — with **no credentials, no SDKs, and no new dependencies**. The direct model labs (OpenAI/Anthropic) expose no pricing API, so those sources fill the gap. `refresh(url=…, mapper=…)` maps any other source onto our schema, and source ids are normalized to bare keys (`openai/gpt-4o` → `gpt-4o`) so refreshed rates line up with `estimate()`. Still offline-safe: static http(s) only, mapped **in memory** (nothing persisted), silent fallback to the last-good table. New `prices.sources()`, `prices.source_name()`, `prices.source_url()`.
|
|
17
|
+
- **Price staleness signal.** `prices.age_days()` and `prices.is_stale(max_age_days=30)` let callers tell when the offline snapshot is old. The bundled snapshot was expanded with more current models and re-dated.
|
|
18
|
+
- **Cost provenance labeling.** `instrument()` now prefers a provider-/gateway-reported cost when the response carries one (e.g. OpenRouter's `usage.cost`) and tags `call.metadata["cost_reported"]=True`; otherwise it prices from the snapshot and tags `call.metadata["cost_estimated"]=True` — so a real billed figure is distinguishable from an estimate (mirrors the existing `usage_estimated` flag). An unknown model with no reported cost still leaves `cost=None`.
|
|
19
|
+
- **Real streamed usage for OpenAI.** `instrument()` auto-injects `stream_options={"include_usage": True}` for OpenAI streams (unless the caller set `stream_options`), so streamed usage is the provider's real billed count instead of an offline estimate.
|
|
20
|
+
|
|
21
|
+
All additive and backward-compatible — `prices.refresh()` keeps its existing signature and offline-safe contract.
|
|
22
|
+
|
|
23
|
+
## [0.1.10] — 2026-06-25
|
|
24
|
+
### Added
|
|
25
|
+
- **Streaming responses.** `instrument()` now handles `stream=True` for sync and async clients: the chunk iterator is passed through to the caller **unchanged** while usage is accumulated, and the `LLMCall` is emitted **once when the stream completes** (or is closed early) — with usage, cost, and true end-to-end latency. Usage is read from the provider's own stream reporting where present (OpenAI's final usage chunk via `stream_options={"include_usage": True}`, Anthropic's `message_start`/`message_delta` events, Bedrock's `metadata` event, Gemini/Ollama final-chunk usage); when a provider streams no usage, it falls back to an **offline token estimate** flagged `call.metadata["usage_estimated"] = True`. Streamed calls carry `call.metadata["streamed"] = True`, with the collected chunks at `call.metadata["response"]` so `cassette` can record/replay them. Previously a streamed call returned an unconsumed iterator and emitted no usable usage/cost (so `tokenguard` saw `$0` per streamed call). Bedrock's separate `converse_stream` entrypoint is still not wrapped — use `converse`.
|
|
26
|
+
|
|
27
|
+
### Fixed
|
|
28
|
+
- **Thread-safety.** The event bus (`subscribe`/`unsubscribe`/`emit`) and the `instrument` interceptor registry (`add_interceptor`/`remove_interceptor`) are now lock-guarded, and `emit`/`_intercept` fan out over a snapshot taken under the lock then **released before** invoking subscribers — so a subscriber may safely (un)subscribe from another thread, or from inside its own callback, without corrupting the list or deadlocking. Closes a latent race when subscribers were registered/removed concurrently with dispatch.
|
|
29
|
+
|
|
30
|
+
## [0.1.9] — 2026-06-24
|
|
31
|
+
### Added
|
|
32
|
+
- `bus.unsubscribe(fn)` — the inverse of `bus.subscribe`, so a tool can register a *temporary* subscriber and tear it down cleanly (e.g. cassette's per-run recorder) instead of reaching into the internal subscriber list. Idempotent; no error if the callable isn't registered.
|
|
33
|
+
|
|
34
|
+
### Fixed
|
|
35
|
+
- `bus.emit` now runs **every** subscriber even if one raises — one tool's failure can no longer starve another (a logging subscriber's bug skipping `tokenguard`'s enforcement, or vice versa, depending on registration order). The first `Exception` is re-raised after all subscribers run, so intentional control flow (`tokenguard`'s post-flight `BudgetExceeded`/`_Truncated`) still propagates; `BaseException` (`KeyboardInterrupt`/`SystemExit`) is not caught.
|
|
36
|
+
- Price tables are parsed with `parse_float=Decimal`, so per-token rates are exact from the JSON text and never round-trip through `float` (the stack's money-is-Decimal rule). Bundled values were already float-exact; this protects high-precision refreshed tables.
|
|
37
|
+
- `prices.refresh()` fetches static JSON over **http(s) only** and rejects other URL schemes (e.g. `file://`), so it can't be pointed at a local file; still never raises and falls back to the bundled snapshot.
|
|
38
|
+
|
|
39
|
+
## [0.1.8] — 2026-06-23
|
|
40
|
+
### Changed
|
|
41
|
+
- Packaging: `LICENSE` and `NOTICE` are now bundled in the distribution (`dist-info/licenses/`), so the Apache-2.0 terms — including the §7 warranty disclaimer and §8 liability limitation — travel inside every wheel/sdist. The README footer states the "as is" / no-warranty / use-at-your-own-risk terms. No code changes.
|
|
42
|
+
|
|
43
|
+
## [0.1.7] — 2026-06-23
|
|
44
|
+
### Added
|
|
45
|
+
- `tokens.method(model)` and `tokens.is_exact(model)` report which counting path is active — `exact` (OpenAI + tiktoken), `bpe-estimate`, `registered`, or `heuristic` — so callers can surface their confidence.
|
|
46
|
+
### Changed
|
|
47
|
+
- Token counting is **accurate-first**. With the `[tiktoken]` extra installed, Claude/Gemini now use tiktoken's `o200k` BPE as a close cross-tokenizer estimate (far better than the character heuristic) rather than the offline subword fallback; OpenAI stays exact. The char/subword heuristic is now explicitly the offline-only fallback, and the docs drop the fixed "~10-15%" accuracy claim for it (a single constant can't track modern tokenizers across prose/code/JSON — install `[tiktoken]` for accuracy).
|
|
48
|
+
|
|
49
|
+
## [0.1.6] — 2026-06-23
|
|
50
|
+
### Changed
|
|
51
|
+
- Relicensed from MIT to Apache-2.0 — adds an explicit patent grant and contribution terms, a better fit for a public library suite.
|
|
52
|
+
- README links to the docs page and CHANGELOG are now absolute GitHub URLs so they resolve on PyPI (they previously broke as repo-relative paths).
|
|
53
|
+
|
|
54
|
+
## [0.1.5] — 2026-06-23
|
|
55
|
+
### Fixed
|
|
56
|
+
- Gemini: `instrument()` now reads the model id from the `GenerativeModel` (`model_name`, `models/` prefix stripped), so the emitted `LLMCall` carries a real, priceable model instead of an empty one.
|
|
57
|
+
|
|
58
|
+
## [0.1.4] — 2026-06-23
|
|
59
|
+
### Added
|
|
60
|
+
- `instrument()` adapters for AWS Bedrock (`converse`), Google Gemini (`generate_content`), and Ollama (`chat`), on top of OpenAI + Anthropic.
|
|
61
|
+
- `tokens.family` detects the `google` family and Bedrock-style prefixed ids (e.g. `anthropic.claude-…`).
|
|
62
|
+
- Bundled prices for `gemini-2.0-flash`, `gemini-1.5-pro`, and `llama3` (local, $0).
|
|
63
|
+
- `otel.ingest(attributes)` — turns OpenTelemetry `gen_ai.*` span attributes into a normalized `LLMCall` on the bus (the managed-runtime capture path).
|
|
64
|
+
|
|
65
|
+
## [0.1.3] — 2026-06-23
|
|
66
|
+
### Changed
|
|
67
|
+
- Anthropic/Gemini token counting now uses a blended char + subword-piece estimator (structure-aware; deterministic, offline). Best-effort; register a precise counter for exactness.
|
|
68
|
+
|
|
69
|
+
## [0.1.2] — 2026-06-23
|
|
70
|
+
### Added
|
|
71
|
+
- `prices.SNAPSHOT_URL` — `prices.refresh()` defaults to a hosted static snapshot, with silent fallback to the bundled table when offline.
|
|
72
|
+
|
|
73
|
+
## [0.1.1] — 2026-06-23
|
|
74
|
+
### Added
|
|
75
|
+
- `Reroute` interceptor directive (lets an interceptor rewrite the outgoing request, e.g. swap the model); request kwargs exposed on `call.metadata`.
|
|
76
|
+
|
|
77
|
+
## [0.1.0] — 2026-06-23
|
|
78
|
+
### Added
|
|
79
|
+
- Initial release: `types` (`LLMCall`, `ToolCall`, `Usage`, Decimal `Money`), provider-aware `tokens.count`, offline `prices` + `estimate`, `instrument`/`instrument_tool` (sync + async, idempotent, with record/replay hooks), in-process `bus`, minimal `otel`, and structural `protocols` (`Compressor`, `EvictionStrategy`, `Sink`, `Subscriber`, `Handle`).
|
|
80
|
+
|
|
81
|
+
[0.1.12]: https://pypi.org/project/cendor-core/0.1.12/
|
|
82
|
+
[0.1.11]: https://pypi.org/project/cendor-core/0.1.11/
|
|
83
|
+
[0.1.10]: https://pypi.org/project/cendor-core/0.1.10/
|
|
84
|
+
[0.1.9]: https://pypi.org/project/cendor-core/0.1.9/
|
|
85
|
+
[0.1.8]: https://pypi.org/project/cendor-core/0.1.8/
|
|
86
|
+
[0.1.7]: https://pypi.org/project/cendor-core/0.1.7/
|
|
87
|
+
[0.1.6]: https://pypi.org/project/cendor-core/0.1.6/
|
|
88
|
+
[0.1.5]: https://pypi.org/project/cendor-core/0.1.5/
|
|
89
|
+
[0.1.4]: https://pypi.org/project/cendor-core/0.1.4/
|
|
90
|
+
[0.1.3]: https://pypi.org/project/cendor-core/0.1.3/
|
|
91
|
+
[0.1.2]: https://pypi.org/project/cendor-core/0.1.2/
|
|
92
|
+
[0.1.1]: https://pypi.org/project/cendor-core/0.1.1/
|
|
93
|
+
[0.1.0]: https://pypi.org/project/cendor-core/0.1.0/
|
|
@@ -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.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cendor-core
|
|
3
|
+
Version: 0.1.12
|
|
4
|
+
Summary: Foundation for the PowerAI Labs stack: shared types, token counting, offline-first & refreshable prices, instrument(), event bus, OTel.
|
|
5
|
+
Author: Raghav Mishra
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
License-File: NOTICE
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Provides-Extra: anthropic
|
|
11
|
+
Requires-Dist: anthropic>=0.30; extra == 'anthropic'
|
|
12
|
+
Provides-Extra: openai
|
|
13
|
+
Requires-Dist: openai>=1.0; extra == 'openai'
|
|
14
|
+
Provides-Extra: otel
|
|
15
|
+
Requires-Dist: opentelemetry-api>=1.25; extra == 'otel'
|
|
16
|
+
Requires-Dist: opentelemetry-sdk>=1.25; extra == 'otel'
|
|
17
|
+
Provides-Extra: tiktoken
|
|
18
|
+
Requires-Dist: tiktoken>=0.7; extra == 'tiktoken'
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# cendor-core
|
|
22
|
+
|
|
23
|
+
The shared foundation for the Cendor stack: canonical types, provider-aware token counting,
|
|
24
|
+
an offline price table, one `instrument()` interception point, an in-process event bus, and
|
|
25
|
+
OpenTelemetry GenAI emitters. Tiny on purpose — it's the blast radius for every other tool.
|
|
26
|
+
|
|
27
|
+
**One `instrument()` call, every sibling tool observes the stream — no per-call wiring, offline by default.**
|
|
28
|
+
|
|
29
|
+
  · usually installed transitively · `import cendor.core`
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from cendor.core import tokens, prices, instrument, bus
|
|
33
|
+
|
|
34
|
+
# Count tokens and price a call — fully offline, no API key, no network:
|
|
35
|
+
n = tokens.count([{"role": "user", "content": "Summarize the attached report in 3 bullets."}],
|
|
36
|
+
model="claude-opus-4-8")
|
|
37
|
+
cost = prices.estimate("claude-opus-4-8", input_tokens=n, output_tokens=200)
|
|
38
|
+
|
|
39
|
+
# Instrument any client once; tools subscribe to the normalized event stream:
|
|
40
|
+
@bus.subscribe
|
|
41
|
+
def on_call(call): # normalized LLMCall with usage + cost
|
|
42
|
+
print(call.provider, call.model, call.cost)
|
|
43
|
+
|
|
44
|
+
client = instrument(openai_or_anthropic_client) # idempotent, additive · sync · async · streaming
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Highlights
|
|
48
|
+
|
|
49
|
+
- **`instrument()`** — wrap any client once: **OpenAI · Anthropic · AWS Bedrock · Google Gemini · Ollama**, detected by *shape*; sync, async, **and streaming**; idempotent + additive. `instrument_tool()` does the same for tools.
|
|
50
|
+
- **Event bus** — `subscribe` / `emit`; **thread-safe within a process**; one failing subscriber never starves another.
|
|
51
|
+
- **Interceptor seam** — `add_interceptor` + `Reroute` / `MISS` powers replay (cassette) and reroute / block (tokenguard) **without a second patch point**.
|
|
52
|
+
- **Token counting, three tiers** — exact (`[tiktoken]`) / BPE-estimate (o200k for Claude/Gemini) / offline heuristic; `tokens.method(model)` reports which is active; `tokens.register()` plugs in a precise counter.
|
|
53
|
+
- **Reasoning-token accounting** — `Usage.reasoning_tokens` breaks out a reasoning/thinking model's internal reasoning (OpenAI `reasoning_tokens`, Gemini `thoughts_token_count`), non-streaming and streaming. A subset of `output_tokens`, so cost is unchanged; Gemini's separately-reported thoughts are now folded into the output total (fixing an under-count).
|
|
54
|
+
- **Offline-first, refreshable prices** — bundled dated snapshot; `estimate() -> Decimal Money` (never `float`); optional `refresh(source="litellm"|"openrouter"|"azure")` from live no-auth sources, with `age_days()`/`is_stale()` staleness signals. A gateway-reported cost (e.g. OpenRouter's `usage.cost`) is preferred over the estimate and labeled `cost_reported` vs `cost_estimated`.
|
|
55
|
+
- **OpenTelemetry** — emit `gen_ai.*` spans, or `otel.ingest()` a managed runtime's spans onto the bus. Structural protocols (`Compressor` / `EvictionStrategy` / `Sink` / `Subscriber` / `Handle`) let the tools interlock without coupling.
|
|
56
|
+
|
|
57
|
+
Install `cendor-core[tiktoken]` for **exact** OpenAI counts (heuristic fallback otherwise), or `[otel]` to emit spans. Provider SDKs are always optional extras.
|
|
58
|
+
|
|
59
|
+
A rendered architecture diagram lives in [`docs/core.md`](https://github.com/PowerAI-Labs/Cendor/blob/main/docs/core.md) (GitHub renders Mermaid; PyPI shows code as text).
|
|
60
|
+
|
|
61
|
+
See [`docs/core.md`](https://github.com/PowerAI-Labs/Cendor/blob/main/docs/core.md) · [CHANGELOG](https://github.com/PowerAI-Labs/Cendor/blob/main/packages/cendor-core/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,41 @@
|
|
|
1
|
+
# cendor-core
|
|
2
|
+
|
|
3
|
+
The shared foundation for the Cendor stack: canonical types, provider-aware token counting,
|
|
4
|
+
an offline price table, one `instrument()` interception point, an in-process event bus, and
|
|
5
|
+
OpenTelemetry GenAI emitters. Tiny on purpose — it's the blast radius for every other tool.
|
|
6
|
+
|
|
7
|
+
**One `instrument()` call, every sibling tool observes the stream — no per-call wiring, offline by default.**
|
|
8
|
+
|
|
9
|
+
  · usually installed transitively · `import cendor.core`
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from cendor.core import tokens, prices, instrument, bus
|
|
13
|
+
|
|
14
|
+
# Count tokens and price a call — fully offline, no API key, no network:
|
|
15
|
+
n = tokens.count([{"role": "user", "content": "Summarize the attached report in 3 bullets."}],
|
|
16
|
+
model="claude-opus-4-8")
|
|
17
|
+
cost = prices.estimate("claude-opus-4-8", input_tokens=n, output_tokens=200)
|
|
18
|
+
|
|
19
|
+
# Instrument any client once; tools subscribe to the normalized event stream:
|
|
20
|
+
@bus.subscribe
|
|
21
|
+
def on_call(call): # normalized LLMCall with usage + cost
|
|
22
|
+
print(call.provider, call.model, call.cost)
|
|
23
|
+
|
|
24
|
+
client = instrument(openai_or_anthropic_client) # idempotent, additive · sync · async · streaming
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Highlights
|
|
28
|
+
|
|
29
|
+
- **`instrument()`** — wrap any client once: **OpenAI · Anthropic · AWS Bedrock · Google Gemini · Ollama**, detected by *shape*; sync, async, **and streaming**; idempotent + additive. `instrument_tool()` does the same for tools.
|
|
30
|
+
- **Event bus** — `subscribe` / `emit`; **thread-safe within a process**; one failing subscriber never starves another.
|
|
31
|
+
- **Interceptor seam** — `add_interceptor` + `Reroute` / `MISS` powers replay (cassette) and reroute / block (tokenguard) **without a second patch point**.
|
|
32
|
+
- **Token counting, three tiers** — exact (`[tiktoken]`) / BPE-estimate (o200k for Claude/Gemini) / offline heuristic; `tokens.method(model)` reports which is active; `tokens.register()` plugs in a precise counter.
|
|
33
|
+
- **Reasoning-token accounting** — `Usage.reasoning_tokens` breaks out a reasoning/thinking model's internal reasoning (OpenAI `reasoning_tokens`, Gemini `thoughts_token_count`), non-streaming and streaming. A subset of `output_tokens`, so cost is unchanged; Gemini's separately-reported thoughts are now folded into the output total (fixing an under-count).
|
|
34
|
+
- **Offline-first, refreshable prices** — bundled dated snapshot; `estimate() -> Decimal Money` (never `float`); optional `refresh(source="litellm"|"openrouter"|"azure")` from live no-auth sources, with `age_days()`/`is_stale()` staleness signals. A gateway-reported cost (e.g. OpenRouter's `usage.cost`) is preferred over the estimate and labeled `cost_reported` vs `cost_estimated`.
|
|
35
|
+
- **OpenTelemetry** — emit `gen_ai.*` spans, or `otel.ingest()` a managed runtime's spans onto the bus. Structural protocols (`Compressor` / `EvictionStrategy` / `Sink` / `Subscriber` / `Handle`) let the tools interlock without coupling.
|
|
36
|
+
|
|
37
|
+
Install `cendor-core[tiktoken]` for **exact** OpenAI counts (heuristic fallback otherwise), or `[otel]` to emit spans. Provider SDKs are always optional extras.
|
|
38
|
+
|
|
39
|
+
A rendered architecture diagram lives in [`docs/core.md`](https://github.com/PowerAI-Labs/Cendor/blob/main/docs/core.md) (GitHub renders Mermaid; PyPI shows code as text).
|
|
40
|
+
|
|
41
|
+
See [`docs/core.md`](https://github.com/PowerAI-Labs/Cendor/blob/main/docs/core.md) · [CHANGELOG](https://github.com/PowerAI-Labs/Cendor/blob/main/packages/cendor-core/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,22 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "cendor-core"
|
|
3
|
+
version = "0.1.12"
|
|
4
|
+
description = "Foundation for the PowerAI Labs stack: shared types, token counting, offline-first & refreshable prices, instrument(), event bus, OTel."
|
|
5
|
+
requires-python = ">=3.11"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
authors = [{ name = "Raghav Mishra" }]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
dependencies = []
|
|
10
|
+
|
|
11
|
+
[project.optional-dependencies]
|
|
12
|
+
openai = ["openai>=1.0"]
|
|
13
|
+
anthropic = ["anthropic>=0.30"]
|
|
14
|
+
otel = ["opentelemetry-api>=1.25", "opentelemetry-sdk>=1.25"]
|
|
15
|
+
tiktoken = ["tiktoken>=0.7"] # optional: exact OpenAI token counts (heuristic fallback otherwise)
|
|
16
|
+
|
|
17
|
+
[build-system]
|
|
18
|
+
requires = ["hatchling"]
|
|
19
|
+
build-backend = "hatchling.build"
|
|
20
|
+
|
|
21
|
+
[tool.hatch.build.targets.wheel]
|
|
22
|
+
packages = ["src/cendor"] # contributes cendor/core only — NEVER add src/cendor/__init__.py
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""cendor.core — the shared foundation. Keep this public surface small and stable."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from . import bus, otel, prices, protocols, tokens
|
|
6
|
+
from .instrument import Reroute, instrument, instrument_tool
|
|
7
|
+
from .types import LLMCall, Money, ToolCall, Usage
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"LLMCall",
|
|
11
|
+
"ToolCall",
|
|
12
|
+
"Usage",
|
|
13
|
+
"Money",
|
|
14
|
+
"bus",
|
|
15
|
+
"tokens",
|
|
16
|
+
"prices",
|
|
17
|
+
"otel",
|
|
18
|
+
"protocols",
|
|
19
|
+
"instrument",
|
|
20
|
+
"instrument_tool",
|
|
21
|
+
"Reroute",
|
|
22
|
+
]
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""In-process pub/sub event bus: one instrument() emits, many tools subscribe. docs/core.md §6.
|
|
2
|
+
|
|
3
|
+
Thread-safe within a process: the subscriber list is guarded by a lock for registration changes,
|
|
4
|
+
and :func:`emit` fans out over a snapshot taken under that lock — so subscribers may (un)subscribe
|
|
5
|
+
from other threads (or from inside a callback) without corrupting the list or deadlocking.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import threading
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
_subscribers: list[Callable[[Any], None]] = []
|
|
15
|
+
_lock = threading.Lock()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def subscribe(fn: Callable[[Any], None]) -> Callable[[Any], None]:
|
|
19
|
+
"""Register a subscriber. Usable as a decorator. Idempotent: re-registering the
|
|
20
|
+
same callable is a no-op, so a sibling tool can safely ensure its subscription."""
|
|
21
|
+
with _lock:
|
|
22
|
+
if fn not in _subscribers:
|
|
23
|
+
_subscribers.append(fn)
|
|
24
|
+
return fn
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def unsubscribe(fn: Callable[[Any], None]) -> None:
|
|
28
|
+
"""Remove a subscriber (no error if absent) — the inverse of :func:`subscribe`.
|
|
29
|
+
|
|
30
|
+
Lets a tool register a *temporary* subscriber (e.g. cassette's recorder) and tear it down
|
|
31
|
+
cleanly, without reaching into the internal subscriber list."""
|
|
32
|
+
with _lock:
|
|
33
|
+
if fn in _subscribers:
|
|
34
|
+
_subscribers.remove(fn)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def emit(event: Any) -> None:
|
|
38
|
+
"""Publish an event to every subscriber (synchronous).
|
|
39
|
+
|
|
40
|
+
Every subscriber runs even if an earlier one raises, so one tool's failure can't starve
|
|
41
|
+
another (a logging subscriber's bug must not skip ``tokenguard``'s enforcement, or vice versa).
|
|
42
|
+
The first ``Exception`` raised is re-raised after all subscribers have run, so intentional
|
|
43
|
+
control flow (e.g. ``tokenguard``'s post-flight ``BudgetExceeded``) still reaches the caller.
|
|
44
|
+
``BaseException`` (``KeyboardInterrupt``/``SystemExit``) is not caught — it propagates at once.
|
|
45
|
+
|
|
46
|
+
The fan-out runs over a snapshot taken under the lock, then *releases* it before invoking any
|
|
47
|
+
subscriber — so a subscriber is free to (un)subscribe without deadlocking, and a slow one never
|
|
48
|
+
blocks registration on another thread.
|
|
49
|
+
"""
|
|
50
|
+
with _lock:
|
|
51
|
+
subscribers = list(_subscribers)
|
|
52
|
+
first_exc: Exception | None = None
|
|
53
|
+
for fn in subscribers:
|
|
54
|
+
try:
|
|
55
|
+
fn(event)
|
|
56
|
+
except Exception as exc: # noqa: BLE001 - isolate subscribers, re-raise first after all run
|
|
57
|
+
if first_exc is None:
|
|
58
|
+
first_exc = exc
|
|
59
|
+
if first_exc is not None:
|
|
60
|
+
raise first_exc
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _reset() -> None:
|
|
64
|
+
"""Test helper: clear all subscribers."""
|
|
65
|
+
with _lock:
|
|
66
|
+
_subscribers.clear()
|