tensorcost-litellm 0.1.5__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.
@@ -0,0 +1,47 @@
1
+ """TensorCost for the LiteLLM proxy.
2
+
3
+ - ``TensorCostAdmit``: a pre-call guardrail that asks TensorCost whether each
4
+ call may go ahead, and follows a refusal or a reroute.
5
+ - ``spend_logger``: the callback instance that pushes each call's spend row
6
+ back to TensorCost. LiteLLM's ``callbacks`` setting takes an instance, so
7
+ config names this one (``tensorcost_litellm.spend_logger``).
8
+ - ``budget_sync``: sets a LiteLLM team's ``max_budget`` from a TensorCost
9
+ budget's room, so LiteLLM refuses on its own if TensorCost can't be reached.
10
+
11
+ The guardrail and the logger import LiteLLM's proxy classes (and so FastAPI),
12
+ which only exist inside the LiteLLM proxy. ``budget_sync`` is a standalone CLI
13
+ that needs only httpx, and importing any submodule runs this file first, so
14
+ the proxy-side names load lazily, on first use, not at import.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any
20
+
21
+ from ._shared import VERSION
22
+
23
+ __all__ = ["TensorCostAdmit", "TensorCostSpendLogger", "provably_never_billed", "spend_logger"]
24
+ __version__ = VERSION
25
+
26
+ _spend_logger: Any = None
27
+
28
+
29
+ def __getattr__(name: str) -> Any:
30
+ global _spend_logger
31
+ if name in ("TensorCostAdmit", "provably_never_billed"):
32
+ from . import guardrail
33
+
34
+ return getattr(guardrail, name)
35
+ if name == "TensorCostSpendLogger":
36
+ from .logger import TensorCostSpendLogger
37
+
38
+ return TensorCostSpendLogger
39
+ if name == "spend_logger":
40
+ # The instance litellm_settings.callbacks names. It reads TENSORCOST_URL
41
+ # and TENSORCOST_GATEWAY_KEY when it first pushes. One per process.
42
+ if _spend_logger is None:
43
+ from .logger import TensorCostSpendLogger
44
+
45
+ _spend_logger = TensorCostSpendLogger()
46
+ return _spend_logger
47
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,306 @@
1
+ """Settings, the call registry and the HTTP helpers both hooks share."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import threading
7
+ import time
8
+ from dataclasses import dataclass
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ #: The request-metadata key the guardrail stamps with the call's correlation id.
12
+ #: TensorCost's log parser reads it from each row's metadata.
13
+ CORRELATION_METADATA_KEY = "tensorcost_correlation_id"
14
+
15
+ #: The request-metadata key a caller names the end customer under, the LiteLLM
16
+ #: side of the SDK's x-tc-customer. The guardrail sends it to admit and the
17
+ #: logger copies it into each row's metadata, where TensorCost's parser reads it.
18
+ CUSTOMER_METADATA_KEY = "tensorcost_customer"
19
+
20
+ #: The longest customer id TensorCost keeps; a longer one is left off.
21
+ MAX_CUSTOMER = 128
22
+
23
+ #: The header an SDK or proxied call names its application with, passed
24
+ #: through LiteLLM by a caller who sets it.
25
+ APPLICATION_HEADER = "x-tc-application"
26
+ #: The request-metadata key a caller names the application under, the
27
+ #: LiteLLM side of x-tc-application. The logger copies the resolved value
28
+ #: into each row's metadata under this key, where TensorCost's parser reads it.
29
+ APPLICATION_METADATA_KEY = "tensorcost_application"
30
+ #: The longest application name the gateway admit API accepts.
31
+ MAX_APPLICATION = 256
32
+
33
+ #: The plugin's version, which every request to TensorCost names in its User-Agent.
34
+ VERSION = "0.1.5"
35
+ USER_AGENT = f"TensorCost-LiteLLM/{VERSION}"
36
+
37
+ URL_ENV = "TENSORCOST_URL"
38
+ KEY_ENV = "TENSORCOST_GATEWAY_KEY"
39
+
40
+ _ENV_PREFIX = "os.environ/"
41
+
42
+
43
+ def resolve_setting(value: Optional[str], env_name: str) -> Optional[str]:
44
+ """A config value, an ``os.environ/NAME`` reference, or the default env var."""
45
+ if isinstance(value, str) and value.startswith(_ENV_PREFIX):
46
+ value = os.environ.get(value[len(_ENV_PREFIX):])
47
+ if not value:
48
+ value = os.environ.get(env_name)
49
+ if isinstance(value, str):
50
+ value = value.strip()
51
+ return value or None
52
+
53
+
54
+ def base_url(value: Optional[str]) -> Optional[str]:
55
+ url = resolve_setting(value, URL_ENV)
56
+ return url.rstrip("/") if url else None
57
+
58
+
59
+ @dataclass
60
+ class CallRecord:
61
+ """What the guardrail knows about one call, for the logger and the cancel."""
62
+
63
+ correlation_id: str
64
+ #: The admit decision this call ran under. None when a cached allow let
65
+ #: it through: that decision belongs to another call and is never cancelled.
66
+ decision_id: Optional[str]
67
+ created: float
68
+ #: id() of the request dict the guardrail admitted. The failure hook acts
69
+ #: only for that same dict, so a caller who puts another call's
70
+ #: correlation id in their own request's metadata can't reach its record.
71
+ request_ref: Optional[int] = None
72
+ #: The proxy reported the request's final failure (the failure hook ran).
73
+ final_failed: bool = False
74
+ #: A row carrying this correlation id has been queued. Only one row per
75
+ #: call ever carries it, so admit's estimate is booked at most once.
76
+ correlation_sent: bool = False
77
+
78
+
79
+ class CallRegistry:
80
+ """Calls the guardrail admitted, by the correlation id it minted, for 30 minutes.
81
+
82
+ Never keyed by LiteLLM's call id: a client sets that with the
83
+ x-litellm-call-id header. Bounded, so a burst can't grow it without limit.
84
+ """
85
+
86
+ def __init__(self, ttl_seconds: float = 1800.0, max_entries: int = 50_000) -> None:
87
+ self._ttl = ttl_seconds
88
+ self._max = max_entries
89
+ self._items: Dict[str, CallRecord] = {}
90
+ self._lock = threading.Lock()
91
+
92
+ def put(self, record: CallRecord) -> None:
93
+ call_id = record.correlation_id
94
+ with self._lock:
95
+ if len(self._items) >= self._max:
96
+ self._evict(time.monotonic())
97
+ while len(self._items) >= self._max:
98
+ self._items.pop(next(iter(self._items)))
99
+ self._items[call_id] = record
100
+
101
+ def get(self, call_id: Optional[str]) -> Optional[CallRecord]:
102
+ if not call_id:
103
+ return None
104
+ with self._lock:
105
+ record = self._items.get(call_id)
106
+ if record is None:
107
+ return None
108
+ if time.monotonic() - record.created > self._ttl:
109
+ self._items.pop(call_id, None)
110
+ return None
111
+ return record
112
+
113
+ def _evict(self, now: float) -> None:
114
+ stale = [k for k, r in self._items.items() if now - r.created > self._ttl]
115
+ for k in stale:
116
+ self._items.pop(k, None)
117
+
118
+ def clear(self) -> None:
119
+ with self._lock:
120
+ self._items.clear()
121
+
122
+
123
+ #: One registry per process: the guardrail writes it, the logger reads it.
124
+ calls = CallRegistry()
125
+
126
+
127
+ def stamped_correlation_id(container: Any) -> Optional[str]:
128
+ """The correlation id the guardrail stamped on a request's metadata (never requester_metadata)."""
129
+ if not isinstance(container, dict):
130
+ return None
131
+ for key in ("litellm_metadata", "metadata"):
132
+ md = container.get(key)
133
+ if isinstance(md, dict):
134
+ value = text(md.get(CORRELATION_METADATA_KEY), 200)
135
+ if value:
136
+ return value
137
+ return None
138
+
139
+
140
+ def request_customer(container: Any) -> Optional[str]:
141
+ """The end customer a caller named in the request's metadata, or None.
142
+
143
+ Read from ``metadata`` or ``litellm_metadata`` and, failing those, from the
144
+ caller's own copy LiteLLM keeps under ``requester_metadata``. Trimmed, at
145
+ most 128 characters and with no control characters, as TensorCost keeps it.
146
+ """
147
+ if not isinstance(container, dict):
148
+ return None
149
+ found: Optional[Any] = None
150
+ for key in ("litellm_metadata", "metadata"):
151
+ md = container.get(key)
152
+ if not isinstance(md, dict):
153
+ continue
154
+ for source in (md, md.get("requester_metadata")):
155
+ if isinstance(source, dict) and source.get(CUSTOMER_METADATA_KEY) is not None:
156
+ found = source.get(CUSTOMER_METADATA_KEY)
157
+ break
158
+ if found is not None:
159
+ break
160
+ value = text(found, MAX_CUSTOMER)
161
+ if value is None or any(ord(ch) < 32 or ord(ch) == 127 for ch in value):
162
+ return None
163
+ return value
164
+
165
+
166
+ def request_application(
167
+ container: Any,
168
+ tags: Optional[List[Any]] = None,
169
+ end_user: Any = None,
170
+ key_alias: Any = None,
171
+ ) -> Optional[str]:
172
+ """The application a call is for, the same way at admit and on its spend row.
173
+
174
+ First of: the x-tc-application header the caller sent through LiteLLM;
175
+ ``tensorcost_application`` in the request's metadata (or the caller's own
176
+ copy under ``requester_metadata``); an ``application=`` or ``app=`` tag
177
+ (``:`` works too); LiteLLM's end user (the body's ``user``); the key's
178
+ alias. The last three are the order TensorCost's parser already used for a
179
+ row's application, so a row from an older logger reads the same.
180
+ ``container`` is the request dict at admit, ``litellm_params`` at log time.
181
+ """
182
+ for value in (_header(container, APPLICATION_HEADER), _metadata_value(container, APPLICATION_METADATA_KEY)):
183
+ found = _label(value, MAX_APPLICATION)
184
+ if found:
185
+ return found
186
+ for key in ("application", "app"):
187
+ for tag in tags or []:
188
+ if not isinstance(tag, str):
189
+ continue
190
+ lower = tag.strip().lower()
191
+ for sep in ("=", ":"):
192
+ if lower.startswith(key + sep):
193
+ found = _label(tag.strip()[len(key) + 1 :], MAX_APPLICATION)
194
+ if found:
195
+ return found
196
+ for value in (end_user, key_alias):
197
+ found = _label(value, MAX_APPLICATION)
198
+ if found:
199
+ return found
200
+ return None
201
+
202
+
203
+ def _header(container: Any, name: str) -> Any:
204
+ """A request header LiteLLM kept, by name in any case (proxy_server_request, then metadata)."""
205
+ if not isinstance(container, dict):
206
+ return None
207
+ sources = [(container.get("proxy_server_request") or {}).get("headers") if isinstance(container.get("proxy_server_request"), dict) else None]
208
+ for key in ("litellm_metadata", "metadata"):
209
+ md = container.get(key)
210
+ if isinstance(md, dict):
211
+ sources.append(md.get("headers"))
212
+ for headers in sources:
213
+ if isinstance(headers, dict):
214
+ for k, v in headers.items():
215
+ if isinstance(k, str) and k.lower() == name:
216
+ return v
217
+ return None
218
+
219
+
220
+ def _metadata_value(container: Any, name: str) -> Any:
221
+ if not isinstance(container, dict):
222
+ return None
223
+ for key in ("litellm_metadata", "metadata"):
224
+ md = container.get(key)
225
+ if not isinstance(md, dict):
226
+ continue
227
+ for source in (md, md.get("requester_metadata")):
228
+ if isinstance(source, dict) and source.get(name) is not None:
229
+ return source.get(name)
230
+ return None
231
+
232
+
233
+ def _label(value: Any, limit: int) -> Optional[str]:
234
+ """text(), and nothing with a control character in it."""
235
+ found = text(value, limit)
236
+ if found is None or any(ord(ch) < 32 or ord(ch) == 127 for ch in found):
237
+ return None
238
+ return found
239
+
240
+
241
+ def auth_headers(key: str) -> Dict[str, str]:
242
+ # The plugin's own User-Agent rather than httpx's: TensorCost's edge can
243
+ # tell its traffic apart, and a request never arrives without one.
244
+ return {"authorization": f"Bearer {key}", "content-type": "application/json", "accept": "application/json", "user-agent": USER_AGENT}
245
+
246
+
247
+ def text(value: Any, limit: int = 256) -> Optional[str]:
248
+ """A trimmed non-empty string no longer than ``limit``, else None."""
249
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
250
+ value = str(value)
251
+ if not isinstance(value, str):
252
+ return None
253
+ value = value.strip()
254
+ if not value or len(value) > limit:
255
+ return None
256
+ return value
257
+
258
+
259
+ def non_negative_int(value: Any) -> Optional[int]:
260
+ if isinstance(value, bool):
261
+ return None
262
+ if isinstance(value, int):
263
+ return value if value >= 0 else None
264
+ if isinstance(value, float) and value.is_integer() and value >= 0:
265
+ return int(value)
266
+ if isinstance(value, str) and value.strip().isdigit():
267
+ return int(value.strip())
268
+ return None
269
+
270
+
271
+ def base_model(litellm_params: Any, model_info: Any = None) -> Optional[str]:
272
+ """The model a deployment bills as, when its config names one (``base_model``).
273
+
274
+ Azure deployments carry names of the customer's own ("prod-mini-deploy"),
275
+ so LiteLLM's Azure docs ask for ``base_model`` ("azure/gpt-4o-mini") to
276
+ price them. Read as LiteLLM 1.108.9 reads it for cost
277
+ (litellm.utils.get_base_model_from_metadata): ``litellm_params.base_model``
278
+ first, then the deployment's ``model_info.base_model``. Pass the call's
279
+ ``model_info`` (from a model_list entry); without one, the call's own
280
+ ``litellm_params.metadata`` and ``litellm_metadata`` are searched for it,
281
+ where LiteLLM's router puts the deployment's model_info on each call.
282
+ """
283
+ found = text(_get_field(litellm_params, "base_model"))
284
+ if found:
285
+ return found
286
+ infos = [model_info] if model_info is not None else [
287
+ _get_field(_get_field(litellm_params, key), "model_info") for key in ("metadata", "litellm_metadata")
288
+ ]
289
+ for info in infos:
290
+ found = text(_get_field(info, "base_model"))
291
+ if found:
292
+ return found
293
+ return None
294
+
295
+
296
+ def without_provider_prefix(model: str, provider: Optional[str]) -> str:
297
+ """LiteLLM's routing prefix taken off: "azure/gpt-4o-mini" under azure is "gpt-4o-mini"."""
298
+ if provider and model.lower().startswith(provider.lower() + "/"):
299
+ return model[len(provider) + 1 :] or model
300
+ return model
301
+
302
+
303
+ def _get_field(obj: Any, name: str) -> Any:
304
+ if isinstance(obj, dict):
305
+ return obj.get(name)
306
+ return getattr(obj, name, None) if obj is not None else None
@@ -0,0 +1,315 @@
1
+ """Set a LiteLLM team's ``max_budget`` from a TensorCost budget's room.
2
+
3
+ The guardrail asks TensorCost before every call. A team budget pushed down
4
+ into LiteLLM as well keeps holding when TensorCost can't be reached: LiteLLM
5
+ refuses the team's calls on its own once its spend reaches ``max_budget``.
6
+
7
+ TensorCost's quota-sync job does this push for a connection whose LiteLLM
8
+ admin URL and key are stored in TensorCost. This module is the same push
9
+ for anyone who would rather keep the admin key on their side and run it
10
+ themselves.
11
+
12
+ The push:
13
+
14
+ 1. ``GET /team/info?team_id=...`` reads the team's ``spend`` and current
15
+ ``max_budget``. If the answer has neither field, this LiteLLM names them
16
+ differently and nothing is changed: the result is ``unsupported``.
17
+ 2. The new ``max_budget`` is the team's LiteLLM spend plus the room left on
18
+ the TensorCost budget, in dollars, rounded down to the cent. Counting from
19
+ LiteLLM's own spend means the limit holds whatever LiteLLM's budget reset
20
+ schedule is. It is never above the team's own limit: the push only ever
21
+ tightens. The team's own limit is the one it had before the first push.
22
+ 3. On a first push, that own limit is saved (``save_original``; the CLI's
23
+ state file) before anything is changed. An update whose answer is lost
24
+ may still have landed, and the team's own limit would go with it. If it
25
+ can't be saved, nothing is sent. A saved limit is never replaced; later
26
+ pushes pass it back as ``original_max_budget``, and only a restore
27
+ (``restore_team_budget``, ``--restore``) clears it.
28
+ 4. ``POST /team/update`` with ``team_id`` and ``max_budget``. The push counts
29
+ only when LiteLLM's answer, or a second read of the team, carries the new
30
+ ``max_budget`` back.
31
+
32
+ Field names are from LiteLLM's ``team_endpoints.py`` (``/team/update`` takes
33
+ ``UpdateTeamRequest`` with ``team_id`` and ``max_budget`` and answers
34
+ ``{"team_id", "data"}``). The check in step 1 and 3 is there because they
35
+ weren't confirmed against every LiteLLM release.
36
+
37
+ Usage::
38
+
39
+ LITELLM_URL=https://litellm.example.com LITELLM_ADMIN_KEY=sk-... \\
40
+ python -m tensorcost_litellm.budget_sync --team-id search --room-usd 412.50
41
+
42
+ # when the TensorCost budget no longer covers the team:
43
+ python -m tensorcost_litellm.budget_sync --team-id search --restore
44
+
45
+ The CLI keeps each team's own limit in a JSON state file
46
+ (``--state-file``, default ``tensorcost-budget-sync.json`` in the working
47
+ directory). Keep that file: it is how a restore knows what to put back.
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import argparse
53
+ import json
54
+ import math
55
+ import os
56
+ import sys
57
+ from dataclasses import asdict, dataclass
58
+ import tempfile
59
+ from typing import Any, Callable, Dict, Optional, Union
60
+
61
+ import httpx
62
+
63
+ TIMEOUT_SECONDS = 10.0
64
+
65
+
66
+ class _Unset:
67
+ pass
68
+
69
+
70
+ #: "Not given": the team's current max_budget is taken as its own limit (a first push).
71
+ UNSET = _Unset()
72
+
73
+
74
+ @dataclass
75
+ class PushResult:
76
+ #: pushed, failed or unsupported.
77
+ status: str
78
+ max_budget: Optional[float] = None
79
+ #: The team's max_budget before this push (None: it had none).
80
+ prior_max_budget: Optional[float] = None
81
+ error: Optional[str] = None
82
+
83
+
84
+ def plan_max_budget(team_spend_usd: float, room_usd: float, ceiling: Optional[float] = None) -> float:
85
+ """LiteLLM spend plus the room, rounded down to the cent; never below the spend, never above the team's own limit."""
86
+ room = max(0.0, room_usd)
87
+ want = math.floor((team_spend_usd + room) * 100 + 1e-6) / 100
88
+ return want if ceiling is None else min(want, ceiling)
89
+
90
+
91
+ def push_team_budget(
92
+ base_url: str,
93
+ admin_key: str,
94
+ team_id: str,
95
+ room_usd: float,
96
+ client: Optional[httpx.Client] = None,
97
+ original_max_budget: Union[float, None, _Unset] = UNSET,
98
+ save_original: Optional[Callable[[Optional[float]], None]] = None,
99
+ ) -> PushResult:
100
+ """Push the room. On a first push (no ``original_max_budget``), ``save_original``
101
+ is called with the team's own limit before any update, and must have stored it."""
102
+ own = client is None
103
+ http = client or httpx.Client(timeout=TIMEOUT_SECONDS)
104
+ try:
105
+ return _push(http, base_url.rstrip("/"), admin_key, team_id, room_usd, original_max_budget, save_original)
106
+ finally:
107
+ if own:
108
+ http.close()
109
+
110
+
111
+ def restore_team_budget(base_url: str, admin_key: str, team_id: str, original: Optional[float], client: Optional[httpx.Client] = None) -> PushResult:
112
+ """Put the team's own limit back (None: no limit)."""
113
+ own = client is None
114
+ http = client or httpx.Client(timeout=TIMEOUT_SECONDS)
115
+ try:
116
+ return _set(http, base_url.rstrip("/"), {"authorization": f"Bearer {admin_key}", "content-type": "application/json"}, team_id, original, original)
117
+ finally:
118
+ if own:
119
+ http.close()
120
+
121
+
122
+ def _push(
123
+ http: httpx.Client,
124
+ base: str,
125
+ key: str,
126
+ team_id: str,
127
+ room_usd: float,
128
+ original: Union[float, None, _Unset],
129
+ save_original: Optional[Callable[[Optional[float]], None]],
130
+ ) -> PushResult:
131
+ headers = {"authorization": f"Bearer {key}", "content-type": "application/json"}
132
+ try:
133
+ res = http.get(f"{base}/team/info", params={"team_id": team_id}, headers=headers)
134
+ except httpx.HTTPError as err:
135
+ return PushResult("failed", error=f"couldn't reach LiteLLM ({type(err).__name__})")
136
+ failed = _failure(res, team_id)
137
+ if failed:
138
+ return failed
139
+ info = _json(res)
140
+ team = info.get("team_info") if isinstance(info, dict) else None
141
+ if not isinstance(team, dict) or "spend" not in team or "max_budget" not in team:
142
+ return PushResult("unsupported", error="LiteLLM's /team/info answer has no team_info.spend or team_info.max_budget")
143
+ spend = team.get("spend")
144
+ spend = 0.0 if spend is None else spend
145
+ prior = team.get("max_budget")
146
+ if not _is_number(spend) or (prior is not None and not _is_number(prior)):
147
+ return PushResult("unsupported", error="LiteLLM's team spend or max_budget isn't a number")
148
+ prior_f = None if prior is None else float(prior)
149
+ ceiling = prior_f if isinstance(original, _Unset) else original
150
+ target = plan_max_budget(float(spend), room_usd, ceiling)
151
+ if prior_f is not None and abs(prior_f - target) < 0.005:
152
+ return PushResult("pushed", max_budget=target, prior_max_budget=prior_f)
153
+ if isinstance(original, _Unset) and save_original is not None:
154
+ try:
155
+ save_original(prior_f)
156
+ except Exception as err:
157
+ return PushResult("failed", prior_max_budget=prior_f, error=f"couldn't save the team's own limit first, so nothing was pushed ({type(err).__name__})")
158
+ return _set(http, base, headers, team_id, target, prior_f)
159
+
160
+
161
+ def _set(http: httpx.Client, base: str, headers: dict, team_id: str, target: Optional[float], prior_f: Optional[float]) -> PushResult:
162
+ try:
163
+ res = http.post(f"{base}/team/update", json={"team_id": team_id, "max_budget": target}, headers=headers)
164
+ except httpx.HTTPError as err:
165
+ return PushResult("failed", prior_max_budget=prior_f, error=f"couldn't reach LiteLLM ({type(err).__name__})")
166
+ if res.status_code == 422:
167
+ return PushResult("unsupported", prior_max_budget=prior_f, error="LiteLLM's /team/update rejected the max_budget field (422)")
168
+ failed = _failure(res, team_id)
169
+ if failed:
170
+ failed.prior_max_budget = prior_f
171
+ return failed
172
+ body = _json(res)
173
+ data = body.get("data") if isinstance(body, dict) else None
174
+ echoed = data.get("max_budget") if isinstance(data, dict) else None
175
+ if not _same(echoed, target):
176
+ # Some releases answer without the row: read the team again before
177
+ # saying the push didn't take.
178
+ if _reads_back(http, base, headers, team_id, target):
179
+ return PushResult("pushed", max_budget=target, prior_max_budget=prior_f)
180
+ return PushResult("unsupported", prior_max_budget=prior_f, error="LiteLLM's /team/update answer didn't carry the new max_budget back")
181
+ return PushResult("pushed", max_budget=target, prior_max_budget=prior_f)
182
+
183
+
184
+ def _reads_back(http: httpx.Client, base: str, headers: dict, team_id: str, target: Optional[float]) -> bool:
185
+ try:
186
+ res = http.get(f"{base}/team/info", params={"team_id": team_id}, headers=headers)
187
+ except httpx.HTTPError:
188
+ return False
189
+ body = _json(res) if res.status_code < 300 else None
190
+ team = body.get("team_info") if isinstance(body, dict) else None
191
+ value = team.get("max_budget") if isinstance(team, dict) else None
192
+ return isinstance(team, dict) and _same(value, target)
193
+
194
+
195
+ def _same(value: Any, target: Optional[float]) -> bool:
196
+ if target is None:
197
+ return value is None
198
+ return _is_number(value) and abs(float(value) - target) < 0.005
199
+
200
+
201
+ def _failure(res: httpx.Response, team_id: str) -> Optional[PushResult]:
202
+ if res.status_code < 300:
203
+ return None
204
+ if res.status_code in (401, 403):
205
+ return PushResult("failed", error=f"LiteLLM refused the admin key ({res.status_code})")
206
+ if res.status_code == 404:
207
+ return PushResult("failed", error=f"LiteLLM has no team {team_id}")
208
+ return PushResult("failed", error=f"LiteLLM answered {res.status_code}")
209
+
210
+
211
+ def _json(res: httpx.Response) -> Any:
212
+ try:
213
+ return res.json()
214
+ except ValueError:
215
+ return None
216
+
217
+
218
+ def _is_number(v: Any) -> bool:
219
+ return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
220
+
221
+
222
+ class StateFile:
223
+ """Each team's own limit from before the first push, by team id. Written atomically."""
224
+
225
+ def __init__(self, path: str) -> None:
226
+ self.path = path
227
+
228
+ def load(self) -> Dict[str, Optional[float]]:
229
+ try:
230
+ with open(self.path, encoding="utf-8") as f:
231
+ data = json.load(f)
232
+ except FileNotFoundError:
233
+ return {}
234
+ teams = data.get("teams") if isinstance(data, dict) else None
235
+ return dict(teams) if isinstance(teams, dict) else {}
236
+
237
+ def _write(self, teams: Dict[str, Optional[float]]) -> None:
238
+ folder = os.path.dirname(os.path.abspath(self.path))
239
+ fd, tmp = tempfile.mkstemp(dir=folder, prefix=".budget-sync-")
240
+ try:
241
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
242
+ json.dump({"teams": teams}, f)
243
+ f.flush()
244
+ os.fsync(f.fileno())
245
+ os.replace(tmp, self.path)
246
+ except BaseException:
247
+ if os.path.exists(tmp):
248
+ os.unlink(tmp)
249
+ raise
250
+
251
+ def remember(self, team_id: str, original: Optional[float]) -> None:
252
+ """Store a team's own limit; one already stored is never replaced."""
253
+ teams = self.load()
254
+ if team_id in teams:
255
+ return
256
+ teams[team_id] = original
257
+ self._write(teams)
258
+
259
+ def forget(self, team_id: str) -> None:
260
+ teams = self.load()
261
+ if teams.pop(team_id, "absent") != "absent":
262
+ self._write(teams)
263
+
264
+
265
+ def main(argv: Optional[list] = None) -> int:
266
+ parser = argparse.ArgumentParser(description="Set a LiteLLM team's max_budget from a TensorCost budget's room.")
267
+ parser.add_argument("--team-id", required=True)
268
+ parser.add_argument("--room-usd", type=float, help="What's left on the TensorCost budget, in dollars")
269
+ parser.add_argument("--restore", action="store_true", help="Put the team's own limit back and forget it")
270
+ parser.add_argument("--state-file", default="tensorcost-budget-sync.json", help="Where each team's own limit is kept")
271
+ parser.add_argument(
272
+ "--original-max-budget",
273
+ help="The team's own max_budget (a number, or 'none'), for a team the state file doesn't have yet. Never replaces a stored one.",
274
+ )
275
+ args = parser.parse_args(argv)
276
+ url = os.environ.get("LITELLM_URL")
277
+ key = os.environ.get("LITELLM_ADMIN_KEY")
278
+ if not url or not key:
279
+ print("Set LITELLM_URL and LITELLM_ADMIN_KEY.", file=sys.stderr)
280
+ return 2
281
+ state = StateFile(args.state_file)
282
+ stored = state.load()
283
+
284
+ if args.restore:
285
+ if args.team_id not in stored:
286
+ print(f"No own limit is stored for team {args.team_id} in {args.state_file}; nothing to put back.", file=sys.stderr)
287
+ return 1
288
+ result = restore_team_budget(url, key, args.team_id, stored[args.team_id])
289
+ if result.status == "pushed":
290
+ state.forget(args.team_id)
291
+ print(json.dumps(asdict(result)))
292
+ return 0 if result.status == "pushed" else 1
293
+
294
+ if args.room_usd is None:
295
+ print("Give --room-usd, or --restore.", file=sys.stderr)
296
+ return 2
297
+ if args.team_id not in stored and args.original_max_budget is not None:
298
+ given = None if args.original_max_budget.strip().lower() == "none" else float(args.original_max_budget)
299
+ state.remember(args.team_id, given)
300
+ stored = state.load()
301
+ original: Union[float, None, _Unset] = stored[args.team_id] if args.team_id in stored else UNSET
302
+ result = push_team_budget(
303
+ url,
304
+ key,
305
+ args.team_id,
306
+ args.room_usd,
307
+ original_max_budget=original,
308
+ save_original=lambda value: state.remember(args.team_id, value),
309
+ )
310
+ print(json.dumps(asdict(result)))
311
+ return 0 if result.status == "pushed" else 1
312
+
313
+
314
+ if __name__ == "__main__":
315
+ sys.exit(main())