Coverage for app / services / swarms / parts.py: 95%

64 statements  

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

1"""The person's documents, read a part at a time — what a chain of agents 

2reads (``topologies.pipeline``). 

3 

4Each reader in a chain is handed one part of the documents and the notes the 

5reader before it wrote, and writes notes for the next: no agent need hold the 

6whole of a long document at once, and none reads past what it was given. The 

7parts are cut here, in the worker, from the documents as the run's workspace 

8holds them — the same cut every time, so the third reader reads what follows 

9what the second read: about ``PART_CHARS`` each, at a paragraph's end where 

10one is near, and never more than ``MAX_PARTS`` (a longer document gets longer 

11parts). A part that begins inside a document says which one it continues, so 

12a reader can say where a passage came from. 

13""" 

14 

15from __future__ import annotations 

16 

17from collections.abc import Sequence 

18from dataclasses import dataclass 

19from math import ceil 

20from typing import Any 

21 

22from app.services.attachments import TurnDocument 

23 

24#: About how long one part is. 

25PART_CHARS = 40_000 

26#: The most parts the documents are cut into. 

27MAX_PARTS = 12 

28#: How far back from a part's end a paragraph break is looked for. 

29_LOOK_BACK = 0.25 

30 

31 

32@dataclass(frozen=True) 

33class Part: 

34 """One part of the documents, and how many there are.""" 

35 

36 document: TurnDocument 

37 count: int 

38 

39 def spec(self) -> dict[str, Any]: 

40 return self.document.spec() 

41 

42 

43def _joined(library: Sequence[dict[str, Any]]) -> tuple[str, list[tuple[int, str]]]: 

44 """The readable documents as one text, and where each begins.""" 

45 text = "" 

46 starts: list[tuple[int, str]] = [] 

47 for doc in library: 

48 body = str(doc.get("text") or "").strip() 

49 if not body or doc.get("availability", "available") != "available": 

50 continue 

51 name = str(doc.get("name") or "Document") 

52 if text: 

53 text += "\n\n" 

54 starts.append((len(text), name)) 

55 text += f"# {name}\n\n{body}" 

56 return text, starts 

57 

58 

59def _cut(text: str, start: int, target: int) -> int: 

60 """Where a part beginning at ``start`` ends: ``target`` on, or the last 

61 paragraph, line or word break shortly before it.""" 

62 end = start + target 

63 if end >= len(text): 

64 return len(text) 

65 floor = end - int(target * _LOOK_BACK) 

66 for mark in ("\n\n", "\n", " "): 

67 at = text.rfind(mark, floor, end) 

68 if at > start: 

69 return at 

70 return end 

71 

72 

73def split(text: str, size: int = PART_CHARS, most: int = MAX_PARTS) -> list[int]: 

74 """Where each part of ``text`` begins: about ``size`` long, ``most`` at 

75 most.""" 

76 if not text: 

77 return [] 

78 count = min(most, max(1, ceil(len(text) / size))) 

79 target = ceil(len(text) / count) 

80 starts = [0] 

81 while len(starts) < count: 

82 end = _cut(text, starts[-1], target) 

83 if end >= len(text): 

84 break 

85 starts.append(end) 

86 return starts 

87 

88 

89def part_of(library: Sequence[dict[str, Any]], index: int) -> Part | None: 

90 """Part ``index`` (from 1) of the documents ``library`` holds (as svc-ai 

91 takes them), or None when they hold nothing readable or no such part.""" 

92 text, docs = _joined(library) 

93 starts = split(text) 

94 if not 1 <= index <= len(starts): 

95 return None 

96 begin = starts[index - 1] 

97 end = starts[index] if index < len(starts) else len(text) 

98 raw = text[begin:end] 

99 body = raw.strip() 

100 # Where its words begin: a part cut at a break starts after it. 

101 first = begin + len(raw) - len(raw.lstrip()) 

102 within = [name for at, name in docs if at <= first] 

103 if within and not any(at == first for at, _ in docs): 

104 body = f"(Continued from {within[-1]}.)\n\n{body}" 

105 return Part( 

106 document=TurnDocument( 

107 id=f"swarm-part-{index}", 

108 name=f"Part {index} of {len(starts)}", 

109 mime_type="text/markdown", 

110 text=body, 

111 ), 

112 count=len(starts), 

113 )