Coverage for app / tools / attachments.py: 97%

211 statements  

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

1"""The tools an agent reads the conversation's attached documents with. 

2 

3A document the person attached is shown to the answering model whole when it 

4fits its share of the request (``attachments.plan``); a longer one is listed 

5with its opening, and these two tools read the rest: 

6 

7* ``read_attachment(document, offset)`` — a part of the document's text from 

8 a character offset, saying where the next part begins; 

9* ``search_attachments(query, document, top_k)`` — the passages of the 

10 documents that share the query's words, each with where it is, for 

11 ``read_attachment`` to read on from. 

12 

13**Bound whenever the conversation has a document**, not only a long one 

14(``graph._attachment_tools``), and described without naming any: the tools a 

15provider caches before the system prompt stay the same from the first 

16document on (``prompt_cache``). Each answering step builds them from the 

17run's state, so a resumed run has them too. 

18 

19**Cited by the document's id.** Both open each block with ``Cite as: [S1]`` 

20and end with the documents trailer (``source_trailers.DOCUMENT``) naming the 

21documents they quoted, so what an answer takes from either is listed under 

22the document once (``source_ledger``). 

23 

24**No model, no network.** The text is the run's own 

25(``GraphState.attachments``) and search is word overlap in process 

26(``memory.lexical``), so neither costs anything or has an ``llm_paths`` 

27entry. 

28""" 

29 

30from __future__ import annotations 

31 

32import re 

33from collections.abc import Sequence 

34from typing import NamedTuple 

35 

36from langchain_core.tools import StructuredTool 

37from pydantic import BaseModel, Field 

38 

39from app.memory import lexical 

40from app.services import token_budget 

41from app.tools.wire import platform_owned 

42from app.util import attachments as attachment_util 

43from app.util import source_trailers, text_pages 

44from app.util.attachments import ATTACHED_LABELS, UNAVAILABLE_LABELS, Attachment 

45from app.util.logger import get_logger 

46 

47logger = get_logger(__name__) 

48 

49READ_ATTACHMENT_TOOL = attachment_util.READ_TOOL 

50SEARCH_ATTACHMENTS_TOOL = attachment_util.SEARCH_TOOL 

51TOOL_NAMES = frozenset({READ_ATTACHMENT_TOOL, SEARCH_ATTACHMENTS_TOOL}) 

52 

53#: The most of a document one ``read_attachment`` call returns, in 

54#: characters (~11,400 tokens); less for a model whose window is small 

55#: (:func:`page_chars`). 

56PAGE_CHARS = 40_000 

57#: The least a page holds, however small the window. 

58MIN_PAGE_CHARS = 4_000 

59#: A searched passage, and how much of the one before it it repeats. 

60PASSAGE_CHARS = 1_200 

61PASSAGE_OVERLAP = 200 

62DEFAULT_HITS = 6 

63MAX_HITS = 10 

64#: Added to a passage's score when it holds the query as written. 

65_PHRASE_BONUS = 0.5 

66 

67_SPACE = re.compile(r"\s+") 

68_PARAGRAPH_BREAK = re.compile(r"\n[ \t]*\n\s*") 

69 

70 

71def page_chars(context_window: int | None) -> int: 

72 """How much of a document one read returns, for a model with this 

73 window: a page, or the documents' share of a smaller window.""" 

74 share = int( 

75 attachment_util.inline_budget(context_window) * token_budget.CHARS_PER_TOKEN 

76 ) 

77 return max(MIN_PAGE_CHARS, min(PAGE_CHARS, share)) 

78 

79 

80def _next_start(text: str, at: int, end: int) -> int: 

81 """A part's start at ``at`` or just after, at the beginning of a word.""" 

82 space = _SPACE.search(text, at, end) 

83 return space.end() if space and space.end() < end else at 

84 

85 

86def _paragraphs(text: str) -> list[tuple[int, int]]: 

87 """The ``(start, end)`` of each paragraph of ``text``: the runs between 

88 blank lines.""" 

89 spans: list[tuple[int, int]] = [] 

90 pos = 0 

91 for brk in _PARAGRAPH_BREAK.finditer(text): 

92 if brk.start() > pos: 

93 spans.append((pos, brk.start())) 

94 pos = brk.end() 

95 if pos < len(text): 

96 spans.append((pos, len(text))) 

97 return spans 

98 

99 

100def passages( 

101 text: str, size: int = PASSAGE_CHARS, overlap: int = PASSAGE_OVERLAP 

102) -> list[tuple[int, int]]: 

103 """The ``(start, end)`` spans search reads ``text`` in, a paragraph's 

104 start a passage's wherever it can be: short paragraphs together up to 

105 about ``size`` characters, a long one in parts that end at a line, 

106 sentence or word and repeat the last ``overlap`` of the part before, so 

107 a sentence cut across two is whole in one.""" 

108 spans: list[tuple[int, int]] = [] 

109 for start, stop in _paragraphs(text): 

110 if spans and stop - spans[-1][0] <= size and spans[-1][1] < start: 

111 spans[-1] = (spans[-1][0], stop) 

112 continue 

113 while True: 

114 end = ( 

115 stop 

116 if stop - start <= size 

117 else text_pages.boundary(text, start, start + size, size // 3) 

118 ) 

119 spans.append((start, end)) 

120 if end >= stop: 

121 break 

122 start = max( 

123 _next_start(text, max(end - overlap, start + 1), end), start + 1 

124 ) 

125 return spans 

126 

127 

128def _when(a: Attachment) -> str: 

129 return ATTACHED_LABELS[a.attached_in] 

130 

131 

132def _label(a: Attachment) -> str: 

133 return f"[{a.citation_id}] {a.name}" if a.citation_id else a.name 

134 

135 

136def listing(attachments: Sequence[Attachment]) -> str: 

137 """One line per document attached to the conversation.""" 

138 lines = [] 

139 for a in attachments: 

140 if a.readable: 

141 lines.append( 

142 f"- {_label(a)} — about {a.tokens:,} tokens, attached {_when(a)}" 

143 ) 

144 else: 

145 reason = UNAVAILABLE_LABELS.get(a.availability, "not available") 

146 lines.append(f"- {a.name} — attached {_when(a)}; {reason}") 

147 return "\n".join(lines) 

148 

149 

150def _not_readable(a: Attachment) -> str: 

151 reason = UNAVAILABLE_LABELS.get(a.availability, "not available") 

152 return ( 

153 f"{a.name} was attached {_when(a)}, but its text is not available " 

154 f"({reason}). Say so if the answer needs it — never guess what it says." 

155 ) 

156 

157 

158def _query(document: str) -> str: 

159 return (document or "").strip().strip("[]").strip() 

160 

161 

162def strong_match(attachments: Sequence[Attachment], document: str) -> Attachment | None: 

163 """The one document ``document`` names beyond doubt — by its id, or by 

164 its name as written (case and separators aside; the extension too, when 

165 ``document`` gives none) — else None.""" 

166 from app.knowledge.documents import name_key, split_ext 

167 

168 query = _query(document) 

169 if not query: 

170 return None 

171 for a in attachments: 

172 if (a.citation_id and query.upper() == a.citation_id.upper()) or query == a.id: 

173 return a 

174 key = name_key(query) 

175 bare = not split_ext(query)[1] 

176 found = [ 

177 a 

178 for a in attachments 

179 if name_key(a.name) == key 

180 or (bare and name_key(a.name, drop_ext=True) == name_key(query, drop_ext=True)) 

181 ] 

182 return found[0] if len(found) == 1 else None 

183 

184 

185def resolve(attachments: Sequence[Attachment], document: str) -> Attachment | str: 

186 """The document ``document`` names — by id or by name, approximate 

187 names resolved — or what to tell the model instead.""" 

188 from app.knowledge.documents import ATTACHED_KB, DocumentRef, match_document 

189 

190 query = _query(document) 

191 if not query: 

192 if len(attachments) == 1: 

193 return attachments[0] 

194 return ( 

195 "Name the document: its id or its name. The documents attached to " 

196 "this conversation:\n" + listing(attachments) 

197 ) 

198 found = strong_match(attachments, query) 

199 if found is not None: 

200 return found 

201 refs = [ 

202 DocumentRef(kb_id=ATTACHED_KB, document_id=a.id, original_filename=a.name) 

203 for a in attachments 

204 ] 

205 best, alternatives = match_document(query, refs) 

206 if best is not None: 

207 same = [a for a in attachments if a.name == best.original_filename] 

208 if len(same) == 1: 

209 return same[0] 

210 alternatives = [ 

211 r for r in refs if r.original_filename == best.original_filename 

212 ] 

213 message = f"No document attached to this conversation is called '{query}'." 

214 if alternatives: 

215 by_id = {a.id: a for a in attachments} 

216 message += " Did you mean one of these? Name it by its id:\n" + listing( 

217 [by_id[r.document_id] for r in alternatives if r.document_id in by_id] 

218 ) 

219 else: 

220 message += " The documents attached to it:\n" + listing(attachments) 

221 return message 

222 

223 

224def _trailer(text: str, quoted: Sequence[Attachment]) -> str: 

225 entries: list[dict[str, str]] = [] 

226 for a in quoted: 

227 entry = {"source": a.name} 

228 if a.citation_id: 

229 entry["citation_id"] = a.citation_id 

230 if entry not in entries: 

231 entries.append(entry) 

232 return source_trailers.append(text, source_trailers.DOCUMENT, entries) 

233 

234 

235def _cite(a: Attachment) -> str: 

236 return f"Cite as: [{a.citation_id}]\n" if a.citation_id else "" 

237 

238 

239def read_page(a: Attachment, offset: int = 0, page: int = PAGE_CHARS) -> str: 

240 """A part of ``a``'s text from ``offset``, as ``read_attachment`` returns 

241 it: its id, where the part is, and where the next begins.""" 

242 if not a.readable: 

243 return _not_readable(a) 

244 size = len(a.text) 

245 offset = max(0, int(offset or 0)) 

246 if offset >= size: 

247 return ( 

248 f"{a.name} has {size:,} characters; offset {offset:,} is past its " 

249 "end. Read from offset 0, or from an offset a passage gave." 

250 ) 

251 end = text_pages.boundary(a.text, offset, offset + page, page // 10) 

252 head = ( 

253 f"{_cite(a)}# {a.name}\nAttached {_when(a)} · about {a.tokens:,} tokens · " 

254 f"characters {offset:,}–{end:,} of {size:,}" 

255 ) 

256 if end < size: 

257 ref = a.citation_id or a.name 

258 tail = ( 

259 f"[Continues: call {READ_ATTACHMENT_TOOL} with document " 

260 f'"{ref}" and offset {end} for the next part.]' 

261 ) 

262 elif a.truncated: 

263 tail = ( 

264 "[End of what CHAIN-R carries of this document: it is longer, and " 

265 "was cut before it reached you.]" 

266 ) 

267 else: 

268 tail = "[End of the document.]" 

269 logger.info( 

270 "[attachments] read id=%s offset=%d chars=%d", 

271 a.citation_id, 

272 offset, 

273 end - offset, 

274 ) 

275 return _trailer(f"{head}\n\n{a.text[offset:end]}\n\n{tail}", [a]) 

276 

277 

278class _Passage(NamedTuple): 

279 attachment: Attachment 

280 start: int 

281 end: int 

282 terms: list[str] 

283 

284 

285class _Index: 

286 """The passages of a conversation's readable documents, split once.""" 

287 

288 def __init__(self) -> None: 

289 self._by_id: dict[str, list[_Passage]] = {} 

290 

291 def of(self, a: Attachment) -> list[_Passage]: 

292 if a.id not in self._by_id: 

293 self._by_id[a.id] = [ 

294 _Passage(a, s, e, lexical.terms(a.text[s:e])) 

295 for s, e in passages(a.text) 

296 ] 

297 return self._by_id[a.id] 

298 

299 

300def _flat(text: str) -> str: 

301 return " ".join(text.lower().split()) 

302 

303 

304def search( 

305 attachments: Sequence[Attachment], 

306 query: str, 

307 top_k: int = DEFAULT_HITS, 

308 index: _Index | None = None, 

309) -> str: 

310 """The passages of ``attachments`` that bear on ``query``, best first, 

311 as ``search_attachments`` returns them.""" 

312 readable = [a for a in attachments if a.readable] 

313 if not readable: 

314 return ( 

315 "None of the documents attached to this conversation can be read:\n" 

316 + listing(attachments) 

317 ) 

318 wanted = lexical.terms(query) 

319 if not wanted: 

320 return ( 

321 f'"{query}" has no words to look for. Search for the names, terms ' 

322 f"or figures the answer needs, or read the document with " 

323 f"{READ_ATTACHMENT_TOOL}." 

324 ) 

325 index = index or _Index() 

326 candidates = [p for a in readable for p in index.of(a)] 

327 corpus = lexical.Corpus(p.terms for p in candidates) 

328 phrase = _flat(query) 

329 want = set(wanted) 

330 scored = [] 

331 for order, p in enumerate(candidates): 

332 score = lexical.coverage(wanted, p.terms, corpus) 

333 if score <= 0: 

334 continue 

335 if len(phrase) >= 4 and phrase in _flat(p.attachment.text[p.start : p.end]): 

336 score += _PHRASE_BONUS 

337 held = sum(1 for t in p.terms if t in want) 

338 scored.append((score, held, -order, p)) 

339 scored.sort(key=lambda s: (s[0], s[1], s[2]), reverse=True) 

340 

341 chosen: list[_Passage] = [] 

342 for *_, p in scored: 

343 if len(chosen) >= top_k: 

344 break 

345 # Passages overlap their neighbours: one hit, not two of one place. 

346 if any( 

347 c.attachment.id == p.attachment.id and c.start < p.end and p.start < c.end 

348 for c in chosen 

349 ): 

350 continue 

351 chosen.append(p) 

352 logger.info( 

353 "[attachments] search documents=%d passages=%d hits=%d", 

354 len(readable), 

355 len(candidates), 

356 len(chosen), 

357 ) 

358 if not chosen: 

359 return ( 

360 f'No passage of the attached documents holds the words of "{query}". ' 

361 f"Try other words, or read the document with {READ_ATTACHMENT_TOOL}." 

362 ) 

363 blocks = [ 

364 f"{_cite(p.attachment)}## {p.attachment.name} — characters " 

365 f"{p.start:,}–{p.end:,} of {len(p.attachment.text):,}\n" 

366 f"{p.attachment.text[p.start : p.end].strip()}" 

367 for p in chosen 

368 ] 

369 head = ( 

370 f"{len(chosen)} passage{'s' if len(chosen) != 1 else ''} of the attached " 

371 f'documents match "{query}", best first. To read on from one, call ' 

372 f"{READ_ATTACHMENT_TOOL} with its document and its start as the offset." 

373 ) 

374 return _trailer(head + "\n\n" + "\n\n".join(blocks), [p.attachment for p in chosen]) 

375 

376 

377class _ReadInput(BaseModel): 

378 document: str = Field( 

379 description=( 

380 "The attached document to read: its id as the request shows it " 

381 "(e.g. S1), or its name. Approximate names are resolved." 

382 ) 

383 ) 

384 offset: int = Field( 

385 default=0, 

386 ge=0, 

387 description=( 

388 "Where to start, in characters from the beginning: 0 for the " 

389 "opening. Each part says where the next one begins." 

390 ), 

391 ) 

392 

393 

394class _SearchInput(BaseModel): 

395 query: str = Field( 

396 description=( 

397 "What to look for: the words, names, terms or figures the answer " 

398 "needs. They are matched as written, in any order." 

399 ) 

400 ) 

401 document: str = Field( 

402 default="", 

403 description=( 

404 "Optional. One attached document's id (e.g. S1) or name; leave " 

405 "empty to search them all." 

406 ), 

407 ) 

408 top_k: int = Field( 

409 default=DEFAULT_HITS, ge=1, le=MAX_HITS, description="How many passages." 

410 ) 

411 

412 

413def make_attachment_tools( 

414 attachments: Sequence[Attachment], context_window: int | None = None 

415) -> list[StructuredTool]: 

416 """``read_attachment`` and ``search_attachments`` over ``attachments``; 

417 none when the conversation has no document. ``context_window`` is the 

418 answering model's: a small one reads in smaller parts.""" 

419 docs = list(attachments) 

420 if not docs: 

421 return [] 

422 page = page_chars(context_window) 

423 index = _Index() 

424 

425 def _read(document: str, offset: int = 0) -> str: 

426 found = resolve(docs, document) 

427 if isinstance(found, str): 

428 return found 

429 return read_page(found, offset, page) 

430 

431 def _search(query: str, document: str = "", top_k: int = DEFAULT_HITS) -> str: 

432 scope = docs 

433 if _query(document): 

434 found = resolve(docs, document) 

435 if isinstance(found, str): 

436 return found 

437 scope = [found] 

438 return search( 

439 scope, query, max(1, min(int(top_k or DEFAULT_HITS), MAX_HITS)), index 

440 ) 

441 

442 return [ 

443 platform_owned( 

444 StructuredTool.from_function( 

445 func=_read, 

446 name=READ_ATTACHMENT_TOOL, 

447 description=( 

448 "Read a document the person attached to this conversation, " 

449 "a part at a time, from a character offset. Use it when a " 

450 "document is shown only as its opening, or to read on from " 

451 f"a passage {SEARCH_ATTACHMENTS_TOOL} found." 

452 ), 

453 args_schema=_ReadInput, 

454 ) 

455 ), 

456 platform_owned( 

457 StructuredTool.from_function( 

458 func=_search, 

459 name=SEARCH_ATTACHMENTS_TOOL, 

460 description=( 

461 "Find the passages of the documents the person attached to " 

462 "this conversation that hold a question's words. Each says " 

463 f"where it is, for {READ_ATTACHMENT_TOOL} to read on from." 

464 ), 

465 args_schema=_SearchInput, 

466 ) 

467 ), 

468 ]