agents-framework 0.3.0__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.
Files changed (50) hide show
  1. agents_framework-0.3.0.dist-info/METADATA +1364 -0
  2. agents_framework-0.3.0.dist-info/RECORD +50 -0
  3. agents_framework-0.3.0.dist-info/WHEEL +5 -0
  4. agents_framework-0.3.0.dist-info/entry_points.txt +2 -0
  5. agents_framework-0.3.0.dist-info/licenses/LICENSE +661 -0
  6. agents_framework-0.3.0.dist-info/top_level.txt +1 -0
  7. framework/__init__.py +0 -0
  8. framework/__main__.py +9 -0
  9. framework/action_page.py +1102 -0
  10. framework/approval_buttons.py +775 -0
  11. framework/approvals.py +678 -0
  12. framework/calendar_card.py +276 -0
  13. framework/cli.py +273 -0
  14. framework/codex_llm.py +401 -0
  15. framework/config.py +126 -0
  16. framework/drafter.py +263 -0
  17. framework/interfaces.py +96 -0
  18. framework/llm.py +744 -0
  19. framework/plugins/__init__.py +147 -0
  20. framework/plugins/agentmail_source.py +355 -0
  21. framework/plugins/approval_destination.py +478 -0
  22. framework/plugins/command_action.py +248 -0
  23. framework/plugins/digest_destination.py +546 -0
  24. framework/plugins/email_destination.py +248 -0
  25. framework/plugins/fanout_destination.py +160 -0
  26. framework/plugins/github_org_source.py +226 -0
  27. framework/plugins/github_releases_source.py +420 -0
  28. framework/plugins/ics_source.py +594 -0
  29. framework/plugins/llm_scorer.py +411 -0
  30. framework/plugins/multi_source.py +241 -0
  31. framework/plugins/reddit_source.py +625 -0
  32. framework/plugins/regex_scorer.py +93 -0
  33. framework/plugins/rss_source.py +346 -0
  34. framework/plugins/signal_destination.py +133 -0
  35. framework/plugins/slack_destination.py +461 -0
  36. framework/plugins/slack_draft_action.py +137 -0
  37. framework/plugins/slack_post_action.py +65 -0
  38. framework/plugins/slack_workspace_source.py +992 -0
  39. framework/plugins/twitter_action.py +210 -0
  40. framework/plugins/websearch_source.py +761 -0
  41. framework/plugins/wordpress_action.py +413 -0
  42. framework/proposals.py +246 -0
  43. framework/registry.py +166 -0
  44. framework/runlog.py +125 -0
  45. framework/runner.py +243 -0
  46. framework/schedule.py +571 -0
  47. framework/signal_messenger.py +1418 -0
  48. framework/slack.py +801 -0
  49. framework/state.py +39 -0
  50. framework/templating.py +76 -0
framework/llm.py ADDED
@@ -0,0 +1,744 @@
1
+ """LLM access through a vendor waterfall on LiteLLM's Router (issue #44).
2
+
3
+ Ported from shmobster's `llm.py`, which we also own, so there is one waterfall
4
+ shape to maintain rather than two. Not a shared package: that would tie
5
+ shmobster's release cadence to this repo's, and the owned surface is small.
6
+
7
+ The chain is a list of vendor rows, tried in order until one answers:
8
+
9
+ {
10
+ "waterfall": [
11
+ {"name": "anthropic", "model": "anthropic/<model>", "api_key_env": "ANTHROPIC_API_KEY"},
12
+ {"name": "codex", "model": "codex/chatgpt/<model>"},
13
+ {"name": "openrouter", "model": "openrouter/<vendor>/<model>:free", "api_key_env": "OPENROUTER_API_KEY"}
14
+ ],
15
+ "budget_park_sec": 3600
16
+ }
17
+
18
+ Row keys: `name` (unique; what logs, `model_used` and parking call the rung),
19
+ `model` (a LiteLLM model id), `api_key_env` (the variable holding the key),
20
+ optional `api_base` (OpenAI-compatible endpoints) and `timeout_sec` (per-request
21
+ ceiling for that rung; else the plugin's `llm_timeout`, default 120).
22
+ `budget_park_sec` defaults to 3600; 0 turns parking off.
23
+
24
+ Where the chain comes from (`build_client`): the plugin block's own `llm` key if
25
+ it has one, else `<workspaces-root>/_shared/llm.json`, else `LLMConfigError`
26
+ naming both. One shared file means one waterfall per deployment; the per-plugin
27
+ block exists for the agent that wants a cheap model for scoring and the good one
28
+ for the weekly post. The root and the workspace reach the plugin as `_root` and
29
+ `_workspace` in its block, injected by `agent run`.
30
+
31
+ Differences from shmobster's rows, both deliberate. A row names the variable
32
+ that holds its key (`api_key_env`), never the key: secrets live in the
33
+ environment in this repo, and a row carrying `api_key` is refused rather than
34
+ honoured. Every non-codex row must name one, because a row without a key would
35
+ let LiteLLM go looking for its own idea of the right variable, which is a
36
+ credential read nobody configured. A `codex/` row takes no key at all: it
37
+ authenticates from the codex CLI's own token file (see `framework/codex_llm.py`),
38
+ so a chain can run on the ChatGPT subscription with nothing in the environment.
39
+ A named variable that is unset fails the build, naming the variable, rather
40
+ than quietly shortening the chain.
41
+
42
+ The Router is built as `primary` plus `fb0..fbN` groups with
43
+ `fallbacks=[{"primary": [...]}]`, `num_retries=1`, `cooldown_time=60` and
44
+ `allowed_fails=0`, so a vendor that fails is cooled on its first failure instead
45
+ of being re-dialled on every call of the run.
46
+
47
+ Budget parking. LiteLLM cools only on status (429/401/408/404), and budget
48
+ exhaustion is neither: Anthropic answers a usage cap with 400, OpenRouter answers
49
+ no-credit with 402. Fallback still covers the call, but the dead vendor would be
50
+ re-dialled first on every run for as long as the cap lasts -- weeks, in the case
51
+ that prompted shmobster's version. So a 402, or a 400/403 whose message names a
52
+ spend problem (`_BUDGET_MARKERS`), parks that vendor -- except a 402 that says
53
+ the request itself was too large (`_REQUEST_SIZED_402`), which means the account
54
+ still has credit and a smaller call still works, so only that call fails. Parking
55
+ puts an expiry into
56
+ `<workspace>/state/llm-parked.json`, and the Router is rebuilt without it until
57
+ then. The expiry is the vendor's own "regain access on
58
+ YYYY-MM-DD" when it states one and the date is in the future (clamped to 31
59
+ days, with the park line saying so), else `budget_park_sec` from now. The file
60
+ is pruned on read, which is what brings a
61
+ vendor back: no timer, the first call after the window simply stops seeing it.
62
+ A fully parked chain is tried in full anyway, since refusing to answer is worse
63
+ than one wasted call.
64
+
65
+ Parking hangs off LiteLLM's per-deployment failure callback, not off an `except`
66
+ around the call: when a fallback succeeds, the Router returns that answer and
67
+ the primary's exception never propagates, so an `except` would only see the case
68
+ parking cannot help. The same callback records one reason per vendor, which is
69
+ what `LLMError` reports when the whole chain fails and what the one stderr line
70
+ about a fallback says when it does not. Deployments carry a per-client id, so a
71
+ failure is attributed to exactly the vendor row that raised it, even with two
72
+ clients (scorer and digest) alive in one process.
73
+
74
+ litellm is imported lazily, by the first `build_client`, not by importing this
75
+ module: every agent imports this module through the plugin table, and only the
76
+ ones with an LLM plugin should pay for litellm (see `_load_litellm`).
77
+
78
+ Logging. LiteLLM's own loggers are capped at WARNING and verbose mode is off
79
+ before any Router exists, because at DEBUG they print raw request params,
80
+ api_key included. This module prints its own events to stderr, as the rest of
81
+ the framework does, and never prints keys, headers or request bodies. Failure
82
+ reasons quote the vendor's error message, first line only, with every
83
+ configured key value redacted, since `LLMError` can end up in a Slack channel.
84
+
85
+ `LLMClient.complete(system, user) -> str` and `model_used` keep their contract.
86
+ `LLMError` still means no rung produced an answer, now with per-vendor reasons;
87
+ an empty completion counts as that rung failing and the call moves on to the
88
+ next live rung, as it did before (see `LLMClient.complete`).
89
+ """
90
+ from __future__ import annotations
91
+
92
+ import datetime
93
+ import json
94
+ import logging
95
+ import os
96
+ import re
97
+ import sys
98
+ import time
99
+ import uuid
100
+ import weakref
101
+ from dataclasses import dataclass, field
102
+ from pathlib import Path
103
+ from types import SimpleNamespace
104
+ from typing import Any
105
+
106
+ from framework.config import CONFIG_FILENAME, STATE_DIRNAME, ConfigError
107
+ from framework.registry import PluginImportError
108
+
109
+ SHARED_DIRNAME = "_shared"
110
+ SHARED_FILENAME = "llm.json"
111
+ PARKED_FILENAME = "llm-parked.json"
112
+
113
+ _DEFAULT_BUDGET_PARK_SEC = 3600
114
+ _DEFAULT_TIMEOUT = 120
115
+
116
+ # A vendor-stated regain date further out than this is clamped to it. The date
117
+ # comes from an error body, and a far-future one (a proxy's, or a typo'd year)
118
+ # would otherwise take the rung out until someone hand-edits the state file.
119
+ _MAX_PARK_SEC = 31 * 24 * 3600
120
+
121
+ # The same strings as `codex_llm.PROVIDER` / `codex_llm.MODEL_PREFIX`, spelled
122
+ # out here because importing codex_llm imports litellm, which this module only
123
+ # does when a client is built (see `_load_litellm`).
124
+ _CODEX_PROVIDER_PREFIX = "codex/"
125
+ _CODEX_MODEL_PREFIX = "codex/chatgpt/"
126
+
127
+ # Budget exhaustion, by status plus message shape. Status alone is too broad --
128
+ # a 400 is also a malformed request, and parking a vendor for an hour over a bad
129
+ # prompt would be worse than the problem.
130
+ _BUDGET_MARKERS = (
131
+ "usage limit",
132
+ "usage limits",
133
+ "insufficient credit",
134
+ "insufficient_quota",
135
+ "credit balance",
136
+ "exceeded your current quota",
137
+ "billing",
138
+ "payment required",
139
+ )
140
+
141
+ # A 402 whose text says a smaller request would be affordable. OpenRouter's
142
+ # reads "This request requires more credits, or fewer max_tokens. You requested
143
+ # up to 16000 tokens, but can only afford 1200." The vendor is not exhausted and
144
+ # must not be parked; only this call fails.
145
+ _REQUEST_SIZED_402 = ("fewer max_tokens", "can only afford")
146
+
147
+ # Anthropic states when access returns: "You will regain access on 2026-09-01".
148
+ _REGAIN_DATE = re.compile(r"regain access on (\d{4})-(\d{2})-(\d{2})")
149
+
150
+ # litellm prefixes its messages with its own class path; the class is reported
151
+ # separately, so the prefix is noise in a reason.
152
+ _LITELLM_PREFIX = re.compile(r"^litellm\.[A-Za-z]+:\s*")
153
+
154
+ _REASON_CHARS = 160
155
+
156
+ # Live clients by deployment-id token, so the one global failure callback can
157
+ # hand a failure to the client whose Router raised it.
158
+ _CLIENTS: "weakref.WeakValueDictionary[str, LLMClient]" = weakref.WeakValueDictionary()
159
+
160
+
161
+ class LLMError(RuntimeError):
162
+ """No rung of the waterfall produced an answer; the message has one reason per vendor."""
163
+
164
+
165
+ class LLMConfigError(ConfigError):
166
+ """No usable waterfall: none configured, unreadable, or naming an unset credential.
167
+
168
+ A `ConfigError`, so `agent run` reports it in one line and exits 2 like any
169
+ other config problem.
170
+ """
171
+
172
+
173
+ def _say(message: str) -> None:
174
+ print(f"llm: {message}", file=sys.stderr)
175
+
176
+
177
+ @dataclass(frozen=True)
178
+ class _Vendor:
179
+ name: str
180
+ model: str
181
+ # Resolved from `api_key_env` at build time. Kept out of repr so an
182
+ # accidental print of a vendor cannot show it.
183
+ api_key: str | None = field(repr=False)
184
+ api_base: str | None
185
+ timeout_sec: float | None
186
+
187
+
188
+ def is_budget_error(exc: BaseException) -> bool:
189
+ """A 402, or a 400/403 that names a spend problem. A 402 needs no marker:
190
+ it has no other reading, and OpenRouter's unqualified one names none, so it
191
+ was re-dialled on every call. A 400 still needs one, because it is also
192
+ 'your request was malformed'.
193
+
194
+ The exception is a 402 that says the request itself was too large
195
+ (`_REQUEST_SIZED_402`). That one is not exhaustion: the account has credit,
196
+ this call just asked for more tokens than it covers, and a smaller call on
197
+ the same vendor still succeeds. Parking the vendor on it would retire a rung
198
+ that still works -- and on the last rung of the waterfall there is nothing
199
+ below to fall to, so an oversized digest step would take every smaller call
200
+ down with it for the whole park window. Such a call fails over without
201
+ parking, which is what the pre-park behaviour did correctly."""
202
+ status = getattr(exc, "status_code", None)
203
+ text = str(getattr(exc, "message", "") or str(exc)).lower()
204
+ if status == 402:
205
+ retval = not any(marker in text for marker in _REQUEST_SIZED_402)
206
+ return retval
207
+ if status not in (400, 403):
208
+ retval = False
209
+ return retval
210
+ retval = any(marker in text for marker in _BUDGET_MARKERS)
211
+ return retval
212
+
213
+
214
+ def _park_until(message: str, window: int) -> tuple[float, str]:
215
+ """When the vendor says it will be back, honour that; otherwise use the
216
+ configured window. A date we cannot parse falls back to the window rather
217
+ than being trusted -- a mis-parse could park a vendor for a year."""
218
+ now = time.time()
219
+ match = _REGAIN_DATE.search(message or "")
220
+ if match:
221
+ try:
222
+ when = datetime.datetime(
223
+ int(match.group(1)), int(match.group(2)), int(match.group(3)),
224
+ tzinfo=datetime.timezone.utc,
225
+ ).timestamp()
226
+ date = match.group(0).split("on ")[1]
227
+ if when > now + _MAX_PARK_SEC:
228
+ retval = (
229
+ now + _MAX_PARK_SEC,
230
+ f"for {_MAX_PARK_SEC // 86400} days (the vendor said until {date}, "
231
+ f"past the {_MAX_PARK_SEC // 86400}-day cap)",
232
+ )
233
+ return retval
234
+ if when > now:
235
+ retval = (when, f"until {date}")
236
+ return retval
237
+ except ValueError:
238
+ _say("unparseable regain date; using the default park window")
239
+ retval = (now + window, f"for {window}s")
240
+ return retval
241
+
242
+
243
+ # litellm and everything built on it, once `_load_litellm` has run.
244
+ _LITELLM: SimpleNamespace | None = None
245
+
246
+
247
+ def _load_litellm(what: str) -> SimpleNamespace:
248
+ """Import litellm on first use, never at module import.
249
+
250
+ Every agent imports this module (the plugin table imports the llm scorer and
251
+ the digest destination unconditionally), and `import litellm` costs over a
252
+ second and a half. Deferring it to the first `build_client` means an agent
253
+ that uses neither plugin never pays it, and a venv without litellm fails
254
+ only the agents that need it, at build time, naming the package.
255
+
256
+ Three things happen here, in this order, before any Router can exist:
257
+ - `LITELLM_LOCAL_MODEL_COST_MAP` defaults to True, because otherwise
258
+ `import litellm` fetches its model price map from GitHub, retrying for
259
+ seconds when the network is down. The bundled copy is enough: nothing
260
+ here reads prices.
261
+ - Verbose mode off and all three LiteLLM loggers capped at WARNING, so
262
+ raw request params, api_key included, are never logged. Capped after
263
+ the import, because litellm sets the levels itself when it loads
264
+ (from `LITELLM_LOG`), and all three because its debug switch flips every
265
+ one and it is "LiteLLM Router" that services the Router used here.
266
+ - The failure callback and the `codex/` provider are registered, once;
267
+ both lists are litellm globals.
268
+ """
269
+ global _LITELLM
270
+ if _LITELLM is not None:
271
+ return _LITELLM
272
+
273
+ os.environ.setdefault("LITELLM_LOCAL_MODEL_COST_MAP", "True")
274
+ try:
275
+ import litellm
276
+ except ImportError as exc:
277
+ raise PluginImportError(
278
+ f"{what} needs the 'litellm' package, which failed to import: "
279
+ f"{type(exc).__name__}: {exc}"
280
+ ) from exc
281
+ litellm.set_verbose = False
282
+ litellm.suppress_debug_info = True
283
+ for logger_name in ("LiteLLM", "LiteLLM Router", "LiteLLM Proxy"):
284
+ logging.getLogger(logger_name).setLevel(logging.WARNING)
285
+
286
+ import openai # litellm's own dependency; the base of its exceptions
287
+ from litellm import Router
288
+ from litellm.integrations.custom_logger import CustomLogger
289
+ from litellm.types.router import RouterRateLimitError
290
+
291
+ from framework import codex_llm
292
+
293
+ class _ChainWatch(CustomLogger):
294
+ """LiteLLM's per-deployment failure callback.
295
+
296
+ The only hook that sees a failure a fallback went on to cover, which is
297
+ the parking case: the call still gets answered, so nothing raises, yet
298
+ the exhausted vendor must not be dialled again."""
299
+
300
+ def log_failure_event(self, kwargs, response_obj, start_time, end_time):
301
+ _on_failure(kwargs)
302
+
303
+ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
304
+ _on_failure(kwargs)
305
+
306
+ litellm.callbacks = list(litellm.callbacks) + [_ChainWatch()]
307
+ # Before the Router is built: litellm resolves every deployment's provider
308
+ # at construction, and must know `codex/` by then.
309
+ codex_llm.register()
310
+
311
+ _LITELLM = SimpleNamespace(
312
+ Router=Router,
313
+ # What a dead chain raises: the primary's litellm exception (all are
314
+ # openai.OpenAIError subclasses) or, when every rung is still cooling
315
+ # from an earlier failure, RouterRateLimitError (a ValueError).
316
+ chain_errors=(openai.OpenAIError, RouterRateLimitError),
317
+ )
318
+ retval = _LITELLM
319
+ return retval
320
+
321
+
322
+ def _on_failure(kwargs: dict) -> None:
323
+ exc = kwargs.get("exception")
324
+ if exc is None:
325
+ return
326
+ metadata = (kwargs.get("litellm_params") or {}).get("metadata") or {}
327
+ deployment_id = str((metadata.get("model_info") or {}).get("id") or "")
328
+ token, sep, name = deployment_id.partition(":")
329
+ client = _CLIENTS.get(token) if sep else None
330
+ if client is None:
331
+ return
332
+ client._record_failure(name, exc)
333
+
334
+
335
+ class LLMClient:
336
+ def __init__(
337
+ self,
338
+ vendors: list[_Vendor],
339
+ parked_path: str | os.PathLike,
340
+ budget_park_sec: int = _DEFAULT_BUDGET_PARK_SEC,
341
+ timeout: int = _DEFAULT_TIMEOUT,
342
+ max_tokens: int = 2000,
343
+ temperature: float = 0.3,
344
+ ):
345
+ if not vendors:
346
+ raise LLMConfigError("the waterfall is empty -- add at least one vendor")
347
+ self.vendors = list(vendors)
348
+ self.parked_path = Path(parked_path)
349
+ self.budget_park_sec = budget_park_sec
350
+ self.timeout = timeout
351
+ self.max_tokens = max_tokens
352
+ self.temperature = temperature
353
+ # Which rung actually answered, for the caller to report.
354
+ self.model_used: str | None = None
355
+ self._token = uuid.uuid4().hex[:12]
356
+ self._router: Any = None
357
+ self._router_vendors: tuple[str, ...] | None = None
358
+ # Vendor name -> reason, for the call in progress.
359
+ self._failures: dict[str, str] = {}
360
+ _CLIENTS[self._token] = self
361
+
362
+ # -- parked-vendor state ------------------------------------------------
363
+
364
+ def _read_parked(self) -> dict:
365
+ if not self.parked_path.exists():
366
+ retval: dict = {}
367
+ return retval
368
+ try:
369
+ raw = json.loads(self.parked_path.read_text())
370
+ except (OSError, ValueError) as exc:
371
+ raise RuntimeError(
372
+ f"{self.parked_path} could not be read ({exc}); delete it to clear parked vendors"
373
+ ) from exc
374
+ if not isinstance(raw, dict):
375
+ raise RuntimeError(
376
+ f"{self.parked_path} is not a JSON object; delete it to clear parked vendors"
377
+ )
378
+ retval = raw
379
+ return retval
380
+
381
+ def _write_parked(self, parked: dict[str, float]) -> None:
382
+ self.parked_path.parent.mkdir(parents=True, exist_ok=True)
383
+ tmp = self.parked_path.with_name(self.parked_path.name + ".tmp")
384
+ tmp.write_text(json.dumps(parked, indent=2, sort_keys=True))
385
+ os.replace(tmp, self.parked_path)
386
+
387
+ def _parked(self) -> dict[str, float]:
388
+ """Vendor -> expiry, with anything already expired dropped and the
389
+ drop written back. Pruning on read is what brings a vendor back."""
390
+ raw = self._read_parked()
391
+ now = time.time()
392
+ live = {
393
+ str(name): float(until) for name, until in raw.items()
394
+ if isinstance(until, (int, float)) and not isinstance(until, bool) and until > now
395
+ }
396
+ if len(live) != len(raw):
397
+ self._write_parked(live)
398
+ for name in sorted(set(raw) - set(live)):
399
+ _say(f"{name} is out of its park window; back in the chain")
400
+ retval = live
401
+ return retval
402
+
403
+ def _park(self, name: str, exc: BaseException) -> None:
404
+ if not self.budget_park_sec:
405
+ return
406
+ parked = self._parked()
407
+ if name in parked:
408
+ # Already parked; the callback fires once per attempt.
409
+ return
410
+ until, human = _park_until(str(getattr(exc, "message", "") or str(exc)), self.budget_park_sec)
411
+ parked[name] = until
412
+ self._write_parked(parked)
413
+ # The vendor's prose is deliberately not repeated here; the reason
414
+ # recorded for this call carries the redacted first line of it.
415
+ _say(f"{name} is out of budget; parked {human}")
416
+ self._router = None
417
+ self._router_vendors = None
418
+
419
+ # -- failures -----------------------------------------------------------
420
+
421
+ def _redact(self, text: str) -> str:
422
+ retval = text
423
+ for vendor in self.vendors:
424
+ if vendor.api_key:
425
+ retval = retval.replace(vendor.api_key, "<redacted>")
426
+ return retval
427
+
428
+ def _reason(self, exc: BaseException) -> str:
429
+ status = getattr(exc, "status_code", None)
430
+ lines = str(exc).strip().splitlines()
431
+ first = _LITELLM_PREFIX.sub("", lines[0]) if lines else ""
432
+ reason = type(exc).__name__
433
+ if status:
434
+ reason += f" {status}"
435
+ if first:
436
+ reason += f": {first[:_REASON_CHARS]}"
437
+ retval = self._redact(reason)
438
+ return retval
439
+
440
+ def _record_failure(self, name: str, exc: BaseException) -> None:
441
+ self._failures[name] = self._reason(exc)
442
+ if is_budget_error(exc):
443
+ self._park(name, exc)
444
+
445
+ def _summary(self, live: list[_Vendor]) -> str:
446
+ parts = [f"{v.name}: {self._failures.get(v.name, 'not tried')}" for v in live]
447
+ live_names = {v.name for v in live}
448
+ parked = sorted(name for name in self._parked() if name not in live_names)
449
+ if parked:
450
+ parts.append(f"parked: {', '.join(parked)}")
451
+ retval = "; ".join(parts)
452
+ return retval
453
+
454
+ # -- router -------------------------------------------------------------
455
+
456
+ def _live(self) -> list[_Vendor]:
457
+ """The configured waterfall minus parked vendors -- but never empty."""
458
+ parked = self._parked()
459
+ live = [v for v in self.vendors if v.name not in parked]
460
+ if not live:
461
+ _say("every vendor is parked; trying the full chain anyway")
462
+ live = list(self.vendors)
463
+ retval = live
464
+ return retval
465
+
466
+ def _deployment(self, group: str, vendor: _Vendor) -> dict:
467
+ # A codex row has no api_key at all. Sending `api_key: None` is not the
468
+ # same as omitting it -- litellm treats the key as present-but-empty.
469
+ params: dict[str, Any] = {
470
+ "model": vendor.model,
471
+ "timeout": vendor.timeout_sec or self.timeout,
472
+ }
473
+ if vendor.api_key:
474
+ params["api_key"] = vendor.api_key
475
+ if vendor.api_base:
476
+ params["api_base"] = vendor.api_base
477
+ retval = {
478
+ "model_name": group,
479
+ "litellm_params": params,
480
+ "model_info": {"id": f"{self._token}:{vendor.name}"},
481
+ }
482
+ return retval
483
+
484
+ def _build(self, live: list[_Vendor]) -> Any:
485
+ lite = _load_litellm("the LLM client")
486
+ model_list = [self._deployment("primary", live[0])]
487
+ rest = live[1:]
488
+ for i, vendor in enumerate(rest):
489
+ model_list.append(self._deployment(f"fb{i}", vendor))
490
+ fallbacks = [{"primary": [f"fb{i}" for i in range(len(rest))]}] if rest else []
491
+ retval = lite.Router(
492
+ model_list=model_list,
493
+ fallbacks=fallbacks,
494
+ num_retries=1,
495
+ cooldown_time=60,
496
+ # Cool a failing deployment on its FIRST failure rather than after
497
+ # the default threshold: a run is short, and by the time a
498
+ # threshold is reached every fail in it was a wasted round-trip.
499
+ allowed_fails=0,
500
+ )
501
+ return retval
502
+
503
+ def _ensure(self) -> tuple[Any, list[_Vendor]]:
504
+ """Build the Router, or rebuild it when the set of usable vendors
505
+ changed -- a park added one, or a park expired and gave one back."""
506
+ live = self._live()
507
+ names = tuple(v.name for v in live)
508
+ if self._router is None or names != self._router_vendors:
509
+ if self._router_vendors is not None:
510
+ _say(f"rebuilding, chain is now {' -> '.join(names)}")
511
+ self._router = self._build(live)
512
+ self._router_vendors = names
513
+ retval = (self._router, live)
514
+ return retval
515
+
516
+ def _answered_by(self, resp: Any) -> _Vendor | None:
517
+ hidden = getattr(resp, "_hidden_params", None) or {}
518
+ token, _, name = str(hidden.get("model_id") or "").partition(":")
519
+ retval = None
520
+ if token == self._token:
521
+ retval = next((v for v in self.vendors if v.name == name), None)
522
+ return retval
523
+
524
+ def complete(self, system: str, user: str) -> str:
525
+ """One system+user turn through the waterfall; the first answer wins.
526
+
527
+ No budget handling here on purpose: when a fallback covers a failure
528
+ nothing is raised, so parking lives in the failure callback. An
529
+ exception reaching this point means every rung failed (or, later in a
530
+ run, that every rung is still cooling from an earlier failure).
531
+
532
+ An empty answer is that rung failing, but to the Router a 200 is a
533
+ success, so it never falls through on one. That part of the walk is
534
+ done here: the call is repeated on a one-off Router over the live rows
535
+ after the one that answered empty, until a rung answers with text or
536
+ none is left. The one-off Router starts with no cooldowns, which only
537
+ matters on this rare path, and only for rungs that failed in an earlier
538
+ call of the same run."""
539
+ chain_errors = _load_litellm("the LLM client").chain_errors
540
+ router, live = self._ensure()
541
+ self._failures = {}
542
+ messages = [
543
+ {"role": "system", "content": system},
544
+ {"role": "user", "content": user},
545
+ ]
546
+ remaining = live
547
+ while True:
548
+ try:
549
+ resp = router.completion(
550
+ model="primary",
551
+ messages=messages,
552
+ max_tokens=self.max_tokens,
553
+ temperature=self.temperature,
554
+ # Rungs differ in which sampling params they accept
555
+ # (current Claude models refuse any temperature but 1, and
556
+ # litellm raises before sending). Dropping what a rung
557
+ # cannot take keeps it in the chain instead of failing it
558
+ # on every call.
559
+ drop_params=True,
560
+ )
561
+ except chain_errors as exc:
562
+ raise LLMError("all models failed — " + self._summary(live)) from exc
563
+
564
+ vendor = self._answered_by(resp)
565
+ label = f"{vendor.name} ({vendor.model})" if vendor else str(resp.model)
566
+ content = (resp.choices[0].message.content or "").strip()
567
+ if content:
568
+ break
569
+ self._failures[vendor.name if vendor else label] = "empty completion"
570
+ # Without knowing which row answered, the rest of the chain has no
571
+ # starting point, so this ends the walk.
572
+ pos = next(
573
+ (i for i, v in enumerate(remaining) if vendor and v.name == vendor.name), None
574
+ )
575
+ remaining = remaining[pos + 1:] if pos is not None else []
576
+ if not remaining:
577
+ raise LLMError("all models failed — " + self._summary(live))
578
+ router = self._build(remaining)
579
+
580
+ if self._failures:
581
+ reasons = "; ".join(f"{name}: {reason}" for name, reason in self._failures.items())
582
+ _say(f"answered by {label} after {reasons}")
583
+ self.model_used = label
584
+ retval = content
585
+ return retval
586
+
587
+
588
+ def _parse_row(row: Any, where: str) -> _Vendor:
589
+ if not isinstance(row, dict):
590
+ raise LLMConfigError(f"{where}: each waterfall row must be an object")
591
+ name = row.get("name")
592
+ model = row.get("model")
593
+ if not isinstance(name, str) or not name:
594
+ raise LLMConfigError(f"{where}: 'name' is required")
595
+ where = f"{where} ({name})"
596
+ if not isinstance(model, str) or not model:
597
+ raise LLMConfigError(f"{where}: 'model' is required")
598
+ if "api_key" in row:
599
+ raise LLMConfigError(
600
+ f"{where}: 'api_key' is not accepted; put the key in the environment "
601
+ f"and name the variable with 'api_key_env'"
602
+ )
603
+
604
+ key_env = row.get("api_key_env")
605
+ api_key = None
606
+ if model.startswith(_CODEX_PROVIDER_PREFIX):
607
+ if not model.startswith(_CODEX_MODEL_PREFIX):
608
+ # See codex_llm.MODEL_PREFIX: without the segment litellm routes
609
+ # the bare model id to OpenAI and bills a platform key instead.
610
+ raise LLMConfigError(
611
+ f"{where}: codex rows must be '{_CODEX_MODEL_PREFIX}<model>' (got {model!r})"
612
+ )
613
+ if key_env is not None:
614
+ raise LLMConfigError(
615
+ f"{where}: codex rows take no 'api_key_env'; they authenticate "
616
+ f"from the codex CLI's token file"
617
+ )
618
+ else:
619
+ if not isinstance(key_env, str) or not key_env:
620
+ raise LLMConfigError(
621
+ f"{where}: 'api_key_env' is required (only '{_CODEX_MODEL_PREFIX}' rows run without a key)"
622
+ )
623
+ api_key = os.environ.get(key_env)
624
+ if not api_key:
625
+ raise LLMConfigError(f"{where}: ${key_env} is not set")
626
+
627
+ api_base = row.get("api_base")
628
+ if api_base is not None and (not isinstance(api_base, str) or not api_base):
629
+ raise LLMConfigError(f"{where}: 'api_base' must be a non-empty string")
630
+ timeout_sec = row.get("timeout_sec")
631
+ if timeout_sec is not None and (
632
+ isinstance(timeout_sec, bool) or not isinstance(timeout_sec, (int, float)) or timeout_sec <= 0
633
+ ):
634
+ raise LLMConfigError(f"{where}: 'timeout_sec' must be a positive number")
635
+
636
+ retval = _Vendor(
637
+ name=name,
638
+ model=model,
639
+ api_key=api_key,
640
+ api_base=api_base,
641
+ timeout_sec=float(timeout_sec) if timeout_sec is not None else None,
642
+ )
643
+ return retval
644
+
645
+
646
+ def _parse_chain(raw: Any, origin: str) -> tuple[list[_Vendor], int]:
647
+ if not isinstance(raw, dict):
648
+ raise LLMConfigError(f"{origin}: must be an object with a 'waterfall' list")
649
+ rows = raw.get("waterfall")
650
+ if not isinstance(rows, list) or not rows:
651
+ raise LLMConfigError(f"{origin}: 'waterfall' must be a non-empty list of vendor rows")
652
+ park_sec = raw.get("budget_park_sec", _DEFAULT_BUDGET_PARK_SEC)
653
+ if isinstance(park_sec, bool) or not isinstance(park_sec, int) or park_sec < 0:
654
+ raise LLMConfigError(
655
+ f"{origin}: 'budget_park_sec' must be a non-negative integer (got {park_sec!r})"
656
+ )
657
+ vendors: list[_Vendor] = []
658
+ for i, row in enumerate(rows):
659
+ vendor = _parse_row(row, f"{origin}: waterfall[{i}]")
660
+ if any(v.name == vendor.name for v in vendors):
661
+ raise LLMConfigError(f"{origin}: vendor name {vendor.name!r} appears twice")
662
+ vendors.append(vendor)
663
+ retval = (vendors, park_sec)
664
+ return retval
665
+
666
+
667
+ def _load_chain(cfg: dict, what: str, config_label: str) -> tuple[Any, str]:
668
+ """The plugin's own `llm` block, else the deployment's shared file."""
669
+ block = cfg.get("llm")
670
+ if block is not None:
671
+ retval = (block, f"{config_label}: {what} 'llm' block")
672
+ return retval
673
+
674
+ root = cfg.get("_root")
675
+ if root:
676
+ shared = Path(root) / SHARED_DIRNAME / SHARED_FILENAME
677
+ if shared.is_file():
678
+ try:
679
+ raw = json.loads(shared.read_text())
680
+ except (OSError, ValueError) as exc:
681
+ raise LLMConfigError(f"{shared} could not be read as JSON: {exc}") from exc
682
+ retval = (raw, str(shared))
683
+ return retval
684
+ shared_label = str(shared)
685
+ else:
686
+ shared_label = (
687
+ f"<workspaces-root>/{SHARED_DIRNAME}/{SHARED_FILENAME} "
688
+ f"(no workspaces root was passed as '_root')"
689
+ )
690
+ raise LLMConfigError(
691
+ f"{what} has no LLM waterfall: add an 'llm' block to {config_label}, "
692
+ f"or create {shared_label}"
693
+ )
694
+
695
+
696
+ def build_client(
697
+ cfg: dict,
698
+ default_max_tokens: int = 2000,
699
+ default_temperature: float = 0.3,
700
+ what: str = "llm",
701
+ ) -> LLMClient:
702
+ """Build an `LLMClient` from a plugin's config block.
703
+
704
+ Every LLM-backed plugin resolves its chain the same way, and this is that
705
+ way, written once (see the module docstring for the order and the row
706
+ shape). `cfg` also carries `_workspace` and `_root`, injected by
707
+ `agent run`; the workspace holds the parked-vendor state, so a client
708
+ cannot be built without it.
709
+
710
+ Plugin keys read here besides `llm`: `llm_timeout` (seconds per request,
711
+ default 120, overridden per row by `timeout_sec`), `max_tokens` and
712
+ `temperature` (defaults supplied by the calling plugin).
713
+
714
+ This is where litellm is first imported (`_load_litellm`), so a venv
715
+ without it fails here, naming the package, and only for agents that use an
716
+ LLM plugin.
717
+
718
+ `what` names the calling plugin in error messages.
719
+ """
720
+ _load_litellm(what)
721
+ if "model" in cfg:
722
+ raise LLMConfigError(
723
+ f"{what}: the 'model' block was replaced by 'llm' "
724
+ f"(a waterfall of vendor rows; see docs/llm.example.json)"
725
+ )
726
+ workspace = cfg.get("_workspace")
727
+ if not workspace:
728
+ raise LLMConfigError(
729
+ f"{what} needs the workspace path for its parked-vendor state; the CLI "
730
+ f"injects it as '_workspace' (it cannot be built outside `agent run`)"
731
+ )
732
+ config_label = str(Path(workspace) / CONFIG_FILENAME)
733
+ raw, origin = _load_chain(cfg, what, config_label)
734
+ vendors, park_sec = _parse_chain(raw, origin)
735
+
736
+ retval = LLMClient(
737
+ vendors=vendors,
738
+ parked_path=Path(workspace) / STATE_DIRNAME / PARKED_FILENAME,
739
+ budget_park_sec=park_sec,
740
+ timeout=int(cfg.get("llm_timeout", _DEFAULT_TIMEOUT)),
741
+ max_tokens=int(cfg.get("max_tokens", default_max_tokens)),
742
+ temperature=float(cfg.get("temperature", default_temperature)),
743
+ )
744
+ return retval