Coverage for app / util / vocab.py: 79%
66 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""Render a vocabulary into prompt text from the data structure that defines it.
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. svc-ai's agent generator told models to use the ``log``
6audit action for months after it was removed. So every list of options a
7model is shown — a widget's config values, a rule's vocabulary, a source
8type — is rendered from its source (a ``Literal``, an ``Enum``, a registry's
9keys) through these helpers, and ``tests/test_prompt_vocabulary.py`` fails on
10any prompt string that enumerates a vocabulary by hand. svc-ai carries the
11same module; the two services share no Python package.
13* :func:`values` — the vocabulary itself, in declaration order.
14* :func:`one_of` — ``'a', 'b' or 'c'``, for prose.
15* :func:`listing` — ``a | b | c``, for schema-like lines.
16* :func:`guide` — one described line per value. Raises
17 :class:`VocabularyDrift` when the descriptions and the vocabulary disagree,
18 so a value added without guidance, or guidance left behind for a removed
19 value, fails at import instead of reaching a model.
20* :func:`member` / :func:`members` — values named one at a time in prose,
21 checked to exist.
22"""
24from __future__ import annotations
26import types
27from collections.abc import Iterable, Mapping
28from enum import Enum
29from typing import Any, Literal, Union, get_args, get_origin
32class VocabularyDrift(ValueError):
33 """A prompt and the vocabulary it describes no longer match."""
36def _text(value: Any) -> str:
37 return str(value.value if isinstance(value, Enum) else value)
40def values(source: Any) -> tuple[str, ...]:
41 """The values of a ``Literal`` type, an ``Enum`` class, a mapping or an iterable.
43 ``Optional[Literal[...]]`` is read through its ``None``. A set has no
44 order of its own, so its values are sorted; everything else keeps the
45 order it was declared in, which is the order a prompt lists them.
46 """
47 origin = get_origin(source)
48 if origin is Union or isinstance(source, types.UnionType):
49 found: list[str] = []
50 for arg in get_args(source):
51 if arg is not type(None):
52 found.extend(values(arg))
53 return tuple(dict.fromkeys(found))
54 if origin is Literal:
55 return tuple(_text(v) for v in get_args(source))
56 if isinstance(source, type) and issubclass(source, Enum):
57 return tuple(_text(member) for member in source)
58 if isinstance(source, Mapping):
59 return tuple(_text(key) for key in source)
60 if isinstance(source, (str, bytes)):
61 raise TypeError("a vocabulary is a collection of values, not one string")
62 if isinstance(source, (set, frozenset)):
63 return tuple(sorted(_text(v) for v in source))
64 if isinstance(source, Iterable):
65 return tuple(_text(v) for v in source)
66 raise TypeError(f"cannot read a vocabulary from {source!r}")
69def _quoted(value: str, quote: str) -> str:
70 return f"{quote}{value}{quote}"
73def listing(source: Any, *, sep: str = " | ", quote: str = "") -> str:
74 """``a | b | c`` — every value, joined."""
75 return sep.join(_quoted(v, quote) for v in values(source))
78def one_of(source: Any, *, quote: str = "'", conjunction: str = "or") -> str:
79 """``'a', 'b' or 'c'`` — every value, as a phrase."""
80 items = [_quoted(v, quote) for v in values(source)]
81 if len(items) <= 1:
82 return "".join(items)
83 return f"{', '.join(items[:-1])} {conjunction} {items[-1]}"
86def member(source: Any, value: str) -> str:
87 """``value``, checked to be one of ``source``'s — for naming one in prose."""
88 if value not in values(source):
89 raise VocabularyDrift(
90 f"{value!r} is not in the vocabulary it is named from: "
91 f"{', '.join(values(source))}"
92 )
93 return value
96def members(source: Any, chosen: Iterable[Any]) -> tuple[str, ...]:
97 """A subset of ``source``, each value checked — for a deliberate selection."""
98 return tuple(member(source, _text(value)) for value in chosen)
101def check(descriptions: Mapping[Any, str], source: Any) -> None:
102 """Raise :class:`VocabularyDrift` unless ``descriptions`` covers exactly ``source``."""
103 described = values(descriptions)
104 expected = values(source)
105 missing = [v for v in expected if v not in described]
106 stale = [v for v in described if v not in expected]
107 if missing or stale:
108 problems = []
109 if missing:
110 problems.append(f"no description for {', '.join(missing)}")
111 if stale:
112 problems.append(
113 f"descriptions for values that no longer exist: {', '.join(stale)}"
114 )
115 raise VocabularyDrift("; ".join(problems))
118def guide(
119 descriptions: Mapping[Any, str],
120 source: Any | None = None,
121 *,
122 indent: str = " ",
123 sep: str = " — ",
124 quote: str = "",
125 align: bool = True,
126 end: str = "",
127 joiner: str = "\n",
128) -> str:
129 """One line per value: `` value — what it means``.
131 With ``source`` given, ``descriptions`` must cover exactly its values
132 (see :func:`check`), and the lines follow the vocabulary's own order.
133 ``sep=" (", end=")", joiner=", ", align=False`` gives the inline form
134 ``'bar' (one metric per category), 'pie' (proportions)``.
135 """
136 if source is not None:
137 check(descriptions, source)
138 order = values(source)
139 else:
140 order = values(descriptions)
141 text = {_text(key): description for key, description in descriptions.items()}
142 width = max((len(_quoted(v, quote)) for v in order), default=0) if align else 0
143 return joiner.join(
144 f"{indent}{_quoted(v, quote).ljust(width)}{sep}{text[v]}{end}" for v in order
145 )
148def inline(descriptions: Mapping[Any, str], source: Any | None = None) -> str:
149 """``'a' (what a means), 'b' (what b means)`` — a guide inside a sentence."""
150 return guide(
151 descriptions, source, indent="", sep=" (", end=")", quote="'",
152 align=False, joiner=", ",
153 ) # fmt: skip