limitr 0.8.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- limitr/__init__.py +23 -0
- limitr/engine.bstf +0 -0
- limitr/engine.py +713 -0
- limitr/py.typed +0 -0
- limitr/types.py +93 -0
- limitr-0.8.6.dist-info/METADATA +106 -0
- limitr-0.8.6.dist-info/RECORD +10 -0
- limitr-0.8.6.dist-info/WHEEL +5 -0
- limitr-0.8.6.dist-info/licenses/LICENSE +201 -0
- limitr-0.8.6.dist-info/top_level.txt +1 -0
limitr/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Copyright 2026 Formata, Inc. All rights reserved.
|
|
3
|
+
#
|
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
# you may not use this file except in compliance with the License.
|
|
6
|
+
# You may obtain a copy of the License at
|
|
7
|
+
#
|
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
#
|
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
# See the License for the specific language governing permissions and
|
|
14
|
+
# limitations under the License.
|
|
15
|
+
#
|
|
16
|
+
|
|
17
|
+
"""Limitr: usage and margin control for AI products. The open-source engine, in-process."""
|
|
18
|
+
|
|
19
|
+
from .engine import Limitr
|
|
20
|
+
from .types import Cap, Customer, Decision, DecisionReason, EntitlementSource, Estimate
|
|
21
|
+
|
|
22
|
+
__version__ = '0.8.6'
|
|
23
|
+
__all__ = ['Limitr', 'Decision', 'DecisionReason', 'EntitlementSource', 'Estimate', 'Customer', 'Cap', '__version__']
|
limitr/engine.bstf
ADDED
|
Binary file
|
limitr/engine.py
ADDED
|
@@ -0,0 +1,713 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Copyright 2026 Formata, Inc. All rights reserved.
|
|
3
|
+
#
|
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
# you may not use this file except in compliance with the License.
|
|
6
|
+
# You may obtain a copy of the License at
|
|
7
|
+
#
|
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
#
|
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
# See the License for the specific language governing permissions and
|
|
14
|
+
# limitations under the License.
|
|
15
|
+
#
|
|
16
|
+
|
|
17
|
+
"""The Limitr engine for Python: a Limitr policy run in-process in a Stof document."""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import asyncio
|
|
22
|
+
import inspect
|
|
23
|
+
import json
|
|
24
|
+
import logging
|
|
25
|
+
import threading
|
|
26
|
+
import weakref
|
|
27
|
+
from contextlib import contextmanager
|
|
28
|
+
from datetime import datetime
|
|
29
|
+
from importlib import resources
|
|
30
|
+
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union
|
|
31
|
+
|
|
32
|
+
from pystof import Doc
|
|
33
|
+
|
|
34
|
+
from .types import Cap, Customer, Decision, EntitlementSource, Estimate, Record
|
|
35
|
+
|
|
36
|
+
log = logging.getLogger('limitr')
|
|
37
|
+
|
|
38
|
+
Policy = Union[str, Dict[str, Any], bytes, bytearray]
|
|
39
|
+
Context = Union[str, Dict[str, Any], None]
|
|
40
|
+
Event = Union[bool, str, Dict[str, Any]]
|
|
41
|
+
Time = Union[int, float, datetime, None]
|
|
42
|
+
|
|
43
|
+
_engine_bytes: Optional[bytes] = None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _engine() -> bytes:
|
|
47
|
+
"""The compiled engine (src/spec as bstf), read once."""
|
|
48
|
+
global _engine_bytes
|
|
49
|
+
if _engine_bytes is None:
|
|
50
|
+
_engine_bytes = resources.files('limitr').joinpath('engine.bstf').read_bytes()
|
|
51
|
+
return _engine_bytes
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _ms(value: Time) -> Optional[float]:
|
|
55
|
+
"""A time as ms since the epoch (a datetime, or a number already in ms)."""
|
|
56
|
+
if value is None:
|
|
57
|
+
return None
|
|
58
|
+
if isinstance(value, datetime):
|
|
59
|
+
return value.timestamp() * 1000
|
|
60
|
+
return float(value)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _num(value: Union[int, float, str, None]) -> Union[float, str, None]:
|
|
64
|
+
"""A value for the engine: numbers as floats, strings (with units, Ex. '250MB') as they are."""
|
|
65
|
+
if value is None or isinstance(value, str):
|
|
66
|
+
return value
|
|
67
|
+
return float(value)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _event(event: Event) -> Union[bool, str]:
|
|
71
|
+
"""Event data for the engine: True/False, or a dict or string sent as JSON."""
|
|
72
|
+
if isinstance(event, (bool, str)):
|
|
73
|
+
return event
|
|
74
|
+
return json.dumps(event)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _context(context: Context) -> Optional[str]:
|
|
78
|
+
"""A call's context (event data) for the engine: a dict or string sent as JSON, or None."""
|
|
79
|
+
if context is None or isinstance(context, str):
|
|
80
|
+
return context
|
|
81
|
+
return json.dumps(context)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _call_weak(method: 'weakref.WeakMethod', key: str, value: Any) -> None:
|
|
85
|
+
"""Call a weakly held method, if its instance is still around."""
|
|
86
|
+
bound = method()
|
|
87
|
+
if bound is not None:
|
|
88
|
+
bound(key, value)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _metadata(metadata: Union[str, Dict[str, Any], None]) -> Optional[str]:
|
|
92
|
+
if metadata is None or isinstance(metadata, str):
|
|
93
|
+
return metadata
|
|
94
|
+
return json.dumps(metadata)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class Limitr:
|
|
98
|
+
"""
|
|
99
|
+
A Limitr policy, run in-process: decide, meter, and price every call for each customer.
|
|
100
|
+
|
|
101
|
+
Every method runs one engine call, one at a time (a lock guards the document), so a single `allow` is safe
|
|
102
|
+
across threads. Two calls in a row are not one unit: use `reserve` and `settle` when concurrent calls must not
|
|
103
|
+
overspend together.
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from limitr import Limitr
|
|
107
|
+
|
|
108
|
+
policy = Limitr(open('policy.stof').read())
|
|
109
|
+
policy.ensure_customer('ada')
|
|
110
|
+
if policy.allow('ada', 'api', 1):
|
|
111
|
+
...
|
|
112
|
+
```
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
def __init__(self, policy: Policy = 'Limitr policy: {}', format: str = 'stof', validate: bool = True):
|
|
116
|
+
"""
|
|
117
|
+
Load a policy: Stof source (default), JSON / YAML / TOML text with `format`, a dict, or compiled bstf bytes.
|
|
118
|
+
Raises ValueError when `validate` (the default) finds the policy isn't valid.
|
|
119
|
+
"""
|
|
120
|
+
self.doc = Doc()
|
|
121
|
+
self._lock = threading.RLock()
|
|
122
|
+
self._handlers: Dict[str, Callable[[str, Any], Any]] = {}
|
|
123
|
+
self._modules: Dict[str, Tuple[bytes, Optional[Callable[[Doc], None]]]] = {}
|
|
124
|
+
self._max_execution_time: Optional[float] = 5000
|
|
125
|
+
|
|
126
|
+
self.doc.binary_import(_engine(), 'bstf') # the compiled engine (src/spec)
|
|
127
|
+
if self.doc.get('LimitrTypes') is not None:
|
|
128
|
+
self.doc.seal('LimitrTypes') # nothing parsed later can change the engine's functions
|
|
129
|
+
self._import(policy, format)
|
|
130
|
+
self.doc.call('<Limitr>.load') # root.policy becomes a Limitr (JSON/YAML/TOML have no type)
|
|
131
|
+
self.doc.set_max_execution_time(self._max_execution_time / 1000)
|
|
132
|
+
# each document keeps its own host functions, callable from any thread (stof 0.11.4). The handler holds this
|
|
133
|
+
# instance weakly: the document holds the handler, so a strong one would keep both alive forever
|
|
134
|
+
emit = weakref.WeakMethod(self._emit)
|
|
135
|
+
self.doc.lib('App', 'event_handler', lambda key, value: _call_weak(emit, key, value))
|
|
136
|
+
if validate:
|
|
137
|
+
ok, error = self.valid()
|
|
138
|
+
if not ok:
|
|
139
|
+
raise ValueError(error)
|
|
140
|
+
|
|
141
|
+
@classmethod
|
|
142
|
+
def new(cls, policy: Policy = 'Limitr policy: {}', format: str = 'stof', validate: bool = True) -> 'Limitr':
|
|
143
|
+
"""Same as `Limitr(policy, format, validate)` (the TypeScript SDK's `Limitr.new`)."""
|
|
144
|
+
return cls(policy, format, validate)
|
|
145
|
+
|
|
146
|
+
@contextmanager
|
|
147
|
+
def _using(self) -> Iterator[None]:
|
|
148
|
+
"""Run engine calls one at a time."""
|
|
149
|
+
with self._lock:
|
|
150
|
+
yield
|
|
151
|
+
|
|
152
|
+
def _import(self, policy: Policy, format: str) -> None:
|
|
153
|
+
if isinstance(policy, (bytes, bytearray)):
|
|
154
|
+
self.doc.binary_import(bytes(policy), 'bstf' if format == 'stof' else format)
|
|
155
|
+
elif isinstance(policy, dict):
|
|
156
|
+
self.doc.string_import(json.dumps(policy), 'json')
|
|
157
|
+
else:
|
|
158
|
+
self.doc.string_import(policy, format)
|
|
159
|
+
|
|
160
|
+
def _call(self, path: str, *args: Any) -> Any:
|
|
161
|
+
with self._using():
|
|
162
|
+
return self.doc.call(path, list(args))
|
|
163
|
+
|
|
164
|
+
def _record(self, node: Any) -> Optional[Record]:
|
|
165
|
+
"""An object in the document (by node ID) as a plain dict."""
|
|
166
|
+
if not isinstance(node, str):
|
|
167
|
+
return None
|
|
168
|
+
with self._using():
|
|
169
|
+
return json.loads(self.doc.string_export('json', node))
|
|
170
|
+
|
|
171
|
+
def _call_record(self, path: str, *args: Any) -> Optional[Record]:
|
|
172
|
+
with self._using():
|
|
173
|
+
return self._record(self.doc.call(path, list(args)))
|
|
174
|
+
|
|
175
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
176
|
+
# Policy
|
|
177
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
def module(self, name: str, data: bytes, setup: Optional[Callable[[Doc], None]] = None) -> None:
|
|
180
|
+
"""
|
|
181
|
+
Load a module into this policy's document: Stof compiled to bstf whose root object is `name`. It's sealed
|
|
182
|
+
like the engine, so nothing parsed later can change it, and loaded once: calling again only runs `setup`.
|
|
183
|
+
"""
|
|
184
|
+
self._modules[name] = (data, setup)
|
|
185
|
+
with self._using():
|
|
186
|
+
if self.doc.get(name) is None:
|
|
187
|
+
self.doc.binary_import(data, 'bstf')
|
|
188
|
+
if self.doc.get(name) is None:
|
|
189
|
+
raise ValueError(f"Limitr: module '{name}' has no root object named '{name}'")
|
|
190
|
+
self.doc.seal(name)
|
|
191
|
+
if setup:
|
|
192
|
+
setup(self.doc)
|
|
193
|
+
|
|
194
|
+
def set_max_execution_time(self, ms: Optional[float]) -> None:
|
|
195
|
+
"""How long a policy call can run before it fails, in milliseconds (None for no limit). Defaults to 5 seconds."""
|
|
196
|
+
self._max_execution_time = ms
|
|
197
|
+
with self._using():
|
|
198
|
+
self.doc.set_max_execution_time(None if ms is None else ms / 1000)
|
|
199
|
+
|
|
200
|
+
def doc_call(self, path: str, *args: Any) -> Any:
|
|
201
|
+
"""Call any engine function by path, Ex. `doc_call('policy.set_customer_refs', id, refs)`."""
|
|
202
|
+
return self._call(path, *args)
|
|
203
|
+
|
|
204
|
+
def valid(self) -> Tuple[bool, str]:
|
|
205
|
+
"""Is this policy valid? (True, '') or (False, the first error)."""
|
|
206
|
+
with self._using():
|
|
207
|
+
if self.doc.call('policy.valid', []):
|
|
208
|
+
return True, ''
|
|
209
|
+
return False, str(self.doc.get('<LimitrValidation>.error_message') or 'invalid policy')
|
|
210
|
+
|
|
211
|
+
def difference(self, other: 'Limitr', symmetric: bool = False) -> Record:
|
|
212
|
+
"""The difference between this policy and another (this one is the schema)."""
|
|
213
|
+
data = other._call('policy.policy_bstf')
|
|
214
|
+
return json.loads(self._call('policy.difference_bstf', bytes(data), symmetric))
|
|
215
|
+
|
|
216
|
+
def version(self) -> str:
|
|
217
|
+
"""The engine version."""
|
|
218
|
+
with self._using():
|
|
219
|
+
ver = self.doc.get('<root.Limitr>.version')
|
|
220
|
+
return str(ver) if ver is not None else 'unknown'
|
|
221
|
+
|
|
222
|
+
def close(self) -> None:
|
|
223
|
+
"""Nothing to release for a local engine (here for symmetry with Limitr Cloud)."""
|
|
224
|
+
|
|
225
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
226
|
+
# Events
|
|
227
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
228
|
+
|
|
229
|
+
def add_handler(self, name: str, handler: Callable[[str, Any], Any]) -> None:
|
|
230
|
+
"""
|
|
231
|
+
Add an event handler by name: `handler(event_name, value)`, called for every event (objects arrive as dicts).
|
|
232
|
+
Handlers run during the engine call that sent the event, so don't call this policy from one (queue the work
|
|
233
|
+
instead). A handler that raises is logged and skipped; a coroutine is scheduled on the running event loop.
|
|
234
|
+
"""
|
|
235
|
+
self._handlers[name] = handler
|
|
236
|
+
|
|
237
|
+
def remove_handler(self, name: str) -> bool:
|
|
238
|
+
return self._handlers.pop(name, None) is not None
|
|
239
|
+
|
|
240
|
+
def clear_handlers(self) -> None:
|
|
241
|
+
self._handlers = {}
|
|
242
|
+
|
|
243
|
+
def _emit(self, key: str, value: Any) -> None:
|
|
244
|
+
if not self._handlers:
|
|
245
|
+
return
|
|
246
|
+
if isinstance(value, str) and value[:1] in ('{', '['):
|
|
247
|
+
try:
|
|
248
|
+
value = json.loads(value)
|
|
249
|
+
except ValueError:
|
|
250
|
+
pass
|
|
251
|
+
for name, handler in list(self._handlers.items()):
|
|
252
|
+
try:
|
|
253
|
+
result = handler(key, value)
|
|
254
|
+
if inspect.isawaitable(result):
|
|
255
|
+
try:
|
|
256
|
+
asyncio.get_running_loop().create_task(result) # type: ignore[arg-type]
|
|
257
|
+
except RuntimeError:
|
|
258
|
+
log.error("Limitr: event handler '%s' returned a coroutine with no running event loop", name)
|
|
259
|
+
result.close() if inspect.iscoroutine(result) else None
|
|
260
|
+
except Exception:
|
|
261
|
+
log.exception("Limitr: event handler '%s' failed on '%s'", name, key)
|
|
262
|
+
|
|
263
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
264
|
+
# Plans
|
|
265
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
266
|
+
|
|
267
|
+
def plan(self, id: str, default: bool = True) -> Optional[Record]:
|
|
268
|
+
"""A plan record by plan ID or customer ID (the default plan when nothing else matches, unless `default` is False)."""
|
|
269
|
+
return self._call_record('policy.plan', id, default)
|
|
270
|
+
|
|
271
|
+
def default_plan(self) -> Optional[Record]:
|
|
272
|
+
return self._call_record('policy.default_plan')
|
|
273
|
+
|
|
274
|
+
def set_plan(self, id: str, plan_stof: str) -> Optional[str]:
|
|
275
|
+
"""Set (add or replace) a plan from Stof source. Returns the plan's node ID."""
|
|
276
|
+
return self._call('policy.set_plan', id, plan_stof)
|
|
277
|
+
|
|
278
|
+
def delete_plan(self, id: str) -> bool:
|
|
279
|
+
return bool(self._call('policy.delete_plan', id))
|
|
280
|
+
|
|
281
|
+
def plan_period(self, id: str) -> Optional[str]:
|
|
282
|
+
"""'yearly', 'monthly', 'weekly', 'daily', or None."""
|
|
283
|
+
return self._call('policy.plan_period', id)
|
|
284
|
+
|
|
285
|
+
def plan_trial_period(self, id: str) -> Optional[float]:
|
|
286
|
+
"""The plan's trial period in ms, if any."""
|
|
287
|
+
return self._call('policy.plan_trial_period', id)
|
|
288
|
+
|
|
289
|
+
def plan_sub_entitlement_name(self, id: str) -> Optional[str]:
|
|
290
|
+
return self._call('policy.plan_sub_entitlement_name', id)
|
|
291
|
+
|
|
292
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
293
|
+
# Credits and exchange
|
|
294
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
295
|
+
|
|
296
|
+
def credit(self, id: str) -> Optional[Record]:
|
|
297
|
+
return self._call_record('policy.credit', id)
|
|
298
|
+
|
|
299
|
+
def credit_for(self, id: str, entitlement: str) -> Optional[Record]:
|
|
300
|
+
"""The credit an entitlement meters in, for a plan ID or customer ID."""
|
|
301
|
+
return self._call_record('policy.credit_for', id, entitlement)
|
|
302
|
+
|
|
303
|
+
def credit_exchange(self, in_credit: str, out_credit: str = 'rune', value: float = 1) -> Optional[float]:
|
|
304
|
+
"""Convert `value` of one credit to another, if there's an exchange path."""
|
|
305
|
+
return self._call('policy.credit_exchange', in_credit, out_credit, _num(value))
|
|
306
|
+
|
|
307
|
+
def exchange_pair(self, name: str) -> Optional[Dict[str, Any]]:
|
|
308
|
+
"""An exchange pair: one `name` is worth `value` of `currency`. None if there's no pair for `name`."""
|
|
309
|
+
pair = self._call_record('policy.exchange.get_pair', name)
|
|
310
|
+
return {'value': pair['value'], 'currency': pair['currency']} if pair else None
|
|
311
|
+
|
|
312
|
+
def set_exchange_pair(self, name: str, value: float, currency: str = 'rune', event: bool = True) -> bool:
|
|
313
|
+
"""Add or replace an exchange pair (Ex. `set_exchange_pair('euro', 1.16, 'usd')`)."""
|
|
314
|
+
return bool(self._call('policy.set_exchange_pair', name, _num(value), currency, event))
|
|
315
|
+
|
|
316
|
+
def remove_exchange_pair(self, name: str, event: bool = True) -> bool:
|
|
317
|
+
return bool(self._call('policy.remove_exchange_pair', name, event))
|
|
318
|
+
|
|
319
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
320
|
+
# Customers
|
|
321
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
322
|
+
|
|
323
|
+
def customer(self, id: str) -> Optional[Customer]:
|
|
324
|
+
"""A customer record by ID or alt ID."""
|
|
325
|
+
return self._call_record('policy.customer', id)
|
|
326
|
+
|
|
327
|
+
def customer_metadata(self, id: str) -> Optional[Record]:
|
|
328
|
+
return self._call_record('policy.customer_metadata', id)
|
|
329
|
+
|
|
330
|
+
def customers(self) -> Dict[str, Customer]:
|
|
331
|
+
"""Every customer, by ID: all the state there is, so this is what to save (see load_customers)."""
|
|
332
|
+
with self._using():
|
|
333
|
+
node = self.doc.call('<Limitr>.load', [])
|
|
334
|
+
customers = self.doc.get('customers', node) if isinstance(node, str) else None
|
|
335
|
+
return self._record(customers) or {}
|
|
336
|
+
|
|
337
|
+
def customer_refs(self, id: str) -> Optional[List[str]]:
|
|
338
|
+
return self._call('policy.customer_refs', id)
|
|
339
|
+
|
|
340
|
+
def set_customer_plan(self, id: str, plan: str, overwrite_meters: bool = True) -> bool:
|
|
341
|
+
"""Change a customer's plan. True when it changed."""
|
|
342
|
+
return bool(self._call('policy.set_customer_plan', id, plan, overwrite_meters))
|
|
343
|
+
|
|
344
|
+
def set_customer_period(self, id: str, start: Time, end: Time = None, event: bool = True) -> bool:
|
|
345
|
+
"""
|
|
346
|
+
Set a customer's billing period ('period' reset schedules follow it). `end` defaults to one plan period after
|
|
347
|
+
`start`; no dates go back to the plan's calendar period. Times are datetimes or ms.
|
|
348
|
+
"""
|
|
349
|
+
return bool(self._call('policy.set_customer_period', id, _ms(start), _ms(end), event))
|
|
350
|
+
|
|
351
|
+
def set_customer_expires(self, id: str, expires: Time, event: bool = True) -> bool:
|
|
352
|
+
"""When a customer's access ends (None: never). From then on allow() and check() refuse; its usage is kept."""
|
|
353
|
+
return bool(self._call('policy.set_customer_expires', id, _ms(expires), event))
|
|
354
|
+
|
|
355
|
+
def ensure_customer_included_topups(self, id: str, event: bool = True) -> None:
|
|
356
|
+
self._call('policy.ensure_included_topups', id, event)
|
|
357
|
+
|
|
358
|
+
def ensure_customer_plan_quantity(self, id: str) -> bool:
|
|
359
|
+
return bool(self._call('policy.ensure_plan_subscription', id))
|
|
360
|
+
|
|
361
|
+
def ensure_customer(self, id: str, plan: str = '', type: str = 'user', label: str = 'User',
|
|
362
|
+
refs: Optional[List[str]] = None, alts: Optional[List[str]] = None,
|
|
363
|
+
metadata: Union[str, Dict[str, Any], None] = None) -> bool:
|
|
364
|
+
"""
|
|
365
|
+
Make sure a customer exists, creating it if needed. True when a new customer was created; False when it
|
|
366
|
+
already existed or couldn't be created (no plan resolves for it, or the ID contains a period).
|
|
367
|
+
"""
|
|
368
|
+
with self._using():
|
|
369
|
+
if self.doc.call('policy.customer', [id]) is not None:
|
|
370
|
+
return False
|
|
371
|
+
node = self.doc.call('policy.create_customer', [id, plan, type, label, refs, alts, _metadata(metadata)])
|
|
372
|
+
return isinstance(node, str)
|
|
373
|
+
|
|
374
|
+
def create_customer(self, id: str, plan: str = '', type: str = 'user', label: str = 'User',
|
|
375
|
+
refs: Optional[List[str]] = None, alts: Optional[List[str]] = None,
|
|
376
|
+
metadata: Union[str, Dict[str, Any], None] = None) -> Optional[Customer]:
|
|
377
|
+
"""
|
|
378
|
+
Create a customer. IDs and alt IDs can't contain a period (Ex. an email): use your own placeholder, or keep
|
|
379
|
+
the email in metadata. None when it couldn't be created. Prefer ensure_customer.
|
|
380
|
+
"""
|
|
381
|
+
return self._call_record('policy.create_customer', id, plan, type, label, refs, alts, _metadata(metadata))
|
|
382
|
+
|
|
383
|
+
def ensure_set_customer(self, customer: Union[str, Customer], event: bool = True) -> bool:
|
|
384
|
+
"""Set a customer from a record unless one with its ID exists. True when it was set."""
|
|
385
|
+
record = json.loads(customer) if isinstance(customer, str) else customer
|
|
386
|
+
id = record.get('id')
|
|
387
|
+
if not id:
|
|
388
|
+
raise ValueError('ensure_set_customer expects a customer record with an ID')
|
|
389
|
+
with self._using():
|
|
390
|
+
if self.doc.call('policy.customer', [id]) is not None:
|
|
391
|
+
return False
|
|
392
|
+
return bool(self.doc.call('policy.set_customer', [json.dumps(record), event]))
|
|
393
|
+
|
|
394
|
+
def set_customer(self, customer: Union[str, Customer], event: bool = True) -> Optional[str]:
|
|
395
|
+
"""Set a customer from a record (a dict or JSON/Stof text). Returns its node ID."""
|
|
396
|
+
source = customer if isinstance(customer, str) else json.dumps(customer)
|
|
397
|
+
return self._call('policy.set_customer', source, event)
|
|
398
|
+
|
|
399
|
+
def load_customers(self, customers: Union[Dict[str, Customer], List[Customer]]) -> None:
|
|
400
|
+
"""Load many customers from records (Ex. what customers() returned): all that's needed to restore state."""
|
|
401
|
+
records = customers if isinstance(customers, list) else [
|
|
402
|
+
{**record, 'id': record.get('id') or key} for key, record in customers.items()
|
|
403
|
+
]
|
|
404
|
+
for record in records:
|
|
405
|
+
if isinstance(record.get('id'), str):
|
|
406
|
+
self.set_customer(record)
|
|
407
|
+
|
|
408
|
+
def remove_customer(self, id: str) -> bool:
|
|
409
|
+
return bool(self._call('policy.delete_customer', id))
|
|
410
|
+
|
|
411
|
+
def add_alt_id(self, existing: str, alt: str, event: bool = True) -> bool:
|
|
412
|
+
"""Add an alternative ID (Ex. a Stripe customer ID or API key) to an existing customer."""
|
|
413
|
+
return bool(self._call('policy.set_alt_customer_id', existing, alt, event))
|
|
414
|
+
|
|
415
|
+
def remove_alt_id(self, alt: str, event: bool = True) -> bool:
|
|
416
|
+
return bool(self._call('policy.delete_alt_customer_id', alt, event))
|
|
417
|
+
|
|
418
|
+
def create_customer_override(self, id: str, entitlement: str, value: Union[float, str, None] = None,
|
|
419
|
+
expires_on: Time = None, credit: Optional[str] = None, mode: Optional[str] = None,
|
|
420
|
+
increment: Union[float, str, None] = None, resets: Optional[bool] = None,
|
|
421
|
+
reset_inc: Union[float, str, None] = None, reset_sch: Optional[str] = None) -> Optional[str]:
|
|
422
|
+
"""Give a customer its own limit for an entitlement (replacing any it had). Returns the limit's node ID."""
|
|
423
|
+
return self._call('policy.create_customer_override', id, entitlement, _ms(expires_on), credit, mode,
|
|
424
|
+
_num(value), _num(increment), resets, _num(reset_inc), reset_sch)
|
|
425
|
+
|
|
426
|
+
def remove_customer_override(self, id: str, entitlement: str) -> bool:
|
|
427
|
+
return bool(self._call('policy.remove_customer_override', id, entitlement))
|
|
428
|
+
|
|
429
|
+
def give_entitlement(self, customer: str, entitlement: str, plan: Optional[str] = None, expires_on: Time = None) -> bool:
|
|
430
|
+
"""Give a customer an entitlement its plan doesn't have, defined by `plan` or the closest plan that has it."""
|
|
431
|
+
return bool(self._call('policy.give_entitlement', customer, entitlement, plan, _ms(expires_on)))
|
|
432
|
+
|
|
433
|
+
def take_entitlement(self, customer: str, entitlement: str, expires_on: Time = None) -> bool:
|
|
434
|
+
"""Take an entitlement away, even though the customer's plan has it. Meters are kept."""
|
|
435
|
+
return bool(self._call('policy.take_entitlement', customer, entitlement, _ms(expires_on)))
|
|
436
|
+
|
|
437
|
+
def restore_entitlement(self, customer: str, entitlement: str) -> bool:
|
|
438
|
+
"""Undo a give or take: the plan decides again."""
|
|
439
|
+
return bool(self._call('policy.restore_entitlement', customer, entitlement))
|
|
440
|
+
|
|
441
|
+
def set_customer_rules(self, customer: str, rules: List[str], event: bool = True) -> bool:
|
|
442
|
+
"""Set the policy's rules that apply to a customer, by name (an empty list clears them)."""
|
|
443
|
+
return bool(self._call('policy.set_customer_rules', customer, rules, event))
|
|
444
|
+
|
|
445
|
+
def entitlement_source(self, customer: str, entitlement: str) -> Optional[EntitlementSource]:
|
|
446
|
+
"""Where a customer's entitlement comes from, and whose meter it is."""
|
|
447
|
+
out = self._call('policy.entitlement_source', customer, entitlement)
|
|
448
|
+
if not out:
|
|
449
|
+
return None
|
|
450
|
+
return {'access': str(out.get('access') or ''), 'limit': out.get('limit'), 'customer': str(out.get('customer') or customer)}
|
|
451
|
+
|
|
452
|
+
def apply_customer_topup(self, id: str, topup: str) -> bool:
|
|
453
|
+
"""Grant a topup (by name) from the customer's plan."""
|
|
454
|
+
return bool(self._call('policy.apply_customer_topup', id, topup))
|
|
455
|
+
|
|
456
|
+
def remaining_credit(self, id: str, credit: str) -> Optional[float]:
|
|
457
|
+
"""Credit left in a customer's grants (for an entitlement's remaining, use remaining)."""
|
|
458
|
+
return self._call('policy.credit_remaining', id, credit)
|
|
459
|
+
|
|
460
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
461
|
+
# Spend caps and margins
|
|
462
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
463
|
+
|
|
464
|
+
def add_customer_cap(self, id: str, value: Union[float, str], cap_id: str = '', credit: str = 'rune',
|
|
465
|
+
exchangeable: Optional[bool] = None, ignore_grants: bool = False, overage_only: bool = False,
|
|
466
|
+
observe_only: bool = False, overhead_cost: bool = False, follow_decrements: bool = False,
|
|
467
|
+
scope: Optional[List[str]] = None, resets: bool = False, reset_inc: Optional[float] = None,
|
|
468
|
+
reset_sch: Optional[str] = None, expires_on: Time = None, send_events: bool = True,
|
|
469
|
+
hard_trailing: bool = False, shared: bool = False, shared_with: Optional[List[str]] = None) -> Optional[Cap]:
|
|
470
|
+
"""
|
|
471
|
+
Add a standing spend cap: a ceiling that only restricts (every cap that applies must have room). `credit`
|
|
472
|
+
defaults to 'rune' (USD-pegged): an umbrella cap over everything convertible to runes. `shared` applies it to
|
|
473
|
+
every customer referencing this one (Ex. an org budget). None when `cap_id` exists or `credit` is unknown.
|
|
474
|
+
"""
|
|
475
|
+
return self._call_record('policy.add_customer_cap', id, _num(value), cap_id, credit, exchangeable,
|
|
476
|
+
ignore_grants, overage_only, observe_only, overhead_cost, follow_decrements, scope,
|
|
477
|
+
resets, _num(reset_inc), reset_sch, _ms(expires_on), send_events, hard_trailing,
|
|
478
|
+
shared, shared_with)
|
|
479
|
+
|
|
480
|
+
def customer_cap(self, id: str, cap_id: str) -> Optional[Cap]:
|
|
481
|
+
return self._call_record('policy.customer_cap', id, cap_id)
|
|
482
|
+
|
|
483
|
+
def reset_customer_cap(self, id: str, cap_id: str, event: bool = True) -> bool:
|
|
484
|
+
"""Reset a cap's consumption to zero, keeping the cap."""
|
|
485
|
+
return bool(self._call('policy.reset_customer_cap', id, cap_id, event))
|
|
486
|
+
|
|
487
|
+
def remove_customer_cap(self, id: str, cap_id: str, event: bool = True) -> bool:
|
|
488
|
+
return bool(self._call('policy.remove_customer_cap', id, cap_id, event))
|
|
489
|
+
|
|
490
|
+
def start_margin_measurement(self, customer: str, cap_id: str, overage_only: bool = True,
|
|
491
|
+
ignore_grants: bool = True, credit: str = 'rune', exchangeable: bool = True) -> None:
|
|
492
|
+
"""Start measuring a customer's margin: two observe-only caps, what was charged and what it cost."""
|
|
493
|
+
self.add_customer_cap(customer, 0, cap_id=cap_id, credit=credit, exchangeable=exchangeable, observe_only=True,
|
|
494
|
+
overage_only=overage_only, ignore_grants=ignore_grants, send_events=False)
|
|
495
|
+
self.add_customer_cap(customer, 0, cap_id=cap_id + '_costs', credit=credit, exchangeable=exchangeable,
|
|
496
|
+
overhead_cost=True, observe_only=True, send_events=False)
|
|
497
|
+
|
|
498
|
+
def capture_margin_measurement(self, customer: str, cap_id: str, stop: bool = True) -> Optional[Record]:
|
|
499
|
+
"""What was charged and what it cost since start_margin_measurement, and the margin (stops it unless `stop` is False)."""
|
|
500
|
+
charged = self.customer_cap(customer, cap_id)
|
|
501
|
+
costs = self.customer_cap(customer, cap_id + '_costs')
|
|
502
|
+
result = None
|
|
503
|
+
if charged and costs:
|
|
504
|
+
charged_usd = charged['meter_value']
|
|
505
|
+
costs_usd = costs['meter_value']
|
|
506
|
+
margin = (charged_usd - costs_usd) / charged_usd if charged_usd > 0 else 0
|
|
507
|
+
result = {
|
|
508
|
+
'charged': round(charged_usd, 2), 'costs': round(costs_usd, 2), 'raw_margin': margin,
|
|
509
|
+
'margin': round(margin * 100, 2), 'charged_cap': charged, 'costs_cap': costs,
|
|
510
|
+
}
|
|
511
|
+
if stop:
|
|
512
|
+
self.remove_customer_cap(customer, cap_id, False)
|
|
513
|
+
self.remove_customer_cap(customer, cap_id + '_costs')
|
|
514
|
+
return result
|
|
515
|
+
|
|
516
|
+
def customer_margin_snapshot(self, customer: str) -> Optional[Dict[str, Any]]:
|
|
517
|
+
return self._call('policy.customer_local_margin_breakdown', customer)
|
|
518
|
+
|
|
519
|
+
def margin_snapshot(self, plan: str, entitlements: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
520
|
+
return self._call('policy.local_margin_breakdown', plan, entitlements)
|
|
521
|
+
|
|
522
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
523
|
+
# Notifications and capabilities
|
|
524
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
525
|
+
|
|
526
|
+
def set_notifications(self, contents: Union[str, bytes], format: str = 'stof') -> None:
|
|
527
|
+
self._call('policy.set_notifications', contents, format)
|
|
528
|
+
|
|
529
|
+
def capability(self, name: str) -> Optional[Record]:
|
|
530
|
+
return self._call_record('policy.capability', name)
|
|
531
|
+
|
|
532
|
+
def set_capabilities(self, contents: Union[str, bytes], format: str = 'stof') -> None:
|
|
533
|
+
self._call('policy.set_capabilities', contents, format)
|
|
534
|
+
|
|
535
|
+
def run_capability(self, name: str, args: Optional[Dict[str, Any]] = None, customer: Optional[str] = None) -> Any:
|
|
536
|
+
"""Run a capability and return its result. None when it doesn't exist or the customer can't use it."""
|
|
537
|
+
out = self._call('policy.run_capability_json', name, args or {}, customer)
|
|
538
|
+
return json.loads(out).get('result') if out else None
|
|
539
|
+
|
|
540
|
+
def claude_tools(self, customer: Optional[str] = None) -> List[Record]:
|
|
541
|
+
"""The policy's capabilities as Claude tools (only the customer's, when given)."""
|
|
542
|
+
out = self._call('policy.claude_tools', customer)
|
|
543
|
+
return json.loads(out).get('tools', []) if out else []
|
|
544
|
+
|
|
545
|
+
def claude_tool_use(self, tool_use: Union[str, Dict[str, Any]], customer: Optional[str] = None) -> Optional[Record]:
|
|
546
|
+
"""Run a Claude tool_use block against the capabilities; returns its tool_result, or None."""
|
|
547
|
+
source = tool_use if isinstance(tool_use, str) else json.dumps(tool_use)
|
|
548
|
+
out = self._call('policy.claude_tool_use', source, customer)
|
|
549
|
+
return json.loads(out) if out else None
|
|
550
|
+
|
|
551
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
552
|
+
# Entitlements and reads
|
|
553
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
554
|
+
|
|
555
|
+
def entitlement(self, id: str, entitlement: str) -> Optional[Record]:
|
|
556
|
+
"""An entitlement record, for a plan ID or customer ID."""
|
|
557
|
+
return self._call_record('policy.entitlement', id, entitlement)
|
|
558
|
+
|
|
559
|
+
def limit(self, id: str, entitlement: str, grants: bool = True) -> Optional[float]:
|
|
560
|
+
"""The limit, in the credit's units (with grants unless `grants` is False). A plan ID or customer ID."""
|
|
561
|
+
return self._call('policy.limit', id, entitlement, grants)
|
|
562
|
+
|
|
563
|
+
def limit_object(self, id: str, entitlement: str) -> Optional[Record]:
|
|
564
|
+
"""The limit that applies (a customer's own override, a rule's, or the plan's)."""
|
|
565
|
+
return self._call_record('policy.limit_obj', id, entitlement)
|
|
566
|
+
|
|
567
|
+
def meter_object(self, id: str, entitlement: str) -> Optional[Record]:
|
|
568
|
+
"""A customer's meter for an entitlement (the scope owner's for a scoped entitlement)."""
|
|
569
|
+
return self._call_record('policy.meter_obj', id, entitlement)
|
|
570
|
+
|
|
571
|
+
def remaining(self, customer: str, entitlement: str, percent: bool = False, grants: bool = True) -> Optional[float]:
|
|
572
|
+
"""limit - used, in the credit's units (negative past a soft limit)."""
|
|
573
|
+
return self._call('policy.remaining', customer, entitlement, percent, grants)
|
|
574
|
+
|
|
575
|
+
def allowance(self, customer: str, entitlement: str, grants: bool = True) -> Optional[float]:
|
|
576
|
+
"""What can be used right now: remaining, or less when a governor allows less. Size calls with it."""
|
|
577
|
+
return self._call('policy.allowance', customer, entitlement, grants)
|
|
578
|
+
|
|
579
|
+
def projected_exhaustion(self, customer: str, entitlement: str, smoothed: bool = False, grants: bool = True) -> Optional[float]:
|
|
580
|
+
"""When the customer runs out at the current rate (ms timestamp), or None."""
|
|
581
|
+
return self._call('policy.projected_exhaustion', customer, entitlement, smoothed, grants)
|
|
582
|
+
|
|
583
|
+
def rate(self, customer: str, entitlement: str) -> float:
|
|
584
|
+
"""Current consumption rate (units per ms)."""
|
|
585
|
+
return self._call('policy.rate', customer, entitlement) or 0
|
|
586
|
+
|
|
587
|
+
def acceleration(self, customer: str, entitlement: str) -> float:
|
|
588
|
+
"""Change in consumption rate (units per ms²)."""
|
|
589
|
+
return self._call('policy.acceleration', customer, entitlement) or 0
|
|
590
|
+
|
|
591
|
+
def value(self, customer: str, entitlement: str, percent: bool = False, grants: bool = True) -> Optional[float]:
|
|
592
|
+
"""Metered this period, in the credit's units."""
|
|
593
|
+
return self._call('policy.value', customer, entitlement, percent, grants)
|
|
594
|
+
|
|
595
|
+
def cost(self, id: str, entitlement: str) -> Optional[float]:
|
|
596
|
+
"""The limit's standard increment."""
|
|
597
|
+
return self._call('policy.cost', id, entitlement)
|
|
598
|
+
|
|
599
|
+
def resets(self, id: str, entitlement: str) -> Optional[float]:
|
|
600
|
+
"""When the meter resets (ms timestamp)."""
|
|
601
|
+
return self._call('policy.resets', id, entitlement)
|
|
602
|
+
|
|
603
|
+
def features(self, customer: str, context: Context = None) -> Optional[List[str]]:
|
|
604
|
+
"""
|
|
605
|
+
The entitlements a customer can use right now, by name (plan, less taken, plus given, each `enabled` rule on
|
|
606
|
+
for `context`). About access: a metered entitlement is listed even when used up (check answers that).
|
|
607
|
+
"""
|
|
608
|
+
return self._call('policy.features', customer, _context(context))
|
|
609
|
+
|
|
610
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
611
|
+
# Metering
|
|
612
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
613
|
+
|
|
614
|
+
def allow(self, customer: str, entitlement: str, value: Union[float, str] = 0, event: Event = True,
|
|
615
|
+
overhead: Optional[float] = None, force: bool = False, detail: bool = False) -> Union[bool, Decision]:
|
|
616
|
+
"""
|
|
617
|
+
Decide and meter: True (and the meter moves by `value`) when allowed. A feature-flag check when the
|
|
618
|
+
entitlement has no limit or `value` is 0. `value` can carry units in a string (Ex. '250MB').
|
|
619
|
+
|
|
620
|
+
- `event`: True, False (no events), or event data (a dict or string): sent with the events and the cost
|
|
621
|
+
function's context (Ex. `{'model': 'sonnet', 'input': 1200, 'output': 300}`).
|
|
622
|
+
- `overhead`: the call's real provider cost in runes, when you know it (overrides the cost function).
|
|
623
|
+
- `force`: record usage that already happened, even past a hard limit or cap.
|
|
624
|
+
- `detail`: return the Decision (allowed, reason, and where the customer stands) instead of a bool.
|
|
625
|
+
"""
|
|
626
|
+
out = self._call('policy.allow', customer, entitlement, _num(value), _event(event), None,
|
|
627
|
+
_num(overhead), force, detail)
|
|
628
|
+
return out if detail else bool(out)
|
|
629
|
+
|
|
630
|
+
def check(self, customer: str, entitlement: str, value: Union[float, str] = 0, context: Context = None,
|
|
631
|
+
overhead: Optional[float] = None, detail: bool = False) -> Union[bool, Decision]:
|
|
632
|
+
"""
|
|
633
|
+
The same decision as allow, changing nothing. Two checks can both pass when only one call fits: use
|
|
634
|
+
reserve when calls run at the same time. `detail` returns the Decision instead of a bool.
|
|
635
|
+
"""
|
|
636
|
+
out = self._call('policy.check', customer, entitlement, _num(value), None, _context(context),
|
|
637
|
+
_num(overhead), detail)
|
|
638
|
+
return out if detail else bool(out)
|
|
639
|
+
|
|
640
|
+
def increment(self, customer: str, entitlement: str, event: Event = True) -> bool:
|
|
641
|
+
"""allow with the limit's standard increment."""
|
|
642
|
+
return bool(self._call('policy.increment', customer, entitlement, _event(event)))
|
|
643
|
+
|
|
644
|
+
def decrement(self, customer: str, entitlement: str, event: Event = True) -> bool:
|
|
645
|
+
"""allow with minus the limit's standard increment."""
|
|
646
|
+
return bool(self._call('policy.decrement', customer, entitlement, _event(event)))
|
|
647
|
+
|
|
648
|
+
def check_increment(self, customer: str, entitlement: str) -> bool:
|
|
649
|
+
return bool(self._call('policy.check_increment', customer, entitlement))
|
|
650
|
+
|
|
651
|
+
def check_decrement(self, customer: str, entitlement: str) -> bool:
|
|
652
|
+
return bool(self._call('policy.check_decrement', customer, entitlement))
|
|
653
|
+
|
|
654
|
+
def set(self, customer: str, entitlement: str, value: float, event: bool = True) -> bool:
|
|
655
|
+
"""Move a meter to `value` (allows the difference). For accumulating usage, use allow."""
|
|
656
|
+
current = self.value(customer, entitlement)
|
|
657
|
+
return self.allow(customer, entitlement, value - current, event) if current is not None else False
|
|
658
|
+
|
|
659
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
660
|
+
# Reservations and estimates
|
|
661
|
+
# ------------------------------------------------------------------------------------------------------------
|
|
662
|
+
|
|
663
|
+
def reserve(self, customer: str, entitlement: str, value: Union[float, str, None] = None, context: Context = None,
|
|
664
|
+
basis: Optional[float] = None, segment: Optional[str] = None, ttl: Optional[float] = None,
|
|
665
|
+
quantile: float = 0.9, overhead: Optional[float] = None) -> Optional[str]:
|
|
666
|
+
"""
|
|
667
|
+
Hold room for a call before it runs (Ex. an LLM request), so concurrent calls can't overspend together.
|
|
668
|
+
Returns a hold ID, or None when the call wouldn't be allowed right now (counting every other hold). Leave
|
|
669
|
+
`value` unset to hold the predicted size (see estimate). A hold spends a governor's tokens like allow.
|
|
670
|
+
When the call finishes, settle it with the real usage, or release it if it never ran.
|
|
671
|
+
|
|
672
|
+
```python
|
|
673
|
+
hold = policy.reserve(user, 'chat', context={'model': model, 'input': input_tokens})
|
|
674
|
+
if not hold:
|
|
675
|
+
return deny()
|
|
676
|
+
res = call_model(...)
|
|
677
|
+
policy.settle(user, 'chat', hold, res.usage.total_tokens, {'model': model, 'input': input_tokens})
|
|
678
|
+
```
|
|
679
|
+
"""
|
|
680
|
+
return self._call('policy.reserve', customer, entitlement, _num(value), _context(context), _num(basis),
|
|
681
|
+
segment, _num(ttl), _num(quantile), _num(overhead))
|
|
682
|
+
|
|
683
|
+
def settle(self, customer: str, entitlement: str, hold: Optional[str], value: Union[float, str],
|
|
684
|
+
event: Event = True, overhead: Optional[float] = None, basis: Optional[float] = None,
|
|
685
|
+
segment: Optional[str] = None) -> bool:
|
|
686
|
+
"""
|
|
687
|
+
Finish a reserved call: drop the hold and record the real usage (even past a hard limit: it already
|
|
688
|
+
happened), then learn from it for future estimates. `event` and `overhead` work like allow.
|
|
689
|
+
"""
|
|
690
|
+
return bool(self._call('policy.settle', customer, entitlement, hold, _num(value), _event(event),
|
|
691
|
+
_num(overhead), _num(basis), segment))
|
|
692
|
+
|
|
693
|
+
def release(self, customer: str, entitlement: str, hold: str) -> bool:
|
|
694
|
+
"""Drop a hold without recording anything (the call never ran)."""
|
|
695
|
+
return bool(self._call('policy.release', customer, entitlement, hold))
|
|
696
|
+
|
|
697
|
+
def held(self, customer: str, entitlement: str) -> float:
|
|
698
|
+
"""Room held right now by reservations, in the credit's units."""
|
|
699
|
+
return self._call('policy.held', customer, entitlement) or 0
|
|
700
|
+
|
|
701
|
+
def estimate(self, customer: str, entitlement: str, context: Context = None, quantile: float = 0.9,
|
|
702
|
+
basis: Optional[float] = None, segment: Optional[str] = None) -> Optional[Estimate]:
|
|
703
|
+
"""
|
|
704
|
+
Predict one call before it runs: its value and provider overhead, from this customer's own usage once
|
|
705
|
+
there's enough of it, otherwise everyone's. None until something has been learned.
|
|
706
|
+
"""
|
|
707
|
+
return self._call('policy.estimate', customer, entitlement, _num(basis), segment, _num(quantile), _context(context))
|
|
708
|
+
|
|
709
|
+
def observe(self, customer: str, entitlement: str, value: Union[float, str], context: Context = None,
|
|
710
|
+
overhead: Optional[float] = None, basis: Optional[float] = None, segment: Optional[str] = None) -> bool:
|
|
711
|
+
"""Record one call's usage for estimates without reserving (settle does this for you)."""
|
|
712
|
+
return bool(self._call('policy.observe', customer, entitlement, _num(value), _num(overhead), _num(basis),
|
|
713
|
+
segment, _context(context)))
|
limitr/py.typed
ADDED
|
File without changes
|
limitr/types.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Copyright 2026 Formata, Inc. All rights reserved.
|
|
3
|
+
#
|
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
# you may not use this file except in compliance with the License.
|
|
6
|
+
# You may obtain a copy of the License at
|
|
7
|
+
#
|
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
#
|
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
# See the License for the specific language governing permissions and
|
|
14
|
+
# limitations under the License.
|
|
15
|
+
#
|
|
16
|
+
|
|
17
|
+
"""The shapes the Limitr engine returns, as typed dicts (the same fields as the TypeScript SDK's types)."""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import Any, Dict, List, Literal, Optional, TypedDict
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
DecisionReason = Literal[
|
|
25
|
+
'no_customer', # no such customer
|
|
26
|
+
'expired', # the customer's access has ended (set_customer_expires)
|
|
27
|
+
'not_entitled', # neither its plan, its gives, its rules, nor its refs have the entitlement
|
|
28
|
+
'taken', # taken from the customer (take_entitlement) or by one of its rules (`access` says which)
|
|
29
|
+
'no_scope', # the entitlement is scoped to a customer type with none up the customer's refs
|
|
30
|
+
'disabled', # the entitlement's `enabled` said no for this call (Ex. a rollout or kill switch)
|
|
31
|
+
'cap', # a spend cap has no room (`cap` and `cap_customer` name it)
|
|
32
|
+
'governor', # the rate governor hasn't refilled enough (`available` says how much it has)
|
|
33
|
+
'limit', # a hard limit, with no grants left to cover the rest
|
|
34
|
+
'held', # the call fits on its own, but room held by reservations doesn't leave enough
|
|
35
|
+
]
|
|
36
|
+
"""Why a call was refused (a decision's `reason`)."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Decision(TypedDict, total=False):
|
|
40
|
+
"""
|
|
41
|
+
What allow() or check() decided and why (with `detail=True`), and where the customer stands: after the call for
|
|
42
|
+
allow(), as things are for check(). Values are in the credit's units. Fields that don't apply are None (Ex. a
|
|
43
|
+
feature flag has no credit, limit, or remaining).
|
|
44
|
+
"""
|
|
45
|
+
allowed: bool
|
|
46
|
+
reason: Optional[DecisionReason]
|
|
47
|
+
customer: str # whose meter it is (Ex. the org's for an entitlement scoped to 'org')
|
|
48
|
+
entitlement: str
|
|
49
|
+
value: float # the call's value
|
|
50
|
+
credit: Optional[str]
|
|
51
|
+
mode: Optional[Literal['hard', 'soft', 'observe']]
|
|
52
|
+
used: Optional[float] # metered this period
|
|
53
|
+
limit: Optional[float] # the limit, including grants
|
|
54
|
+
remaining: Optional[float]
|
|
55
|
+
allowance: Optional[float] # what can be used right now (less when a governor allows less)
|
|
56
|
+
held: float # room held by reservations
|
|
57
|
+
resets: Optional[float] # when the meter resets (ms timestamp)
|
|
58
|
+
access: Optional[str] # 'plan', 'given', 'taken', 'rule:<name>', 'ref:<id>', 'default'
|
|
59
|
+
limit_source: Optional[str] # 'override', 'rule:<name>', 'plan', or None
|
|
60
|
+
cap: str # reason 'cap': the cap's ID
|
|
61
|
+
cap_customer: str # reason 'cap': the customer holding it
|
|
62
|
+
available: float # reason 'governor': how much the governor has available
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class EntitlementSource(TypedDict):
|
|
66
|
+
"""Where a customer's entitlement comes from (entitlement_source)."""
|
|
67
|
+
access: str
|
|
68
|
+
limit: Optional[str]
|
|
69
|
+
customer: str
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Estimate(TypedDict):
|
|
73
|
+
"""A predicted call (estimate)."""
|
|
74
|
+
value: float # predicted usage for one call, in the credit's units
|
|
75
|
+
overhead: float # predicted provider overhead for one call, in runes (typically USD)
|
|
76
|
+
samples: int # observations behind the estimate
|
|
77
|
+
source: str # 'local' (learned in this engine) or 'cloud' (seeded or pooled by Limitr Cloud)
|
|
78
|
+
scope: str # 'customer' (this customer's own usage) or 'policy' (everyone's)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
Customer = Dict[str, Any]
|
|
82
|
+
"""A customer record: id, plan, alt_ids, refs, type, label, meters, overrides, given, taken, rules, grants, caps,
|
|
83
|
+
metadata, period_start, period_end, expires."""
|
|
84
|
+
|
|
85
|
+
Cap = Dict[str, Any]
|
|
86
|
+
"""A standing spend cap: id, credit, value, meter_value, exchangeable, ignore_grants, overage_only, observe_only,
|
|
87
|
+
overhead_cost, follow_decrements, hard_trailing, shared, shared_with, scope, resets, reset_inc, reset_sch, ..."""
|
|
88
|
+
|
|
89
|
+
Record = Dict[str, Any]
|
|
90
|
+
EventHandler = Any
|
|
91
|
+
"""An event handler: `handler(name: str, value: Any)`. Objects arrive as dicts."""
|
|
92
|
+
|
|
93
|
+
__all__ = ['DecisionReason', 'Decision', 'EntitlementSource', 'Estimate', 'Customer', 'Cap', 'Record', 'EventHandler', 'List']
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: limitr
|
|
3
|
+
Version: 0.8.6
|
|
4
|
+
Summary: Limits, credits, and billing inside your AI product: an open-source engine that decides what each customer can do, what it costs you, and what to bill, on every call, in-process.
|
|
5
|
+
Author-email: "Formata, Inc." <info@limitr.dev>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://limitr.dev
|
|
8
|
+
Project-URL: Documentation, https://limitr.dev/docs/introduction
|
|
9
|
+
Project-URL: Repository, https://github.com/dev-formata-io/limitr
|
|
10
|
+
Project-URL: Issues, https://github.com/dev-formata-io/limitr/issues
|
|
11
|
+
Keywords: usage-based-billing,usage-based-pricing,entitlements,metering,feature-flags,rate-limiting,llm,ai-agents,credits
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
15
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: stof<0.12,>=0.11.4
|
|
21
|
+
Provides-Extra: test
|
|
22
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# Limitr for Python
|
|
26
|
+
|
|
27
|
+
Usage and margin control for AI products: limits, credits, and billing decided inside your app. Limitr is an
|
|
28
|
+
open-source engine that runs in-process and decides every call for each customer: what they can do, what it costs
|
|
29
|
+
you, and what to bill. Plans, credits, limits, costs, and contract terms live in one policy, so changing pricing is a
|
|
30
|
+
policy change, not a migration.
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
pip install limitr
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Quick start
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from limitr import Limitr
|
|
40
|
+
|
|
41
|
+
policy = Limitr("""
|
|
42
|
+
policy: {
|
|
43
|
+
credits: {
|
|
44
|
+
request: { label: 'Request' }
|
|
45
|
+
ai_token: { label: 'AI token', price: { amount: 0.00002 } }
|
|
46
|
+
}
|
|
47
|
+
plans: {
|
|
48
|
+
free: {
|
|
49
|
+
default: true
|
|
50
|
+
entitlements: {
|
|
51
|
+
api: { limit: { credit: 'request', mode: 'hard', value: 1000, resets: true } }
|
|
52
|
+
chat: { limit: { credit: 'ai_token', mode: 'hard', value: 100_000, resets: true } }
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
""")
|
|
58
|
+
|
|
59
|
+
policy.ensure_customer('ada')
|
|
60
|
+
|
|
61
|
+
if policy.allow('ada', 'api', 1): # decide and count
|
|
62
|
+
...
|
|
63
|
+
|
|
64
|
+
d = policy.check('ada', 'api', 5000, detail=True)
|
|
65
|
+
if not d['allowed']:
|
|
66
|
+
print(d['reason'], d['remaining'], d['resets']) # Ex. 'limit' 999 1796083200000
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Policies can also be YAML, JSON, or TOML (`Limitr(text, 'yaml')`) or a dict.
|
|
70
|
+
|
|
71
|
+
## LLM calls: reserve, then settle
|
|
72
|
+
|
|
73
|
+
A call's size is only known when it's done, and calls run at the same time. Hold room first, then record what the call
|
|
74
|
+
really used:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
hold = policy.reserve('ada', 'chat', 4096) # or leave the value out to hold the predicted size
|
|
78
|
+
if not hold:
|
|
79
|
+
return 'out of tokens'
|
|
80
|
+
res = client.messages.create(model=model, max_tokens=4096, messages=messages)
|
|
81
|
+
policy.settle('ada', 'chat', hold, res.usage.input_tokens + res.usage.output_tokens,
|
|
82
|
+
{'model': model, 'input': res.usage.input_tokens, 'output': res.usage.output_tokens})
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Events and state
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
policy.add_handler('billing', lambda name, event: print(name, event)) # objects arrive as dicts
|
|
89
|
+
|
|
90
|
+
saved = policy.customers() # all customer state: store it anywhere
|
|
91
|
+
restored = Limitr(policy_source)
|
|
92
|
+
restored.load_customers(saved)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Event handlers run during the call that sent the event, so don't call the policy from one; queue the work instead.
|
|
96
|
+
|
|
97
|
+
## Notes
|
|
98
|
+
|
|
99
|
+
- Every method is one engine call, run one at a time (a lock guards the document), so a single `allow` is safe across
|
|
100
|
+
threads. Use `reserve` and `settle` when concurrent calls must not overspend together.
|
|
101
|
+
- Method names match the TypeScript SDK in snake_case (`ensureCustomer` is `ensure_customer`), and options are
|
|
102
|
+
keyword arguments (`allow(customer, entitlement, value, detail=True)`).
|
|
103
|
+
- This release is the engine. Limitr Cloud (live policy changes, ledgers, invoices, Limitr Analyst) comes next.
|
|
104
|
+
|
|
105
|
+
Docs: [limitr.dev](https://limitr.dev). Policy semantics: the [policy reference](https://limitr.dev/docs/reference/policy).
|
|
106
|
+
Source: [github.com/dev-formata-io/limitr](https://github.com/dev-formata-io/limitr). Apache 2.0.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
limitr/__init__.py,sha256=ASnogti1bqE5EGPhadMK2rPW2d5zeXNUtpjUBfyE0t8,951
|
|
2
|
+
limitr/engine.bstf,sha256=EbGLRV4gPHPF72UcyAnfYaKZjYxlYcXH7k10ypu5qao,895040
|
|
3
|
+
limitr/engine.py,sha256=4bokq1fbhMfy9CurNytVYZXZoYiTXKnfZxuF_UveLms,39067
|
|
4
|
+
limitr/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
limitr/types.py,sha256=70N3O1SvhlwYTgegJ3_5CwRYfa1TfSfWzbDzb4vviWo,4536
|
|
6
|
+
limitr-0.8.6.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
7
|
+
limitr-0.8.6.dist-info/METADATA,sha256=EOf0MzywKLd2DMFLUtJWeuMgKxjB6GfILvkGpugWS_g,4166
|
|
8
|
+
limitr-0.8.6.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
limitr-0.8.6.dist-info/top_level.txt,sha256=d8ZMFDc3WR0Pr4uH20d8zCEFx98Rd4P1aPfOYWDQ7q0,7
|
|
10
|
+
limitr-0.8.6.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
limitr
|