Coverage for app / services / model_catalogue.py: 97%

66 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2svc-ai's model catalogue, and what a request to each model would cost. 

3 

4An Economy profile's lighter model (``services/lighter_model.py``) and a 

5native sibling for the structured steps (``services/native_sibling.py``) are 

6both chosen from it: the cheapest available model that qualifies. This wraps 

7the catalogue in something they can ask questions of, the same way 

8:class:`~app.services.usage.UsageWindow` wraps the ledger for the quota 

9actions. 

10 

11Two things matter about how it behaves when svc-ai is unreachable: 

12 

13* It never raises. Choosing a cheaper model is an optimisation, not a gate — 

14 the turn already has a model, and failing it because the *alternative* 

15 could not be looked up would turn a degraded optimiser into an outage. 

16* It reports that it is empty rather than pretending nothing qualifies. A 

17 caller that cannot see the catalogue leaves the turn on its own model, 

18 which is materially different from concluding that no model is suitable. 

19""" 

20 

21from __future__ import annotations 

22 

23import logging 

24import threading 

25from decimal import Decimal, InvalidOperation 

26from typing import Any 

27 

28from app.services.ai_client import list_models 

29 

30logger = logging.getLogger(__name__) 

31 

32#: Assumed completion length when comparing prices and the real one is not yet 

33#: known — which, before the turn, it never is: the model has not been 

34#: called. Only the *ratio* between input and output pricing matters for a 

35#: comparison, so a plausible constant is enough to stop a model with cheap 

36#: input and ruinous output from ranking first on input price alone. 

37ASSUMED_OUTPUT_TOKENS = 500 

38 

39 

40def _decimal(value: Any) -> Decimal | None: 

41 """Exact decimal form of ``value``, or None when it is not a number.""" 

42 if value is None or isinstance(value, bool): 

43 return None 

44 try: 

45 return Decimal(str(value)) 

46 except (InvalidOperation, ValueError, TypeError): 

47 return None 

48 

49 

50class ModelCatalogue: 

51 """Available models from svc-ai, fetched at most once. 

52 

53 Memoised so every choice made for one turn sees the same list: the 

54 lighter model and the native sibling chosen beside it are chosen from 

55 one catalogue. An evaluation target keeps one for its whole run 

56 (``TargetGovernance.catalogue``), shared by the pool threads that run its 

57 cells, so the first read is made under a lock. 

58 """ 

59 

60 def __init__(self) -> None: 

61 self._models: list[dict[str, Any]] | None = None 

62 self._failed = False 

63 self._lock = threading.Lock() 

64 

65 # -- access ---------------------------------------------------------- 

66 

67 def available(self) -> list[dict[str, Any]]: 

68 """Every chat model svc-ai reports as available, or [] if it could 

69 not be reached. Callers distinguish the two with :meth:`usable`. 

70 

71 Chat models only: every choice made from it is of a model to answer 

72 a prompt, and an embedding model (the catalogue's cheapest priced 

73 row) answers none.""" 

74 if self._models is None and not self._failed: 

75 with self._lock: 

76 if self._models is None and not self._failed: 

77 self._fetch() 

78 return self._models or [] 

79 

80 def _fetch(self) -> None: 

81 try: 

82 self._models = [ 

83 model 

84 for model in list_models(is_available=True) 

85 if isinstance(model, dict) and model.get("is_chat", True) 

86 ] 

87 # Deliberately broad: a cheaper model is an optimisation, and no 

88 # failure looking up an *alternative* model should fail the request 

89 # that already has one. 

90 except Exception: 

91 logger.warning( 

92 "Could not fetch the model catalogue — the turn keeps its own " 

93 "model for all of its work", 

94 exc_info=True, 

95 ) 

96 self._failed = True 

97 self._models = [] 

98 

99 def usable(self) -> bool: 

100 """True when the catalogue was actually read. 

101 

102 The distinction from an empty list is the whole point: "svc-ai says no 

103 model is available" and "svc-ai could not be asked" call for different 

104 behaviour, and only one of them should change where a request goes. 

105 """ 

106 self.available() 

107 return not self._failed 

108 

109 def get(self, model_id: str | None) -> dict[str, Any] | None: 

110 """The available model with this id, or None.""" 

111 if not model_id: 

112 return None 

113 wanted = str(model_id) 

114 for model in self.available(): 

115 if str(model.get("id")) == wanted: 

116 return model 

117 return None 

118 

119 def is_available(self, model_id: str | None) -> bool: 

120 return self.get(model_id) is not None 

121 

122 

123# ── Cost ────────────────────────────────────────────────────────────────────── 

124 

125 

126def estimated_request_cost( 

127 model: dict[str, Any], 

128 prompt_tokens: int | None = None, 

129) -> Decimal | None: 

130 """What one request to ``model`` would cost, for ranking purposes. 

131 

132 Weighted by the prompt's real token count when the caller supplies one, 

133 and by :data:`ASSUMED_OUTPUT_TOKENS` for the completion, which is never 

134 known before the call. Returns None when the model publishes no price at 

135 all — an unpriced model is not free, and ranking it as cheapest would send 

136 traffic to the one model whose cost nobody can account for. 

137 """ 

138 input_price = _decimal(model.get("input_cost_per_token")) 

139 output_price = _decimal(model.get("output_cost_per_token")) 

140 if input_price is None and output_price is None: 

141 return None 

142 

143 inputs = Decimal(int(prompt_tokens)) if prompt_tokens else Decimal(0) 

144 total = Decimal(0) 

145 if input_price is not None: 

146 total += input_price * inputs 

147 if output_price is not None: 

148 total += output_price * Decimal(ASSUMED_OUTPUT_TOKENS) 

149 return total 

150 

151 

152def cheapest_first( 

153 models: list[dict[str, Any]], 

154 prompt_tokens: int | None = None, 

155) -> list[dict[str, Any]]: 

156 """``models`` ordered by estimated request cost, cheapest first. 

157 

158 Unpriced models are dropped rather than sorted to either end: they cannot 

159 be compared, and both alternatives are wrong — first would send spend to 

160 an unaccountable model, last would silently prefer a more expensive priced 

161 one over a possibly-cheaper unpriced one while claiming to be cheapest. 

162 """ 

163 priced: list[tuple[Decimal, dict[str, Any]]] = [] 

164 for model in models: 

165 cost = estimated_request_cost(model, prompt_tokens) 

166 if cost is not None: 

167 priced.append((cost, model)) 

168 priced.sort(key=lambda pair: (pair[0], str(pair[1].get("model_name") or ""))) 

169 return [model for _, model in priced]