|
| 1 | +"""Asking a model to interpret, and checking that it only did that. |
| 2 | +
|
| 3 | +One function, because the rule it enforces is the one that separates a |
| 4 | +research organization from a very articulate opinion generator: |
| 5 | +
|
| 6 | + **An agent may only state figures it was shown.** |
| 7 | +
|
| 8 | +The subtlety that makes this worth centralising: the set of permitted numerals |
| 9 | +must be derived from *exactly* the material that was rendered into the prompt. |
| 10 | +Building the prompt from one structure and validating against another is an |
| 11 | +easy mistake — it was made twice while writing M2 — and it fails in the worst |
| 12 | +possible direction, rejecting honest output while letting invented figures |
| 13 | +through whenever the two structures happen to diverge. |
| 14 | +
|
| 15 | +Here the material is rendered and validated from the same object, so the two |
| 16 | +cannot drift. |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import re |
| 22 | +from typing import TYPE_CHECKING, Any |
| 23 | + |
| 24 | +from aurelis.core.enums import ModelTier |
| 25 | +from aurelis.platform.budget.ledger import Spend |
| 26 | +from aurelis.platform.llm.types import LlmRequest, LlmResponse, Message, ModelRef |
| 27 | + |
| 28 | +if TYPE_CHECKING: |
| 29 | + from aurelis.agents.loop import AgentContext |
| 30 | + |
| 31 | +__all__ = [ |
| 32 | + "Interpretation", |
| 33 | + "UnsourcedFigures", |
| 34 | + "allowed_figures", |
| 35 | + "interpret", |
| 36 | + "render_material", |
| 37 | + "unsourced_numerals", |
| 38 | +] |
| 39 | + |
| 40 | +#: Numerals that may appear in prose without being a claim about the data. |
| 41 | +#: Deliberately tiny: small counts and ordinals are unavoidable in English |
| 42 | +#: ("two things stand out"), and everything else must be sourced. |
| 43 | +_FREE_NUMERALS = frozenset({"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}) |
| 44 | + |
| 45 | +_NUMERAL = re.compile(r"-?\d+(?:[.,]\d+)*%?") |
| 46 | + |
| 47 | + |
| 48 | +def unsourced_numerals(text: str, allowed: set[str]) -> list[str]: |
| 49 | + """Numerals in ``text`` that do not appear in the measurements. |
| 50 | +
|
| 51 | + The check is deliberately literal: a figure is either one the tools |
| 52 | + produced or it is not. Matching "approximately" would defeat the purpose, |
| 53 | + since a model that rounds 1.47 to 1.5 has stated a number nothing |
| 54 | + supports. |
| 55 | + """ |
| 56 | + found: list[str] = [] |
| 57 | + for match in _NUMERAL.finditer(text): |
| 58 | + token = match.group(0) |
| 59 | + bare = token.rstrip("%").replace(",", "") |
| 60 | + if bare in _FREE_NUMERALS or bare in allowed: |
| 61 | + continue |
| 62 | + # Tolerate a trailing zero difference: "0.50" cites "0.5". |
| 63 | + if bare.rstrip("0").rstrip(".") in {a.rstrip("0").rstrip(".") for a in allowed}: |
| 64 | + continue |
| 65 | + found.append(token) |
| 66 | + return found |
| 67 | + |
| 68 | + |
| 69 | +def allowed_figures(*payloads: dict[str, Any]) -> set[str]: |
| 70 | + """Every numeric token the agent was actually shown.""" |
| 71 | + allowed: set[str] = set() |
| 72 | + |
| 73 | + def walk(value: Any) -> None: |
| 74 | + if isinstance(value, dict): |
| 75 | + for item in value.values(): |
| 76 | + walk(item) |
| 77 | + elif isinstance(value, list): |
| 78 | + for item in value: |
| 79 | + walk(item) |
| 80 | + elif isinstance(value, str): |
| 81 | + for match in _NUMERAL.finditer(value): |
| 82 | + allowed.add(match.group(0).rstrip("%").replace(",", "")) |
| 83 | + elif isinstance(value, (int, float)): |
| 84 | + allowed.add(str(value)) |
| 85 | + |
| 86 | + for payload in payloads: |
| 87 | + walk(payload) |
| 88 | + return allowed |
| 89 | + |
| 90 | + |
| 91 | + |
| 92 | +class UnsourcedFigures(ValueError): |
| 93 | + """The model stated a number nothing it was shown supports.""" |
| 94 | + |
| 95 | + def __init__(self, invented: list[str], shown: int) -> None: |
| 96 | + super().__init__( |
| 97 | + f"output cites {len(invented)} figure(s) not present in the " |
| 98 | + f"{shown} value(s) supplied: {', '.join(invented[:5])}. " |
| 99 | + "Agents interpret; software computes." |
| 100 | + ) |
| 101 | + self.invented = invented |
| 102 | + |
| 103 | + |
| 104 | +class Interpretation: |
| 105 | + """A validated model response and what it cost.""" |
| 106 | + |
| 107 | + __slots__ = ("response", "text") |
| 108 | + |
| 109 | + def __init__(self, response: LlmResponse) -> None: |
| 110 | + self.response = response |
| 111 | + self.text = response.text.strip() |
| 112 | + |
| 113 | + @property |
| 114 | + def spend(self) -> Spend: |
| 115 | + return Spend(self.response.usd, self.response.usage.total) |
| 116 | + |
| 117 | + |
| 118 | +def render_material(material: dict[str, Any]) -> str: |
| 119 | + """Render the material an agent is being shown, deterministically.""" |
| 120 | + lines: list[str] = [] |
| 121 | + for section, payload in material.items(): |
| 122 | + lines.append(f"{section.replace('_', ' ').title()}:") |
| 123 | + if isinstance(payload, dict): |
| 124 | + lines += [f" {key}: {value}" for key, value in sorted(payload.items())] |
| 125 | + elif isinstance(payload, list): |
| 126 | + lines += [f" - {item}" for item in payload] |
| 127 | + else: |
| 128 | + lines.append(f" {payload}") |
| 129 | + lines.append("") |
| 130 | + return "\n".join(lines).strip() |
| 131 | + |
| 132 | + |
| 133 | +def interpret( |
| 134 | + context: AgentContext, |
| 135 | + *, |
| 136 | + system: str, |
| 137 | + material: dict[str, Any], |
| 138 | + tier: ModelTier = ModelTier.MID, |
| 139 | + max_tokens: int = 400, |
| 140 | +) -> Interpretation: |
| 141 | + """Ask the model to interpret ``material``, and refuse anything else. |
| 142 | +
|
| 143 | + Raises :class:`UnsourcedFigures` if the response contains a numeral that |
| 144 | + does not appear in ``material``. The turn then fails and the reason is |
| 145 | + recorded against the agent, which is the outcome an Agent Behavior Auditor |
| 146 | + needs to be able to sample for. |
| 147 | + """ |
| 148 | + response = context.provider.complete( |
| 149 | + context.session, |
| 150 | + LlmRequest( |
| 151 | + model=ModelRef( |
| 152 | + provider=context.provider.name, |
| 153 | + model=str(context.task.payload.get("model", "mock-1")), |
| 154 | + tier=tier, |
| 155 | + max_tokens=max_tokens, |
| 156 | + ), |
| 157 | + system=system, |
| 158 | + messages=(Message("user", render_material(material)),), |
| 159 | + actor=context.agent.ref, |
| 160 | + task_ref=context.task.ref, |
| 161 | + ), |
| 162 | + ) |
| 163 | + |
| 164 | + permitted = allowed_figures(material) |
| 165 | + invented = unsourced_numerals(response.text, permitted) |
| 166 | + if invented: |
| 167 | + raise UnsourcedFigures(invented, len(permitted)) |
| 168 | + return Interpretation(response) |
0 commit comments