Coverage for app / services / token_budget.py: 89%

194 statements  

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

1""" 

2How much of a conversation's history a call can carry (cost-control plan, 

3B1.3). 

4 

5svc-core sends a conversation's newest messages within an outer bound 

6(``app/util/history_window.py`` there: 100 messages, ~1M characters), and 

7nothing here fitted them to the model they go to. A long chat — or one turn 

8that pasted a long document, which is stored with the turn and replayed on 

9every later one — could cross the model's long-context price tier (OpenAI 

10reprices a whole request past 272K input tokens) and then its context window, 

11when the call fails with a 400. This fits the history to the call: 

12 

13 H = min(W − O − P − R − G − 5%·W, T − P − R − G − 5%·T, H_profile) 

14 

15* ``W`` the model's context window (``DEFAULT_CONTEXT_WINDOW`` if unknown), 

16 ``O`` the most it may write, ``T`` its long-context threshold, if it has 

17 one — all from the catalogue (``llm_models``), LiteLLM's table second; 

18* ``P`` the system prompt and tool definitions, ``R`` the request context and 

19 task, both measured on the call; ``G`` room for a tool loop's results 

20 (``TOOL_LOOP_RESERVE``); 5% for the estimate being an estimate; 

21* ``H_profile`` the run's cost profile's own cap (``app/agents/effort.py``, 

22 ``PipelineEffort.history_token_cap``) — none for ``thorough``. 

23 

24The first two bound every call: they keep a request inside the model's 

25window and below its price tier, and change nothing for a conversation that 

26already fits. When one does not: 

27 

281. **Old turns' documents become stubs.** A document pasted in an earlier 

29 turn is replaced by a line saying so; the newest turn keeps its own. 

302. **Whole turns go, oldest first, in blocks** (``BLOCK_TURNS``) anchored at 

31 the first turn, so what stays starts at the same message for several 

32 turns and the cached prefix behind it moves once a block, not every turn. 

33 A turn — a question and what answered it — is never split. 

343. **A newest turn too large on its own is cut** to what fits, and says so. 

35 

36The answering model is told how many earlier turns it cannot see (the 

37caller adds the note), and the node's ``node_end`` frame carries the figure 

38into the turn's decision record (``history_turns_omitted``). 

39 

40Tokens are estimated, not counted — ``CHARS_PER_TOKEN`` is set below the 

41usual four so the estimate errs high, which is the safe side for a bound. 

42""" 

43 

44from __future__ import annotations 

45 

46import logging 

47import math 

48import re 

49import threading 

50import time 

51from dataclasses import dataclass 

52from typing import Any 

53 

54from langchain_core.messages import BaseMessage, HumanMessage 

55 

56from app.util import safe_json 

57 

58logger = logging.getLogger(__name__) 

59 

60#: Assumed when neither the catalogue nor LiteLLM knows a model's window. 

61DEFAULT_CONTEXT_WINDOW = 128_000 

62#: Room kept for the estimate being an estimate. 

63SAFETY_SHARE = 0.05 

64#: Room kept for a tool loop's rounds: the replies and results it adds. 

65TOOL_LOOP_RESERVE = 8_000 

66#: Characters per token the estimate assumes — under the usual 4, so it errs 

67#: high. 

68CHARS_PER_TOKEN = 3.5 

69#: What a message costs beyond its text (role, framing). 

70MESSAGE_OVERHEAD_TOKENS = 4 

71#: Turns dropped together, so the history's start moves once a block. 

72BLOCK_TURNS = 4 

73#: How long the catalogue's limits are kept before being read again. 

74LIMITS_CACHE_S = 300 

75 

76#: What an earlier turn's document becomes once the history must shrink. 

77DOCUMENT_STUB = ( 

78 "[This document's text was given in this earlier turn and is not repeated here.]" 

79) 

80#: What a message cut to fit ends with. 

81CUT_MARK = "\n[…cut to fit the model's context.]" 

82 

83#: svc-core's attached-document block (``app/util/document.py``): the body 

84#: between these tags is what a stub replaces. 

85_DOCUMENT_BODY = re.compile( 

86 r"(<document_content>)(.*?)(</document_content>)", re.DOTALL 

87) 

88 

89 

90@dataclass(frozen=True) 

91class ModelLimits: 

92 """What a model can take: from the catalogue, else LiteLLM's table.""" 

93 

94 context_window: int | None = None 

95 max_output_tokens: int | None = None 

96 #: Input tokens past which a request is billed at a higher tier. 

97 long_context_threshold: int | None = None 

98 

99 

100@dataclass(frozen=True) 

101class Fitted: 

102 """A history fitted to a call.""" 

103 

104 messages: list[BaseMessage] 

105 #: Whole turns left out, oldest first. 

106 omitted_turns: int = 0 

107 #: Earlier turns whose document text was replaced by a stub. 

108 stubbed_documents: int = 0 

109 #: The newest turn had to be cut to fit. 

110 cut: bool = False 

111 #: The history token budget it was fitted to. 

112 budget_tokens: int = 0 

113 

114 

115# ── Limits ─────────────────────────────────────────────────────────────────── 

116 

117_limits: dict[tuple[str, str], ModelLimits] = {} 

118_limits_loaded_at = 0.0 

119_limits_lock = threading.Lock() 

120 

121 

122def _catalogue_limits() -> dict[tuple[str, str], ModelLimits]: 

123 """``(provider, model) → ModelLimits`` from the catalogue, cached.""" 

124 global _limits, _limits_loaded_at 

125 with _limits_lock: 

126 if time.monotonic() - _limits_loaded_at < LIMITS_CACHE_S: 

127 return _limits 

128 try: 

129 from app.db.postgres.engine import SessionLocal 

130 from app.db.postgres.models import LLMModel, Provider 

131 

132 db = SessionLocal() 

133 try: 

134 _limits = { 

135 ( 

136 str(getattr(provider, "value", provider)), 

137 str(model.model_name), 

138 ): ( 

139 ModelLimits( 

140 context_window=model.context_window, 

141 max_output_tokens=model.max_output_tokens, 

142 long_context_threshold=model.long_context_threshold, 

143 ) 

144 ) 

145 for provider, model in db.query(Provider.name, LLMModel) 

146 .join(Provider, LLMModel.provider_id == Provider.id) 

147 .all() 

148 } 

149 finally: 

150 db.close() 

151 except Exception: # noqa: BLE001 — LiteLLM's table, then the default 

152 logger.warning("[token_budget] could not load model limits", exc_info=True) 

153 _limits_loaded_at = time.monotonic() 

154 return _limits 

155 

156 

157def _litellm_limits(model: str) -> ModelLimits: 

158 try: 

159 import litellm 

160 

161 info = litellm.get_model_info(model) 

162 except Exception: # noqa: BLE001 — an unknown model has no entry 

163 return ModelLimits() 

164 window = info.get("max_input_tokens") 

165 output = info.get("max_output_tokens") 

166 return ModelLimits( 

167 context_window=window if isinstance(window, int) and window > 0 else None, 

168 max_output_tokens=output if isinstance(output, int) and output > 0 else None, 

169 ) 

170 

171 

172def limits_for_model(provider: str, model: str) -> ModelLimits: 

173 """What ``provider``/``model`` can take.""" 

174 found = _catalogue_limits().get((provider or "", model or "")) 

175 if found is not None and found.context_window: 

176 return found 

177 fallback = _litellm_limits(model or "") 

178 if found is None: 

179 return fallback 

180 return ModelLimits( 

181 context_window=fallback.context_window, 

182 max_output_tokens=found.max_output_tokens or fallback.max_output_tokens, 

183 long_context_threshold=found.long_context_threshold, 

184 ) 

185 

186 

187def limits_for(llm: Any) -> ModelLimits: 

188 """What the model behind a chat client can take.""" 

189 from app.services.structured_output import provider_model 

190 

191 provider, model = provider_model(llm) 

192 return limits_for_model(provider or "", model or "") 

193 

194 

195def max_output_of(llm: Any) -> int | None: 

196 """The most a chat client is set to write.""" 

197 for name in ("max_tokens", "max_completion_tokens", "max_output_tokens"): 

198 value = getattr(llm, name, None) 

199 if isinstance(value, int) and value > 0: 

200 return value 

201 return None 

202 

203 

204# ── Estimating ─────────────────────────────────────────────────────────────── 

205 

206 

207def estimate_tokens(text: str) -> int: 

208 return math.ceil(len(text or "") / CHARS_PER_TOKEN) 

209 

210 

211def text_of(content: Any) -> str: 

212 if isinstance(content, str): 

213 return content 

214 if isinstance(content, list): 

215 return " ".join( 

216 str(block.get("text", "")) if isinstance(block, dict) else str(block) 

217 for block in content 

218 ) 

219 return str(content or "") 

220 

221 

222def message_tokens(messages: list[BaseMessage]) -> int: 

223 return sum( 

224 estimate_tokens(text_of(m.content)) + MESSAGE_OVERHEAD_TOKENS for m in messages 

225 ) 

226 

227 

228def tool_tokens(tools: list[Any]) -> int: 

229 """What the tool definitions bound to a call cost, as sent.""" 

230 from langchain_core.utils.function_calling import convert_to_openai_tool 

231 

232 total = 0 

233 for tool in tools or []: 

234 try: 

235 total += estimate_tokens(safe_json.dumps(convert_to_openai_tool(tool))) 

236 except Exception: # noqa: BLE001 — a tool that will not convert costs a guess 

237 total += 200 

238 return total 

239 

240 

241def history_budget( 

242 limits: ModelLimits, 

243 *, 

244 max_output: int | None, 

245 fixed_tokens: int, 

246 reserve: int = TOOL_LOOP_RESERVE, 

247 profile_cap: int | None = None, 

248) -> int: 

249 """``H``: the history tokens a call can carry (see the module docstring). 

250 ``fixed_tokens`` is ``P + R``: everything sent besides the history.""" 

251 window = limits.context_window or DEFAULT_CONTEXT_WINDOW 

252 output = max_output or limits.max_output_tokens or 4096 

253 terms = [window - output - fixed_tokens - reserve - int(SAFETY_SHARE * window)] 

254 threshold = limits.long_context_threshold 

255 if threshold: 

256 terms.append(threshold - fixed_tokens - reserve - int(SAFETY_SHARE * threshold)) 

257 if profile_cap is not None: 

258 terms.append(profile_cap) 

259 return max(0, min(terms)) 

260 

261 

262# ── Fitting ────────────────────────────────────────────────────────────────── 

263 

264 

265def _turns(messages: list[BaseMessage]) -> list[list[BaseMessage]]: 

266 """``messages`` as turns: each from a person's message up to the next. 

267 Anything before the first (a note, an answer whose question went) is a 

268 turn of its own.""" 

269 turns: list[list[BaseMessage]] = [] 

270 for message in messages: 

271 if isinstance(message, HumanMessage) or not turns: 

272 turns.append([message]) 

273 else: 

274 turns[-1].append(message) 

275 return turns 

276 

277 

278def _stubbed(message: BaseMessage) -> tuple[BaseMessage, bool]: 

279 content = message.content 

280 if not isinstance(content, str) or "<document_content>" not in content: 

281 return message, False 

282 replaced = _DOCUMENT_BODY.sub( 

283 lambda m: f"{m.group(1)}{DOCUMENT_STUB}{m.group(3)}", content 

284 ) 

285 if replaced == content: 

286 return message, False 

287 return message.model_copy(update={"content": replaced}), True 

288 

289 

290def _cut(messages: list[BaseMessage], budget: int) -> list[BaseMessage]: 

291 """``messages`` cut to ``budget`` tokens, each keeping its share and 

292 saying it was cut.""" 

293 over = message_tokens(messages) 

294 if over <= budget or not messages: 

295 return messages 

296 share = max(budget, 0) / over 

297 out: list[BaseMessage] = [] 

298 for message in messages: 

299 text = text_of(message.content) 

300 keep = int(len(text) * share) - len(CUT_MARK) 

301 if keep < len(text): 

302 text = text[: max(keep, 0)] + CUT_MARK 

303 out.append(message.model_copy(update={"content": text})) 

304 return out 

305 

306 

307def fit(messages: list[BaseMessage], budget: int) -> Fitted: 

308 """``messages`` (a conversation, oldest first) fitted to ``budget`` 

309 tokens: documents in earlier turns stubbed, then whole turns dropped in 

310 blocks from the start, then the newest turn cut. Unchanged when it fits. 

311 System messages travel with whatever turn they sit in.""" 

312 if message_tokens(messages) <= budget: 

313 return Fitted(list(messages), budget_tokens=budget) 

314 

315 turns = _turns(list(messages)) 

316 stubbed = 0 

317 for index in range(len(turns) - 1): 

318 kept: list[BaseMessage] = [] 

319 for message in turns[index]: 

320 replaced, changed = _stubbed(message) 

321 stubbed += int(changed) 

322 kept.append(replaced) 

323 turns[index] = kept 

324 

325 def flat(from_turn: int) -> list[BaseMessage]: 

326 return [m for turn in turns[from_turn:] for m in turn] 

327 

328 if message_tokens(flat(0)) <= budget: 

329 return Fitted(flat(0), stubbed_documents=stubbed, budget_tokens=budget) 

330 

331 last = len(turns) - 1 

332 start = 0 

333 while start < last: 

334 # Whole blocks from the first turn, never the newest turn. 

335 start = min(start + BLOCK_TURNS, last) 

336 if message_tokens(flat(start)) <= budget: 

337 return Fitted( 

338 flat(start), 

339 omitted_turns=start, 

340 stubbed_documents=stubbed, 

341 budget_tokens=budget, 

342 ) 

343 return Fitted( 

344 _cut(flat(last), budget), 

345 omitted_turns=last, 

346 stubbed_documents=stubbed, 

347 cut=True, 

348 budget_tokens=budget, 

349 ) 

350 

351 

352def fit_for_call( 

353 llm: Any, 

354 history: list[BaseMessage], 

355 *, 

356 system_text: str, 

357 task_text: str, 

358 tools: list[Any] | None = None, 

359 profile_cap: int | None = None, 

360) -> Fitted: 

361 """``history`` fitted to a call to ``llm`` with this system prompt, 

362 tools and task. Never raises: a history that cannot be measured goes as 

363 it came.""" 

364 if not history: 

365 return Fitted([]) 

366 try: 

367 fixed = ( 

368 estimate_tokens(system_text) 

369 + tool_tokens(tools or []) 

370 + estimate_tokens(task_text) 

371 ) 

372 budget = history_budget( 

373 limits_for(llm), 

374 max_output=max_output_of(llm), 

375 fixed_tokens=fixed, 

376 reserve=TOOL_LOOP_RESERVE if tools else 0, 

377 profile_cap=profile_cap, 

378 ) 

379 fitted = fit(list(history), budget) 

380 except Exception: # noqa: BLE001 — a bound is worth less than the call 

381 logger.warning("[token_budget] could not fit the history", exc_info=True) 

382 return Fitted(list(history)) 

383 if fitted.omitted_turns or fitted.stubbed_documents or fitted.cut: 

384 logger.info( 

385 "[token_budget] history fitted to %d tokens: %d turns left out, " 

386 "%d documents stubbed%s", 

387 fitted.budget_tokens, 

388 fitted.omitted_turns, 

389 fitted.stubbed_documents, 

390 ", newest turn cut" if fitted.cut else "", 

391 ) 

392 return fitted 

393 

394 

395def fits( 

396 llm: Any, 

397 history: list[BaseMessage], 

398 *, 

399 system_text: str, 

400 task_text: str, 

401 tools: list[Any] | None = None, 

402 profile_cap: int | None = None, 

403) -> bool: 

404 """Whether a call to ``llm`` takes ``history`` as the profile would send 

405 it — nothing more left out, stubbed or cut for ``llm``'s own window or 

406 price tier than ``profile_cap`` already takes. What a smaller model must 

407 pass before it may answer in place of the agent's own (an Economy 

408 profile's lighter model). Unmeasurable: no.""" 

409 try: 

410 need = message_tokens(list(history)) 

411 if profile_cap is not None: 

412 need = min(need, profile_cap) 

413 fixed = ( 

414 estimate_tokens(system_text) 

415 + tool_tokens(tools or []) 

416 + estimate_tokens(task_text) 

417 ) 

418 budget = history_budget( 

419 limits_for(llm), 

420 max_output=max_output_of(llm), 

421 fixed_tokens=fixed, 

422 reserve=TOOL_LOOP_RESERVE if tools else 0, 

423 ) 

424 except Exception: # noqa: BLE001 — unmeasured is not a fit 

425 logger.warning("[token_budget] could not measure a fit", exc_info=True) 

426 return False 

427 return need <= budget 

428 

429 

430def omitted_note(fitted: Fitted) -> str: 

431 """What the answering model is told about what it cannot see — empty 

432 when it sees everything it was sent.""" 

433 parts: list[str] = [] 

434 if fitted.omitted_turns: 

435 turns = "turn" if fitted.omitted_turns == 1 else "turns" 

436 parts.append( 

437 f"The {fitted.omitted_turns} earliest {turns} of this conversation " 

438 "are not shown: the conversation is longer than this model can " 

439 "take in one request." 

440 ) 

441 if fitted.stubbed_documents: 

442 parts.append( 

443 "Documents attached in earlier turns are not repeated; their " 

444 "text is no longer in view." 

445 ) 

446 if fitted.cut: 

447 parts.append("The most recent turn was cut to fit.") 

448 if not parts: 

449 return "" 

450 return "<history_note>" + " ".join(parts) + "</history_note>"