Coverage for app / tools / limits.py: 100%

35 statements  

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

1"""A tool's call limit: how it says it is spent, and how the tool loop reads it. 

2 

3``web_search``, ``url_fetch`` and ``geocode`` each allow so many calls a run 

4and answer the next one with a note instead of a result. The tool loop kept 

5offering them: in run 4 an agent made nine more calls after both web tools 

6had said so, each a model round re-sending about 35,000 tokens, before the 

7loop's own cap ended it. Now each tool words its limit through 

8:func:`reached`, and the loop reads :func:`spent` from its results and stops 

9offering a tool that is (``BaseAgent.run_with_tools``). 

10""" 

11 

12from __future__ import annotations 

13 

14import re 

15from collections.abc import Iterable 

16from typing import Any 

17 

18_REACHED = re.compile(r"^\[(?P<tool>[a-z_]+)\] call limit of \d+ reached") 

19 

20#: Where a limited tool keeps its budget (``StructuredTool.metadata``). 

21_BUDGET_KEY = "call_budget" 

22 

23 

24class Budget: 

25 """A limited tool's calls, kept with the tool. A revision runs the tool 

26 loop again with the same tools, and a tool spent in the first pass was 

27 offered in the next: pdf-brief made six more ``url_fetch`` calls after 

28 its limit across three passes.""" 

29 

30 def __init__(self, max_calls: int) -> None: 

31 self.max_calls = max(0, int(max_calls)) 

32 self.used = 0 

33 

34 def take(self) -> bool: 

35 """Count a call; False when it is past the limit.""" 

36 self.used += 1 

37 return self.used <= self.max_calls 

38 

39 @property 

40 def spent(self) -> bool: 

41 return self.used >= self.max_calls 

42 

43 

44def attach(tool: Any, budget: Budget) -> Any: 

45 """``tool`` carrying ``budget``, for :func:`is_spent`.""" 

46 tool.metadata = {**(getattr(tool, "metadata", None) or {}), _BUDGET_KEY: budget} 

47 return tool 

48 

49 

50def is_spent(tool: Any) -> bool: 

51 """Whether ``tool`` has used every call its budget allows.""" 

52 budget = (getattr(tool, "metadata", None) or {}).get(_BUDGET_KEY) 

53 return isinstance(budget, Budget) and budget.spent 

54 

55 

56def reached(tool: str, max_calls: int, then: str = "") -> str: 

57 """What a tool past its limit returns in place of a result.""" 

58 line = f"[{tool}] call limit of {max_calls} reached for this session." 

59 return f"{line} {then}" if then else line 

60 

61 

62def spent(results: Iterable[object]) -> set[str]: 

63 """The tools whose results in ``results`` (tool messages' text) say they 

64 are past their limit.""" 

65 names: set[str] = set() 

66 for text in results: 

67 match = _REACHED.match(text) if isinstance(text, str) else None 

68 if match: 

69 names.add(match.group("tool")) 

70 return names 

71 

72 

73def withdrawn_note(names: Iterable[str]) -> str: 

74 """What the model is told when tools are no longer offered.""" 

75 listed = ", ".join(sorted(names)) 

76 return ( 

77 f"{listed} reached the call limit for this turn and " 

78 f"{'is' if ',' not in listed else 'are'} no longer available. Carry on " 

79 "with what the calls already returned, or with your other tools." 

80 )