Coverage for app / util / source_trailers.py: 100%

21 statements  

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

1"""The trailer a knowledge tool ends its result with: what the result quoted. 

2 

3A knowledge tool's result is text for the model followed by one line for 

4citation extraction — a marker and a JSON list of the sources the text 

5quoted:: 

6 

7 …passages… 

8 __SOURCES__:[{"source": "handbook.pdf", "kb_name": "Policies"}] 

9 

10An entry is a source's name, or ``{"source", "kb_name"}`` when the result 

11says which knowledge base each source came from. The tools write the 

12trailer (``rag``, ``neo4j_client``, the registry's knowledge tools) and 

13``source_ledger``'s per-tool parsers read it, both through this module, so 

14the markers and the rule for reading them have one definition. 

15 

16A result carries one trailer, at its end, read from the LAST marker. A 

17search of several knowledge bases used to end each section with its own; 

18the reader took everything after the first marker as one JSON list, found 

19none, and the result cited nothing. 

20""" 

21 

22from __future__ import annotations 

23 

24from typing import Any 

25 

26from app.util import safe_json 

27 

28#: A knowledge base search's passages (``search_knowledge``, 

29#: ``query_knowledge_base``). 

30KNOWLEDGE = "\n__SOURCES__:" 

31#: A knowledge graph's entities (``explore_graph``, ``query_knowledge_graph``). 

32GRAPH = "\n__GRAPH_SOURCES__:" 

33#: A document read in full (``read_document``). 

34DOCUMENT = "\n__FILE_SOURCES__:" 

35 

36 

37def split(text: str, marker: str) -> tuple[str, list[Any]]: 

38 """``text`` without its trailer, and the entries the trailer lists. 

39 

40 The trailer is the last ``marker`` and the JSON list that runs from it to 

41 the end of ``text``. With no marker, or one followed by anything but a 

42 list, ``text`` is returned whole and lists nothing. 

43 """ 

44 head, found, tail = (text or "").rpartition(marker) 

45 if not found: 

46 return text, [] 

47 try: 

48 entries = safe_json.loads_exact(tail) 

49 except ValueError: 

50 return text, [] 

51 if not isinstance(entries, list): 

52 return text, [] 

53 return head, entries 

54 

55 

56def append(text: str, marker: str, entries: list[Any]) -> str: 

57 """``text`` ending in the trailer that lists ``entries``; as it is when 

58 there are none.""" 

59 if not entries: 

60 return text 

61 return text + marker + safe_json.dumps(entries)