cogno-meter 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.
@@ -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 Sudoers AI
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,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: cogno-meter
3
+ Version: 0.1.0
4
+ Summary: Usage metering + pricing/overage for the Cogno cognitive pipeline — cross-modality (LLM/embedding tokens + STT/TTS chars) billable-token accounting against a plan allowance
5
+ Author: Vinicius Vale
6
+ Maintainer: Sudoers AI
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/sudoers-ai/cogno-meter
9
+ Project-URL: Repository, https://github.com/sudoers-ai/cogno-meter
10
+ Project-URL: Issues, https://github.com/sudoers-ai/cogno-meter/issues
11
+ Keywords: metering,billing,pricing,tokens,usage,llm,overage,agents
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Office/Business :: Financial
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=8.0; extra == "dev"
27
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
28
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
29
+ Requires-Dist: ruff>=0.5; extra == "dev"
30
+ Requires-Dist: mypy>=1.8; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # cogno-meter
34
+
35
+ **Usage metering + pricing/overage for the [Cogno](https://github.com/sudoers-ai/cogno-anima) cognitive pipeline** — cross-modality billable-token accounting against a plan allowance.
36
+
37
+ `cogno-meter` turns raw usage (LLM/embedding **tokens** + STT/TTS **characters**) into a bill. Pure code, zero dependencies, zero I/O — the host owns the plan values, the price book values, the accumulated-usage persistence, and invoicing. Adapted clean-room from the parent Cogno SaaS's `pricing` / `metering` / `db_billing`.
38
+
39
+ > Status: **alpha** — the pricing + overage core and the unit suite are in place.
40
+
41
+ ## The billing model
42
+
43
+ - **Everything counts as billable tokens.** A **local** model costs nothing to run, but its tokens still draw down the monthly allowance.
44
+ - **Audio is char-metered, with a multiplier.** STT/TTS usage is measured in characters and multiplied (default `2×`) so audio is more expensive per the allowance.
45
+ - **Overage is per-plan, not per-model.** Beyond the monthly allowance, the customer is charged the **plan's** rate per million tokens — cheap, because the platform runs local models. **BYOK is not exempt**: over the limit you pay the override even with your own API key.
46
+ - **Provider cost is transparency only.** The real upstream cost (per-model price book) is computed alongside so the client can track external-LLM spend; for external models under BYOK the client pays the provider directly. It is **not** the platform charge.
47
+
48
+ ## Use
49
+
50
+ ```python
51
+ from cogno_meter import meter, Plan, PriceBook, UsageRecord, Modality
52
+
53
+ plan = Plan(name="Básico", monthly_token_limit=500_000, overage_price=0.05, base_price=20.0)
54
+ book = PriceBook.default() # or PriceBook.from_mapping(host_pricing_dict)
55
+
56
+ records = [ # a period's usage (from synapse + vox)
57
+ UsageRecord(Modality.LLM, "ollama:mistral:latest", tokens_in=1_000_000, tokens_out=200_000),
58
+ UsageRecord(Modality.TTS, "local:kokoro", chars=50_000), # 50k × 2 = 100k billable tokens
59
+ ]
60
+
61
+ bill = meter(records, plan=plan, book=book)
62
+ # bill.total_tokens=1_300_000 overage_tokens=800_000 overage_cost=0.04
63
+ # bill.total=20.04 provider_cost_brl=0.0 (all local → free upstream)
64
+ ```
65
+
66
+ External, paid model (transparency cost appears, charge stays plan-based):
67
+
68
+ ```python
69
+ records = [UsageRecord(Modality.LLM, "openai:gpt-4.1-mini", tokens_in=1_000_000, tokens_out=500_000)]
70
+ bill = meter(records, plan=plan, book=book)
71
+ # overage_cost=0.05 total=20.05 (platform charge — plan rate)
72
+ # provider_cost_usd=1.20 provider_cost_brl=6.84 (transparency — client pays OpenAI via BYOK)
73
+ ```
74
+
75
+ ## The price book
76
+
77
+ `PriceBook` resolves a model's rate by exact match → fuzzy version-prefix → provider `_default` (self-hosted = 0), and converts USD→currency. The lib ships an **illustrative** seed (`DEFAULT_RATES`); a host injects its own via `PriceBook.from_mapping(...)` (load your YAML/JSON/DB and pass a plain mapping — no YAML dependency here). Units: LLM/embedding USD per 1M tokens, STT USD per minute, TTS USD per 1M characters.
78
+
79
+ ## Boundary
80
+
81
+ | Concern | Owner |
82
+ | --- | --- |
83
+ | Price book resolution, per-modality cost, audio char×multiplier, overage math | **cogno-meter** |
84
+ | Plan/allowance/overage-price values, price book values | **host** |
85
+ | Accumulated-usage persistence (the token ledger), invoicing, Stripe | **host** |
86
+ | Per-tenant model overrides, BYOK key storage | **host** |
87
+
88
+ `meter` consumes usage produced by `cogno-synapse` (tokens) and `cogno-vox` (audio chars); it never imports them — usage is handed in as plain `UsageRecord`s.
89
+
90
+ ## The Cogno ecosystem
91
+
92
+ `cogno-meter` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
93
+ small, composable, Apache-2.0 libraries that together form a complete
94
+ conversational-agent platform. Each library owns a single concern and stays
95
+ infra-agnostic; a **host** assembles them into a running agent:
96
+
97
+ ![The Cogno ecosystem](docs/assets/cogno-ecosystem.svg)
98
+
99
+ The open-source libraries are the organs; the **host is the body** that joins
100
+ them. Our reference host — `cogno-host`, with its `cogno-ui` dashboard — is the
101
+ private product layer, but it holds no special powers: everything it does rides
102
+ on the public seams documented in each library's `docs/HOST_INTEGRATION.md`, so
103
+ you can assemble a body of your own.
104
+
105
+ ## Test
106
+
107
+ ```bash
108
+ pip install -e ".[dev]"
109
+ pytest tests/unit -q
110
+ ```
@@ -0,0 +1,78 @@
1
+ # cogno-meter
2
+
3
+ **Usage metering + pricing/overage for the [Cogno](https://github.com/sudoers-ai/cogno-anima) cognitive pipeline** — cross-modality billable-token accounting against a plan allowance.
4
+
5
+ `cogno-meter` turns raw usage (LLM/embedding **tokens** + STT/TTS **characters**) into a bill. Pure code, zero dependencies, zero I/O — the host owns the plan values, the price book values, the accumulated-usage persistence, and invoicing. Adapted clean-room from the parent Cogno SaaS's `pricing` / `metering` / `db_billing`.
6
+
7
+ > Status: **alpha** — the pricing + overage core and the unit suite are in place.
8
+
9
+ ## The billing model
10
+
11
+ - **Everything counts as billable tokens.** A **local** model costs nothing to run, but its tokens still draw down the monthly allowance.
12
+ - **Audio is char-metered, with a multiplier.** STT/TTS usage is measured in characters and multiplied (default `2×`) so audio is more expensive per the allowance.
13
+ - **Overage is per-plan, not per-model.** Beyond the monthly allowance, the customer is charged the **plan's** rate per million tokens — cheap, because the platform runs local models. **BYOK is not exempt**: over the limit you pay the override even with your own API key.
14
+ - **Provider cost is transparency only.** The real upstream cost (per-model price book) is computed alongside so the client can track external-LLM spend; for external models under BYOK the client pays the provider directly. It is **not** the platform charge.
15
+
16
+ ## Use
17
+
18
+ ```python
19
+ from cogno_meter import meter, Plan, PriceBook, UsageRecord, Modality
20
+
21
+ plan = Plan(name="Básico", monthly_token_limit=500_000, overage_price=0.05, base_price=20.0)
22
+ book = PriceBook.default() # or PriceBook.from_mapping(host_pricing_dict)
23
+
24
+ records = [ # a period's usage (from synapse + vox)
25
+ UsageRecord(Modality.LLM, "ollama:mistral:latest", tokens_in=1_000_000, tokens_out=200_000),
26
+ UsageRecord(Modality.TTS, "local:kokoro", chars=50_000), # 50k × 2 = 100k billable tokens
27
+ ]
28
+
29
+ bill = meter(records, plan=plan, book=book)
30
+ # bill.total_tokens=1_300_000 overage_tokens=800_000 overage_cost=0.04
31
+ # bill.total=20.04 provider_cost_brl=0.0 (all local → free upstream)
32
+ ```
33
+
34
+ External, paid model (transparency cost appears, charge stays plan-based):
35
+
36
+ ```python
37
+ records = [UsageRecord(Modality.LLM, "openai:gpt-4.1-mini", tokens_in=1_000_000, tokens_out=500_000)]
38
+ bill = meter(records, plan=plan, book=book)
39
+ # overage_cost=0.05 total=20.05 (platform charge — plan rate)
40
+ # provider_cost_usd=1.20 provider_cost_brl=6.84 (transparency — client pays OpenAI via BYOK)
41
+ ```
42
+
43
+ ## The price book
44
+
45
+ `PriceBook` resolves a model's rate by exact match → fuzzy version-prefix → provider `_default` (self-hosted = 0), and converts USD→currency. The lib ships an **illustrative** seed (`DEFAULT_RATES`); a host injects its own via `PriceBook.from_mapping(...)` (load your YAML/JSON/DB and pass a plain mapping — no YAML dependency here). Units: LLM/embedding USD per 1M tokens, STT USD per minute, TTS USD per 1M characters.
46
+
47
+ ## Boundary
48
+
49
+ | Concern | Owner |
50
+ | --- | --- |
51
+ | Price book resolution, per-modality cost, audio char×multiplier, overage math | **cogno-meter** |
52
+ | Plan/allowance/overage-price values, price book values | **host** |
53
+ | Accumulated-usage persistence (the token ledger), invoicing, Stripe | **host** |
54
+ | Per-tenant model overrides, BYOK key storage | **host** |
55
+
56
+ `meter` consumes usage produced by `cogno-synapse` (tokens) and `cogno-vox` (audio chars); it never imports them — usage is handed in as plain `UsageRecord`s.
57
+
58
+ ## The Cogno ecosystem
59
+
60
+ `cogno-meter` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
61
+ small, composable, Apache-2.0 libraries that together form a complete
62
+ conversational-agent platform. Each library owns a single concern and stays
63
+ infra-agnostic; a **host** assembles them into a running agent:
64
+
65
+ ![The Cogno ecosystem](docs/assets/cogno-ecosystem.svg)
66
+
67
+ The open-source libraries are the organs; the **host is the body** that joins
68
+ them. Our reference host — `cogno-host`, with its `cogno-ui` dashboard — is the
69
+ private product layer, but it holds no special powers: everything it does rides
70
+ on the public seams documented in each library's `docs/HOST_INTEGRATION.md`, so
71
+ you can assemble a body of your own.
72
+
73
+ ## Test
74
+
75
+ ```bash
76
+ pip install -e ".[dev]"
77
+ pytest tests/unit -q
78
+ ```
@@ -0,0 +1,66 @@
1
+ """
2
+ cogno-meter — usage metering + pricing/overage for the Cogno stack.
3
+
4
+ Cross-modality usage (LLM/embedding tokens + STT/TTS characters) is normalized to
5
+ **billable tokens** and billed against a plan: a monthly token allowance plus a
6
+ per-million **overage** at the plan's rate. Local models cost nothing to run but
7
+ still consume the allowance; audio is char-metered with a multiplier so it costs
8
+ more. The real upstream **provider cost** is computed alongside, as transparency
9
+ only (with BYOK the client pays the provider directly).
10
+
11
+ Pure code, zero dependencies, zero I/O: the host owns the plan values, the price
12
+ book values, the accumulated-usage persistence, and invoicing. Adapted from the
13
+ parent cogno's pricing/metering/billing.
14
+ """
15
+
16
+ from importlib.metadata import PackageNotFoundError
17
+ from importlib.metadata import version as _dist_version
18
+
19
+ try:
20
+ __version__ = _dist_version("cogno-meter")
21
+ except PackageNotFoundError: # source tree without an installed dist (e.g. vendored checkout)
22
+ __version__ = "0.0.0"
23
+
24
+
25
+ from cogno_meter.types import Bill, Modality, Plan, UsageRecord
26
+ from cogno_meter.pricing import (
27
+ DEFAULT_AUDIO_MULTIPLIER,
28
+ DEFAULT_RATES,
29
+ DEFAULT_USD_BRL_RATE,
30
+ PriceBook,
31
+ )
32
+ from cogno_meter.billing import (
33
+ compute_bill,
34
+ meter,
35
+ total_billable_tokens,
36
+ total_provider_cost_usd,
37
+ )
38
+ from cogno_meter.budget import (
39
+ BLOCKING_STATUSES,
40
+ WARN_THRESHOLD,
41
+ BudgetInputs,
42
+ BudgetReason,
43
+ BudgetVerdict,
44
+ evaluate_budget,
45
+ )
46
+
47
+ __all__ = [
48
+ "Modality",
49
+ "UsageRecord",
50
+ "Plan",
51
+ "Bill",
52
+ "PriceBook",
53
+ "DEFAULT_RATES",
54
+ "DEFAULT_USD_BRL_RATE",
55
+ "DEFAULT_AUDIO_MULTIPLIER",
56
+ "meter",
57
+ "compute_bill",
58
+ "total_billable_tokens",
59
+ "total_provider_cost_usd",
60
+ "evaluate_budget",
61
+ "BudgetInputs",
62
+ "BudgetVerdict",
63
+ "BudgetReason",
64
+ "BLOCKING_STATUSES",
65
+ "WARN_THRESHOLD",
66
+ ]
@@ -0,0 +1,71 @@
1
+ """
2
+ cogno_meter.billing — aggregate usage and compute the bill.
3
+
4
+ The overage math is ported from the parent ``cogno/core/db_billing.py`` (the
5
+ pure calculation, not the DB/Stripe layer): everything counts toward the monthly
6
+ token total (local models included, at zero provider cost); the customer is
7
+ charged the **plan's** per-million ``overage_price`` on tokens beyond the
8
+ allowance — independent of whose API key ran the model (BYOK is not exempt).
9
+
10
+ The provider cost (price book) is aggregated alongside, purely as transparency.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ from typing import Iterable
17
+
18
+ from cogno_meter.pricing import PriceBook
19
+ from cogno_meter.types import Bill, Plan, UsageRecord
20
+
21
+ # Pure functions — DEBUG-only (the caller logs the returned Bill; the
22
+ # budget-block decision belongs to the host). See LOGGING.md.
23
+ logger = logging.getLogger("cogno_meter.billing")
24
+
25
+
26
+ def total_billable_tokens(records: Iterable[UsageRecord], book: PriceBook) -> int:
27
+ return sum(book.billable_tokens(r) for r in records)
28
+
29
+
30
+ def total_provider_cost_usd(records: Iterable[UsageRecord], book: PriceBook) -> float:
31
+ return sum(book.usage_cost_usd(r) for r in records)
32
+
33
+
34
+ def compute_bill(
35
+ *,
36
+ plan: Plan,
37
+ billable_tokens: int,
38
+ provider_cost_usd: float,
39
+ book: PriceBook,
40
+ ) -> Bill:
41
+ """Apply the plan's allowance + per-million overage to a period's totals."""
42
+ overage_tokens = max(0, billable_tokens - plan.monthly_token_limit)
43
+ overage_cost = (overage_tokens / 1_000_000) * plan.overage_price
44
+ total = plan.base_price + overage_cost
45
+ logger.debug(
46
+ "event=compute_bill total_tokens=%d allowance=%d overage_tokens=%d "
47
+ "overage_cost=%.6f total=%.6f provider_cost_usd=%.6f",
48
+ billable_tokens, plan.monthly_token_limit, overage_tokens,
49
+ overage_cost, total, provider_cost_usd,
50
+ )
51
+ return Bill(
52
+ total_tokens=billable_tokens,
53
+ allowance=plan.monthly_token_limit,
54
+ overage_tokens=overage_tokens,
55
+ overage_cost=round(overage_cost, 6),
56
+ base_price=plan.base_price,
57
+ total=round(total, 6),
58
+ provider_cost_usd=round(provider_cost_usd, 6),
59
+ provider_cost_brl=round(provider_cost_usd * book.usd_brl_rate, 6),
60
+ )
61
+
62
+
63
+ def meter(records: Iterable[UsageRecord], *, plan: Plan, book: PriceBook) -> Bill:
64
+ """End-to-end: aggregate a period's usage records into a :class:`Bill`."""
65
+ records = list(records)
66
+ return compute_bill(
67
+ plan=plan,
68
+ billable_tokens=total_billable_tokens(records, book),
69
+ provider_cost_usd=total_provider_cost_usd(records, book),
70
+ book=book,
71
+ )
@@ -0,0 +1,106 @@
1
+ """Budget/quota decision — the pure gate the host wires to its stores.
2
+
3
+ The parent's ``BudgetGuard`` (``cogno/core/budget_guard.py``) mixed store I/O, currency, dates and
4
+ pt-BR messages into one class. Here the **decision** is extracted as pure policy: the host fetches
5
+ the numbers (daily spend, monthly usage, subscription state), converts them to the plan currency,
6
+ parses expiry, and passes them in; this module applies the layered budget policy and returns a
7
+ :class:`BudgetVerdict`. Zero I/O, no dates, no FX, no locale — a blocked verdict names the
8
+ :class:`BudgetReason`, and the host renders the localized message.
9
+
10
+ Layers (order): tenant daily budget → identity daily budget → subscription status/expiry →
11
+ monthly token quota (hard-stop ONLY when the plan has no overage). Each daily layer warns at 80%.
12
+ A budget of ``None`` / ``<= 0`` is *unset* (no limit) — never blocks. Never raises.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass, field
18
+ from enum import Enum
19
+ from typing import List, Optional
20
+
21
+ # Subscription states that block a turn (an active or unset/"inactive" free plan runs). The host
22
+ # may override via ``BudgetInputs.blocking_statuses``.
23
+ BLOCKING_STATUSES: "frozenset[str]" = frozenset({"canceled", "past_due", "suspended"})
24
+ # Soft-warning threshold (fraction of a budget/quota that raises a warning, not a block).
25
+ WARN_THRESHOLD = 0.8
26
+
27
+
28
+ class BudgetReason(str, Enum):
29
+ """Why a turn was blocked — the host maps this to a localized user message."""
30
+
31
+ TENANT_DAILY = "tenant_daily_budget"
32
+ IDENTITY_DAILY = "identity_daily_budget"
33
+ SUBSCRIPTION_INACTIVE = "subscription_inactive"
34
+ SUBSCRIPTION_EXPIRED = "subscription_expired"
35
+ MONTHLY_TOKENS = "monthly_tokens"
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class BudgetInputs:
40
+ """Everything pre-fetched + normalized by the host. Spends are in the SAME unit as the budgets
41
+ (the host applies any FX before building this); ``subscription_expired`` is pre-computed (the
42
+ host parses the date). A ``None``/non-positive budget or a 0 monthly limit means *unset*."""
43
+
44
+ tenant_daily_budget: Optional[float] = None
45
+ tenant_daily_spend: float = 0.0
46
+ identity_daily_budget: Optional[float] = None
47
+ identity_daily_spend: float = 0.0
48
+ subscription_status: Optional[str] = None # None → no subscription (skip the layer)
49
+ subscription_expired: bool = False
50
+ monthly_token_limit: int = 0
51
+ monthly_tokens_used: int = 0
52
+ overage_price: float = 0.0 # >0 → paid plan keeps running over the limit
53
+ plan_limits: dict = field(default_factory=dict) # loop-depth caps to pass through
54
+ call_limit: Optional[float] = None # per-call ceiling to pass through
55
+ blocking_statuses: "frozenset[str]" = BLOCKING_STATUSES
56
+
57
+
58
+ @dataclass
59
+ class BudgetVerdict:
60
+ """The decision. ``plan_limits``/``call_limit`` pass through for the host to apply on an
61
+ allowed turn; ``warnings`` carries 80%-threshold notices (``"<reason>:80pct"``)."""
62
+
63
+ blocked: bool = False
64
+ reason: Optional[BudgetReason] = None
65
+ plan_limits: dict = field(default_factory=dict)
66
+ call_limit: Optional[float] = None
67
+ warnings: List[str] = field(default_factory=list)
68
+
69
+
70
+ def evaluate_budget(inp: BudgetInputs) -> BudgetVerdict:
71
+ """Apply the layered budget policy → a :class:`BudgetVerdict`. Currency/locale/time-agnostic."""
72
+ warnings: List[str] = []
73
+
74
+ def _block(reason: BudgetReason) -> BudgetVerdict:
75
+ return BudgetVerdict(blocked=True, reason=reason, plan_limits=inp.plan_limits,
76
+ call_limit=inp.call_limit, warnings=warnings)
77
+
78
+ # 1) tenant daily budget, then 2) identity daily budget — block at 100%, warn at 80%.
79
+ for budget, spend, reason in (
80
+ (inp.tenant_daily_budget, inp.tenant_daily_spend, BudgetReason.TENANT_DAILY),
81
+ (inp.identity_daily_budget, inp.identity_daily_spend, BudgetReason.IDENTITY_DAILY),
82
+ ):
83
+ if budget is None or budget <= 0: # unset → no limit (narrows budget to float below)
84
+ continue
85
+ if spend >= budget:
86
+ return _block(reason)
87
+ if spend >= budget * WARN_THRESHOLD:
88
+ warnings.append(f"{reason.value}:80pct")
89
+
90
+ # 3) subscription status / expiry (only when a subscription is present)
91
+ if inp.subscription_status is not None:
92
+ if inp.subscription_status.lower() in inp.blocking_statuses:
93
+ return _block(BudgetReason.SUBSCRIPTION_INACTIVE)
94
+ if inp.subscription_expired:
95
+ return _block(BudgetReason.SUBSCRIPTION_EXPIRED)
96
+
97
+ # 4) monthly token quota — hard-stop ONLY for a plan with no overage (Free); paid plans run on
98
+ if inp.monthly_token_limit > 0:
99
+ used, limit = inp.monthly_tokens_used, inp.monthly_token_limit
100
+ if used >= limit and inp.overage_price <= 0:
101
+ return _block(BudgetReason.MONTHLY_TOKENS)
102
+ if used >= limit * WARN_THRESHOLD:
103
+ warnings.append("monthly_tokens:80pct")
104
+
105
+ return BudgetVerdict(blocked=False, reason=None, plan_limits=inp.plan_limits,
106
+ call_limit=inp.call_limit, warnings=warnings)
@@ -0,0 +1,211 @@
1
+ """
2
+ cogno_meter.pricing — the price book + per-modality cost resolution.
3
+
4
+ Adapted clean-room from the parent ``cogno/core/pricing.py``: model rates with
5
+ exact → fuzzy-prefix (version suffixes) → ``_default`` resolution, USD→currency
6
+ conversion, and per-modality cost. Two distinct numbers come out of here:
7
+
8
+ * **billable_tokens** — what counts toward the plan allowance/overage (LLM &
9
+ embedding tokens directly; audio = ``chars × audio_multiplier``).
10
+ * **cost_usd** — the real upstream provider cost (transparency only). Local /
11
+ self-hosted models resolve to ``_default = 0``.
12
+
13
+ The lib ships a default seed (illustrative rates); a host injects its own via
14
+ ``PriceBook.from_mapping(...)``. No YAML dependency — the host loads its config
15
+ (YAML/JSON/DB) and hands over a plain mapping.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import copy
21
+ import logging
22
+ from dataclasses import dataclass, field
23
+
24
+ from cogno_meter.types import Modality, UsageRecord
25
+
26
+ # Pure functions: no WARNING/INFO (the budget-block decision is the host's, and
27
+ # the caller logs the returned Bill). DEBUG only — inspect the calculation.
28
+ logger = logging.getLogger("cogno_meter.pricing")
29
+
30
+ # Illustrative seed — values are examples (verify against providers; host overrides).
31
+ # llm: USD per 1M tokens (input/output). embedding: USD per 1M tokens.
32
+ # stt: USD per minute of audio. tts: USD per 1M characters. _default: self-hosted = 0.
33
+ DEFAULT_RATES: dict = {
34
+ "llm": {
35
+ # exact keys for every catalogued model — the fuzzy resolver would otherwise let a
36
+ # bare "gpt-5-mini" greedily prefix-match "gpt-5"'s far pricier rate.
37
+ "openai:gpt-5-nano": {"input": 0.05, "output": 0.40},
38
+ "openai:gpt-4.1-nano": {"input": 0.10, "output": 0.40},
39
+ "openai:gpt-4o-mini": {"input": 0.15, "output": 0.60},
40
+ "openai:gpt-5.4-nano": {"input": 0.20, "output": 1.25},
41
+ "openai:gpt-5-mini": {"input": 0.25, "output": 2.00},
42
+ "openai:gpt-4.1-mini": {"input": 0.40, "output": 1.60},
43
+ "openai:gpt-5.4-mini": {"input": 0.75, "output": 4.50},
44
+ "openai:gpt-5.6-luna": {"input": 1.00, "output": 6.00},
45
+ "openai:gpt-5": {"input": 1.25, "output": 10.00},
46
+ "openai:gpt-4.1": {"input": 2.00, "output": 8.00},
47
+ "openai:gpt-5.6-terra": {"input": 2.50, "output": 15.00},
48
+ "openai:gpt-5.6-sol": {"input": 5.00, "output": 30.00},
49
+ "openai:gpt-5.5-pro": {"input": 30.00, "output": 180.00},
50
+ "openai:gpt-4o": {"input": 2.50, "output": 10.00},
51
+ # anthropic — real per-MTok rates (Opus 4.6=$5/$25, Sonnet 4.5=$3/$15, Haiku 4.5=$1/$5);
52
+ # the original Opus 4 keeps its launch $15/$75.
53
+ # Anthropic API IDs are hyphenated (claude-opus-4-6, not …4.6) — must match the id the
54
+ # backend reports into the ledger, or the rate resolves to _default (0).
55
+ "anthropic:claude-haiku-4-5": {"input": 1.00, "output": 5.00},
56
+ "anthropic:claude-sonnet-4-0": {"input": 3.00, "output": 15.00},
57
+ "anthropic:claude-sonnet-4-5": {"input": 3.00, "output": 15.00},
58
+ "anthropic:claude-opus-4-0": {"input": 15.00, "output": 75.00},
59
+ "anthropic:claude-opus-4-5": {"input": 5.00, "output": 25.00},
60
+ "anthropic:claude-opus-4-6": {"input": 5.00, "output": 25.00},
61
+ # gemini — 2.5 family verified vs ai.google.dev; 3.x preview partly estimated.
62
+ "gemini:gemini-2.5-flash-lite": {"input": 0.10, "output": 0.40}, # verified
63
+ "gemini:gemini-2.5-flash": {"input": 0.30, "output": 2.50}, # verified
64
+ "gemini:gemini-3-flash": {"input": 0.50, "output": 3.00}, # input verified, output est.
65
+ "gemini:gemini-2.5-pro": {"input": 1.25, "output": 10.00}, # verified (≤200k prompt)
66
+ "gemini:gemini-3-pro": {"input": 2.00, "output": 12.00}, # est. (aligned to 3.1-pro)
67
+ "gemini:gemini-3.1-pro": {"input": 2.00, "output": 12.00}, # verified (3.1 Pro Preview)
68
+ # grok — verified vs xAI pricing; grok-3-mini estimated. (grok-4.20 was fictional →
69
+ # dropped; real flagship is grok-4.5.)
70
+ "grok:grok-3-mini": {"input": 0.30, "output": 0.50}, # est.
71
+ "grok:grok-3": {"input": 2.00, "output": 10.00}, # verified (legacy)
72
+ "grok:grok-4": {"input": 3.00, "output": 15.00}, # verified
73
+ "grok:grok-4.1-fast": {"input": 0.20, "output": 0.50}, # verified
74
+ "grok:grok-4.3": {"input": 1.25, "output": 2.50}, # verified
75
+ "grok:grok-4.5": {"input": 2.00, "output": 6.00}, # verified (flagship)
76
+ "ollama:_default": {"input": 0.0, "output": 0.0}, # self-hosted
77
+ "_default": {"input": 0.0, "output": 0.0},
78
+ },
79
+ "embedding": {
80
+ "openai:text-embedding-3-small": 0.02,
81
+ "openai:text-embedding-3-large": 0.13,
82
+ "_default": 0.0,
83
+ },
84
+ "stt": { # USD per minute
85
+ "openai:whisper-1": 0.006,
86
+ "groq:whisper-large-v3-turbo": 0.04,
87
+ "_default": 0.0, # self-hosted faster-whisper
88
+ },
89
+ "tts": { # USD per 1M characters
90
+ "openai:tts-1": 15.00,
91
+ "openai:tts-1-hd": 30.00,
92
+ "xai:grok-2-tts": 4.20,
93
+ "_default": 0.0, # self-hosted Kokoro
94
+ },
95
+ }
96
+
97
+ DEFAULT_USD_BRL_RATE = 5.70
98
+ DEFAULT_AUDIO_MULTIPLIER = 2.0
99
+
100
+
101
+ @dataclass
102
+ class PriceBook:
103
+ rates: dict = field(default_factory=lambda: copy.deepcopy(DEFAULT_RATES))
104
+ usd_brl_rate: float = DEFAULT_USD_BRL_RATE
105
+ audio_multiplier: float = DEFAULT_AUDIO_MULTIPLIER # chars × this → billable tokens
106
+
107
+ @classmethod
108
+ def default(cls) -> "PriceBook":
109
+ return cls()
110
+
111
+ @classmethod
112
+ def from_mapping(cls, mapping: dict) -> "PriceBook":
113
+ """Build from a host-supplied mapping (the parsed pricing config)."""
114
+ return cls(
115
+ rates={k: v for k, v in mapping.items()
116
+ if k in ("llm", "embedding", "stt", "tts")},
117
+ usd_brl_rate=float(mapping.get("usd_brl_rate", DEFAULT_USD_BRL_RATE)),
118
+ audio_multiplier=float(mapping.get("audio_multiplier", DEFAULT_AUDIO_MULTIPLIER)),
119
+ )
120
+
121
+ # ── rate resolution: exact → prefix-fuzzy → BARE (no 'provider:' prefix) → _default ──
122
+ #
123
+ # The ledger stores the backend's bare model name ('gpt-4o', 'qwen3:8b'), but the rate keys
124
+ # carry a 'provider:' prefix ('openai:gpt-4o'). So besides matching a prefixed model, also
125
+ # match a bare model against the key's model part (exact first so 'gpt-4o' doesn't greedily
126
+ # grab 'gpt-4o-mini', then longest-prefix fuzzy for versioned names like 'gpt-4o-mini-2024…').
127
+ @staticmethod
128
+ def _bare(key: str) -> str:
129
+ return key.split(":", 1)[1] if ":" in key else key
130
+
131
+ @staticmethod
132
+ def _resolve(table: dict, model: str):
133
+ if model in table:
134
+ logger.debug("event=rate_resolve model=%s match=exact", model)
135
+ return table[model]
136
+ items = [(k, r) for k, r in table.items() if k != "_default"]
137
+ # Longest-key-first so a short key that string-prefixes a longer one (``gpt-5`` vs
138
+ # ``gpt-5.5-pro``) never steals the more specific model's rate. All fuzzy passes below
139
+ # must be longest-first; step 2 used to iterate in dict-insertion order and mispriced
140
+ # dated builds of flagship models (~19x under-report on the cost-transparency figure).
141
+ prefix_items = sorted(items, key=lambda kv: len(kv[0]), reverse=True)
142
+ for key, rate in prefix_items: # prefixed model vs prefixed key (versioned)
143
+ if model.startswith(key):
144
+ logger.debug("event=rate_resolve model=%s match=fuzzy key=%s", model, key)
145
+ return rate
146
+ for key, rate in items: # bare model == the key's model part
147
+ if model == PriceBook._bare(key):
148
+ logger.debug("event=rate_resolve model=%s match=bare key=%s", model, key)
149
+ return rate
150
+ for key, rate in sorted(items, key=lambda kv: len(PriceBook._bare(kv[0])), reverse=True):
151
+ bare = PriceBook._bare(key) # bare versioned → longest bare prefix wins
152
+ if bare and model.startswith(bare):
153
+ logger.debug("event=rate_resolve model=%s match=bare_fuzzy key=%s", model, key)
154
+ return rate
155
+ # Per-provider catch-all (``openai:_default``) before the global one, so a host can set a
156
+ # non-zero default per provider instead of every un-catalogued model silently costing 0.
157
+ if ":" in model:
158
+ provider_default = table.get(f"{model.split(':', 1)[0]}:_default")
159
+ if provider_default is not None:
160
+ logger.debug("event=rate_resolve model=%s match=provider_default", model)
161
+ return provider_default
162
+ logger.debug("event=rate_resolve model=%s match=default", model)
163
+ return table.get("_default")
164
+
165
+ # ── provider cost (transparency), in USD ──────────────────────────
166
+ def llm_cost_usd(self, model: str, tokens_in: int, tokens_out: int) -> float:
167
+ rates = self._resolve(self.rates.get("llm", {}), model)
168
+ if not isinstance(rates, dict):
169
+ return 0.0
170
+ return (tokens_in / 1_000_000) * float(rates.get("input", 0)) + \
171
+ (tokens_out / 1_000_000) * float(rates.get("output", 0))
172
+
173
+ def embedding_cost_usd(self, model: str, tokens: int) -> float:
174
+ rate = self._resolve(self.rates.get("embedding", {}), model)
175
+ return (tokens / 1_000_000) * float(rate or 0.0)
176
+
177
+ def stt_cost_usd(self, model: str, minutes: float) -> float:
178
+ rate = self._resolve(self.rates.get("stt", {}), model)
179
+ return float(minutes) * float(rate or 0.0)
180
+
181
+ def tts_cost_usd(self, model: str, chars: int) -> float:
182
+ rate = self._resolve(self.rates.get("tts", {}), model)
183
+ return (chars / 1_000_000) * float(rate or 0.0)
184
+
185
+ def usage_cost_usd(self, rec: UsageRecord) -> float:
186
+ if rec.modality == Modality.LLM:
187
+ return self.llm_cost_usd(rec.model, int(rec.tokens_in or 0), int(rec.tokens_out or 0))
188
+ if rec.modality == Modality.EMBEDDING:
189
+ return self.embedding_cost_usd(rec.model, int(rec.tokens_in or 0) or int(rec.tokens_out or 0))
190
+ if rec.modality == Modality.STT:
191
+ return self.stt_cost_usd(rec.model, rec.minutes)
192
+ if rec.modality == Modality.TTS:
193
+ return self.tts_cost_usd(rec.model, rec.chars)
194
+ return 0.0
195
+
196
+ # ── billable tokens (toward the allowance/overage) ────────────────
197
+ def billable_tokens(self, rec: UsageRecord) -> int:
198
+ """Tokens that count toward the monthly allowance. LLM/embedding use the
199
+ token counts directly; audio is metered by chars × ``audio_multiplier``.
200
+
201
+ Token fields are coerced (``None``/missing → 0): one malformed ledger record must not
202
+ raise ``TypeError`` and abort billing for the whole period."""
203
+ tin, tout = int(rec.tokens_in or 0), int(rec.tokens_out or 0)
204
+ if rec.modality == Modality.LLM:
205
+ return tin + tout
206
+ # Embedding: mirror the cost path (``tokens_in or tokens_out``) so billable tokens and
207
+ # the priced amount interpret the same record identically — embeddings carry input only.
208
+ if rec.modality == Modality.EMBEDDING:
209
+ return tin or tout
210
+ # STT / TTS — always char-metered, scaled up by the audio multiplier.
211
+ return int(round((rec.chars or 0) * self.audio_multiplier))
File without changes
@@ -0,0 +1,64 @@
1
+ """
2
+ cogno_meter.types — usage records, plans, and the computed bill.
3
+
4
+ All cross-modality usage is normalized to **billable tokens** (the unit the
5
+ monthly allowance and overage are denominated in). Audio (STT/TTS) is metered by
6
+ **characters**, multiplied by a configurable factor so it draws down the
7
+ allowance faster (see ``PriceBook.audio_multiplier``).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ from enum import Enum
14
+
15
+
16
+ class Modality(str, Enum):
17
+ LLM = "llm"
18
+ EMBEDDING = "embedding"
19
+ STT = "stt"
20
+ TTS = "tts"
21
+
22
+
23
+ @dataclass
24
+ class UsageRecord:
25
+ """One unit of metered usage (a stage call, a TTS synthesis, …).
26
+
27
+ LLM/embedding usage carries token counts; audio (STT/TTS) carries ``chars``
28
+ (always char-metered) and, optionally, ``minutes`` of audio for the
29
+ provider-cost transparency figure (STT is priced per minute upstream).
30
+ """
31
+
32
+ modality: Modality
33
+ model: str # "provider:model" (the model that actually ran)
34
+ tokens_in: int = 0
35
+ tokens_out: int = 0
36
+ chars: int = 0 # audio: STT transcribed / TTS input characters
37
+ minutes: float = 0.0 # audio duration (optional; STT provider-cost only)
38
+
39
+
40
+ @dataclass
41
+ class Plan:
42
+ """A tenant's plan. Values are host-owned (Stripe/DB) — these are just the
43
+ parameters the overage math needs."""
44
+
45
+ name: str
46
+ monthly_token_limit: int # free billable tokens included per period
47
+ overage_price: float # charge per 1M tokens over the limit (plan currency)
48
+ base_price: float = 0.0 # subscription base for the period (plan currency)
49
+
50
+
51
+ @dataclass
52
+ class Bill:
53
+ """The computed bill for a period. ``total`` is what the platform charges the
54
+ customer; ``provider_cost_*`` is transparency only (real upstream cost, paid
55
+ by the client via BYOK for external models — NOT the platform charge)."""
56
+
57
+ total_tokens: int # billable tokens (incl. audio chars × multiplier)
58
+ allowance: int
59
+ overage_tokens: int
60
+ overage_cost: float # plan currency
61
+ base_price: float
62
+ total: float # base_price + overage_cost (plan currency)
63
+ provider_cost_usd: float # transparency
64
+ provider_cost_brl: float # transparency (usd × usd_brl_rate)
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: cogno-meter
3
+ Version: 0.1.0
4
+ Summary: Usage metering + pricing/overage for the Cogno cognitive pipeline — cross-modality (LLM/embedding tokens + STT/TTS chars) billable-token accounting against a plan allowance
5
+ Author: Vinicius Vale
6
+ Maintainer: Sudoers AI
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://github.com/sudoers-ai/cogno-meter
9
+ Project-URL: Repository, https://github.com/sudoers-ai/cogno-meter
10
+ Project-URL: Issues, https://github.com/sudoers-ai/cogno-meter/issues
11
+ Keywords: metering,billing,pricing,tokens,usage,llm,overage,agents
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Office/Business :: Financial
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=8.0; extra == "dev"
27
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
28
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
29
+ Requires-Dist: ruff>=0.5; extra == "dev"
30
+ Requires-Dist: mypy>=1.8; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # cogno-meter
34
+
35
+ **Usage metering + pricing/overage for the [Cogno](https://github.com/sudoers-ai/cogno-anima) cognitive pipeline** — cross-modality billable-token accounting against a plan allowance.
36
+
37
+ `cogno-meter` turns raw usage (LLM/embedding **tokens** + STT/TTS **characters**) into a bill. Pure code, zero dependencies, zero I/O — the host owns the plan values, the price book values, the accumulated-usage persistence, and invoicing. Adapted clean-room from the parent Cogno SaaS's `pricing` / `metering` / `db_billing`.
38
+
39
+ > Status: **alpha** — the pricing + overage core and the unit suite are in place.
40
+
41
+ ## The billing model
42
+
43
+ - **Everything counts as billable tokens.** A **local** model costs nothing to run, but its tokens still draw down the monthly allowance.
44
+ - **Audio is char-metered, with a multiplier.** STT/TTS usage is measured in characters and multiplied (default `2×`) so audio is more expensive per the allowance.
45
+ - **Overage is per-plan, not per-model.** Beyond the monthly allowance, the customer is charged the **plan's** rate per million tokens — cheap, because the platform runs local models. **BYOK is not exempt**: over the limit you pay the override even with your own API key.
46
+ - **Provider cost is transparency only.** The real upstream cost (per-model price book) is computed alongside so the client can track external-LLM spend; for external models under BYOK the client pays the provider directly. It is **not** the platform charge.
47
+
48
+ ## Use
49
+
50
+ ```python
51
+ from cogno_meter import meter, Plan, PriceBook, UsageRecord, Modality
52
+
53
+ plan = Plan(name="Básico", monthly_token_limit=500_000, overage_price=0.05, base_price=20.0)
54
+ book = PriceBook.default() # or PriceBook.from_mapping(host_pricing_dict)
55
+
56
+ records = [ # a period's usage (from synapse + vox)
57
+ UsageRecord(Modality.LLM, "ollama:mistral:latest", tokens_in=1_000_000, tokens_out=200_000),
58
+ UsageRecord(Modality.TTS, "local:kokoro", chars=50_000), # 50k × 2 = 100k billable tokens
59
+ ]
60
+
61
+ bill = meter(records, plan=plan, book=book)
62
+ # bill.total_tokens=1_300_000 overage_tokens=800_000 overage_cost=0.04
63
+ # bill.total=20.04 provider_cost_brl=0.0 (all local → free upstream)
64
+ ```
65
+
66
+ External, paid model (transparency cost appears, charge stays plan-based):
67
+
68
+ ```python
69
+ records = [UsageRecord(Modality.LLM, "openai:gpt-4.1-mini", tokens_in=1_000_000, tokens_out=500_000)]
70
+ bill = meter(records, plan=plan, book=book)
71
+ # overage_cost=0.05 total=20.05 (platform charge — plan rate)
72
+ # provider_cost_usd=1.20 provider_cost_brl=6.84 (transparency — client pays OpenAI via BYOK)
73
+ ```
74
+
75
+ ## The price book
76
+
77
+ `PriceBook` resolves a model's rate by exact match → fuzzy version-prefix → provider `_default` (self-hosted = 0), and converts USD→currency. The lib ships an **illustrative** seed (`DEFAULT_RATES`); a host injects its own via `PriceBook.from_mapping(...)` (load your YAML/JSON/DB and pass a plain mapping — no YAML dependency here). Units: LLM/embedding USD per 1M tokens, STT USD per minute, TTS USD per 1M characters.
78
+
79
+ ## Boundary
80
+
81
+ | Concern | Owner |
82
+ | --- | --- |
83
+ | Price book resolution, per-modality cost, audio char×multiplier, overage math | **cogno-meter** |
84
+ | Plan/allowance/overage-price values, price book values | **host** |
85
+ | Accumulated-usage persistence (the token ledger), invoicing, Stripe | **host** |
86
+ | Per-tenant model overrides, BYOK key storage | **host** |
87
+
88
+ `meter` consumes usage produced by `cogno-synapse` (tokens) and `cogno-vox` (audio chars); it never imports them — usage is handed in as plain `UsageRecord`s.
89
+
90
+ ## The Cogno ecosystem
91
+
92
+ `cogno-meter` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
93
+ small, composable, Apache-2.0 libraries that together form a complete
94
+ conversational-agent platform. Each library owns a single concern and stays
95
+ infra-agnostic; a **host** assembles them into a running agent:
96
+
97
+ ![The Cogno ecosystem](docs/assets/cogno-ecosystem.svg)
98
+
99
+ The open-source libraries are the organs; the **host is the body** that joins
100
+ them. Our reference host — `cogno-host`, with its `cogno-ui` dashboard — is the
101
+ private product layer, but it holds no special powers: everything it does rides
102
+ on the public seams documented in each library's `docs/HOST_INTEGRATION.md`, so
103
+ you can assemble a body of your own.
104
+
105
+ ## Test
106
+
107
+ ```bash
108
+ pip install -e ".[dev]"
109
+ pytest tests/unit -q
110
+ ```
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ cogno_meter/__init__.py
5
+ cogno_meter/billing.py
6
+ cogno_meter/budget.py
7
+ cogno_meter/pricing.py
8
+ cogno_meter/py.typed
9
+ cogno_meter/types.py
10
+ cogno_meter.egg-info/PKG-INFO
11
+ cogno_meter.egg-info/SOURCES.txt
12
+ cogno_meter.egg-info/dependency_links.txt
13
+ cogno_meter.egg-info/requires.txt
14
+ cogno_meter.egg-info/top_level.txt
@@ -0,0 +1,7 @@
1
+
2
+ [dev]
3
+ pytest>=8.0
4
+ pytest-asyncio>=0.23.0
5
+ pytest-cov>=5.0
6
+ ruff>=0.5
7
+ mypy>=1.8
@@ -0,0 +1 @@
1
+ cogno_meter
@@ -0,0 +1,67 @@
1
+ [project]
2
+ name = "cogno-meter"
3
+ version = "0.1.0"
4
+ description = "Usage metering + pricing/overage for the Cogno cognitive pipeline — cross-modality (LLM/embedding tokens + STT/TTS chars) billable-token accounting against a plan allowance"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Vinicius Vale" }]
10
+ maintainers = [{ name = "Sudoers AI" }]
11
+ keywords = ["metering", "billing", "pricing", "tokens", "usage", "llm", "overage", "agents"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Developers",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.10",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Topic :: Office/Business :: Financial",
20
+ "Topic :: Software Development :: Libraries",
21
+ "Operating System :: OS Independent",
22
+ "Typing :: Typed",
23
+ ]
24
+ # Pure code: no third-party runtime dependency. The host loads its pricing config
25
+ # (YAML/JSON/DB) and hands a plain mapping to PriceBook.from_mapping.
26
+ dependencies = []
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/sudoers-ai/cogno-meter"
30
+ Repository = "https://github.com/sudoers-ai/cogno-meter"
31
+ Issues = "https://github.com/sudoers-ai/cogno-meter/issues"
32
+
33
+ [project.optional-dependencies]
34
+ dev = [
35
+ "pytest>=8.0",
36
+ "pytest-asyncio>=0.23.0",
37
+ "pytest-cov>=5.0",
38
+ "ruff>=0.5",
39
+ "mypy>=1.8",
40
+ ]
41
+
42
+ [build-system]
43
+ requires = ["setuptools>=77.0.3", "wheel"]
44
+ build-backend = "setuptools.build_meta"
45
+
46
+ [tool.setuptools.packages.find]
47
+ include = ["cogno_meter*"]
48
+
49
+ [tool.setuptools.package-data]
50
+ cogno_meter = ["py.typed"]
51
+
52
+ [tool.pytest.ini_options]
53
+ asyncio_mode = "auto"
54
+ testpaths = ["tests"]
55
+
56
+ [tool.ruff]
57
+ line-length = 110
58
+ target-version = "py310"
59
+
60
+ [tool.ruff.lint]
61
+ select = ["E4", "E7", "E9", "F"]
62
+
63
+ [tool.mypy]
64
+ python_version = "3.10"
65
+ ignore_missing_imports = true
66
+ files = ["cogno_meter"]
67
+ warn_unused_ignores = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+