Coverage for app / util / vocab.py: 98%

66 statements  

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

1"""Render a vocabulary into prompt text from the data structure that defines it. 

2 

3A prompt that spells out its options by hand drifts from the code that 

4enforces them: a value is added, renamed or removed, and the prompt goes on 

5offering the old set. The agent generator told models to use the ``log`` audit 

6action for months after it was removed, while the schema beside it refused 

7that very value. So every list of options a model is shown is rendered from 

8its source — a ``Literal``, an ``Enum``, a registry's keys — through these 

9helpers, and ``tests/test_prompt_vocabulary.py`` fails on any prompt string 

10that enumerates a vocabulary by hand. 

11 

12* :func:`values` — the vocabulary itself, in declaration order. 

13* :func:`one_of` — ``'a', 'b' or 'c'``, for prose. 

14* :func:`listing` — ``a | b | c``, for schema-like lines. 

15* :func:`guide` — one described line per value. Raises 

16 :class:`VocabularyDrift` when the descriptions and the vocabulary disagree, 

17 so a value added without guidance, or guidance left behind for a removed 

18 value, fails at import instead of reaching a model. 

19* :func:`member` / :func:`members` — values named one at a time in prose, 

20 checked to exist. 

21""" 

22 

23from __future__ import annotations 

24 

25import types 

26from collections.abc import Iterable, Mapping 

27from enum import Enum 

28from typing import Any, Literal, Union, get_args, get_origin 

29 

30 

31class VocabularyDrift(ValueError): 

32 """A prompt and the vocabulary it describes no longer match.""" 

33 

34 

35def _text(value: Any) -> str: 

36 return str(value.value if isinstance(value, Enum) else value) 

37 

38 

39def values(source: Any) -> tuple[str, ...]: 

40 """The values of a ``Literal`` type, an ``Enum`` class, a mapping or an iterable. 

41 

42 ``Optional[Literal[...]]`` is read through its ``None``. A set has no 

43 order of its own, so its values are sorted; everything else keeps the 

44 order it was declared in, which is the order a prompt lists them. 

45 """ 

46 origin = get_origin(source) 

47 if origin is Union or isinstance(source, types.UnionType): 

48 found: list[str] = [] 

49 for arg in get_args(source): 

50 if arg is not type(None): 

51 found.extend(values(arg)) 

52 return tuple(dict.fromkeys(found)) 

53 if origin is Literal: 

54 return tuple(_text(v) for v in get_args(source)) 

55 if isinstance(source, type) and issubclass(source, Enum): 

56 return tuple(_text(member) for member in source) 

57 if isinstance(source, Mapping): 

58 return tuple(_text(key) for key in source) 

59 if isinstance(source, (str, bytes)): 

60 raise TypeError("a vocabulary is a collection of values, not one string") 

61 if isinstance(source, (set, frozenset)): 

62 return tuple(sorted(_text(v) for v in source)) 

63 if isinstance(source, Iterable): 

64 return tuple(_text(v) for v in source) 

65 raise TypeError(f"cannot read a vocabulary from {source!r}") 

66 

67 

68def _quoted(value: str, quote: str) -> str: 

69 return f"{quote}{value}{quote}" 

70 

71 

72def listing(source: Any, *, sep: str = " | ", quote: str = "") -> str: 

73 """``a | b | c`` — every value, joined.""" 

74 return sep.join(_quoted(v, quote) for v in values(source)) 

75 

76 

77def one_of(source: Any, *, quote: str = "'", conjunction: str = "or") -> str: 

78 """``'a', 'b' or 'c'`` — every value, as a phrase.""" 

79 items = [_quoted(v, quote) for v in values(source)] 

80 if len(items) <= 1: 

81 return "".join(items) 

82 return f"{', '.join(items[:-1])} {conjunction} {items[-1]}" 

83 

84 

85def member(source: Any, value: str) -> str: 

86 """``value``, checked to be one of ``source``'s — for naming one in prose.""" 

87 if value not in values(source): 

88 raise VocabularyDrift( 

89 f"{value!r} is not in the vocabulary it is named from: " 

90 f"{', '.join(values(source))}" 

91 ) 

92 return value 

93 

94 

95def members(source: Any, chosen: Iterable[Any]) -> tuple[str, ...]: 

96 """A subset of ``source``, each value checked — for a deliberate selection.""" 

97 return tuple(member(source, _text(value)) for value in chosen) 

98 

99 

100def check(descriptions: Mapping[Any, str], source: Any) -> None: 

101 """Raise :class:`VocabularyDrift` unless ``descriptions`` covers exactly ``source``.""" 

102 described = values(descriptions) 

103 expected = values(source) 

104 missing = [v for v in expected if v not in described] 

105 stale = [v for v in described if v not in expected] 

106 if missing or stale: 

107 problems = [] 

108 if missing: 

109 problems.append(f"no description for {', '.join(missing)}") 

110 if stale: 

111 problems.append( 

112 f"descriptions for values that no longer exist: {', '.join(stale)}" 

113 ) 

114 raise VocabularyDrift("; ".join(problems)) 

115 

116 

117def guide( 

118 descriptions: Mapping[Any, str], 

119 source: Any | None = None, 

120 *, 

121 indent: str = " ", 

122 sep: str = " — ", 

123 quote: str = "", 

124 align: bool = True, 

125 end: str = "", 

126 joiner: str = "\n", 

127) -> str: 

128 """One line per value: `` value — what it means``. 

129 

130 With ``source`` given, ``descriptions`` must cover exactly its values 

131 (see :func:`check`), and the lines follow the vocabulary's own order. 

132 ``sep=" (", end=")", joiner=", ", align=False`` gives the inline form 

133 ``'bar' (one metric per category), 'pie' (proportions)``. 

134 """ 

135 if source is not None: 

136 check(descriptions, source) 

137 order = values(source) 

138 else: 

139 order = values(descriptions) 

140 text = {_text(key): description for key, description in descriptions.items()} 

141 width = max((len(_quoted(v, quote)) for v in order), default=0) if align else 0 

142 return joiner.join( 

143 f"{indent}{_quoted(v, quote).ljust(width)}{sep}{text[v]}{end}" for v in order 

144 ) 

145 

146 

147def inline(descriptions: Mapping[Any, str], source: Any | None = None) -> str: 

148 """``'a' (what a means), 'b' (what b means)`` — a guide inside a sentence.""" 

149 return guide( 

150 descriptions, source, indent="", sep=" (", end=")", quote="'", 

151 align=False, joiner=", ", 

152 ) # fmt: skip