Coverage for app / util / history_window.py: 94%

18 statements  

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

1""" 

2How much of a stored conversation svc-core sends with a turn. 

3 

4svc-core used to send every message of a conversation, however long, though 

5svc-ai's agent path reads only its last turns: a long chat paid to ship its 

6whole past on every turn, and a direct model chat sent all of it to the 

7model. This is the outer bound — the newest messages that fit a count and a 

8size — and svc-ai fits what it receives to the model's own budget. 

9 

10System messages always go: a chat's system prompt is stored once, at the 

11start, and dropping it with the old turns would change who the model is. 

12""" 

13 

14from __future__ import annotations 

15 

16from typing import Any, Callable 

17 

18#: The most earlier messages a turn sends — 50 exchanges. 

19MAX_HISTORY_MESSAGES = 100 

20#: The most characters of earlier messages a turn sends (~250K tokens). 

21MAX_HISTORY_CHARS = 1_000_000 

22 

23 

24def newest( 

25 messages: list[Any], 

26 *, 

27 role: Callable[[Any], str], 

28 content: Callable[[Any], str], 

29 max_messages: int = MAX_HISTORY_MESSAGES, 

30 max_chars: int = MAX_HISTORY_CHARS, 

31) -> list[Any]: 

32 """The newest of ``messages`` within both bounds, in their order, with 

33 every system message kept. A message that would cross a bound stops it: 

34 the history never skips a message to fit an older one.""" 

35 kept: set[int] = set() 

36 count = chars = 0 

37 for index in range(len(messages) - 1, -1, -1): 

38 message = messages[index] 

39 if role(message) == "system": 

40 continue 

41 size = len(content(message) or "") 

42 if count + 1 > max_messages or chars + size > max_chars: 

43 break 

44 kept.add(index) 

45 count += 1 

46 chars += size 

47 return [ 

48 message 

49 for index, message in enumerate(messages) 

50 if index in kept or role(message) == "system" 

51 ]