Coverage for app / inference / context.py: 100%

16 statements  

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

1""" 

2InferenceContext — per-request state shared across the full engine lifecycle. 

3""" 

4 

5from __future__ import annotations 

6 

7import time 

8from dataclasses import dataclass, field 

9from typing import TYPE_CHECKING, Any 

10 

11if TYPE_CHECKING: 

12 from app.models.spec import ExecuteRequest 

13 from app.util.attachments import Attachment 

14 

15 

16@dataclass 

17class InferenceContext: 

18 """ 

19 Mutable state threaded through pre_infer → _do_infer → post_infer. 

20 

21 ``filtered_input`` is populated by the rules engine during pre_infer and 

22 should be used by engines as the actual LLM input (it may differ from 

23 ``request.input`` when a policy rule applied PII filtering). 

24 """ 

25 

26 request: "ExecuteRequest" 

27 db: Any | None 

28 

29 # Populated at engine start 

30 started_at: float = field(default_factory=time.monotonic) 

31 

32 # Set by RulesEnforcer.apply_input() — use this as the actual LLM prompt 

33 filtered_input: str = "" 

34 

35 # Audit trail of which rule actions fired during this request 

36 rule_events: list[dict[str, Any]] = field(default_factory=list) 

37 

38 # The documents attached to the conversation, apart from the person's 

39 # words (``attachments.gather``, for engines that take them apart). The 

40 # input as the Input rules read it — documents still pasted in — stays 

41 # in ``governed_input``, which rule conditions go on reading. 

42 attachments: list["Attachment"] = field(default_factory=list) 

43 governed_input: str = "" 

44 

45 def __post_init__(self) -> None: 

46 # Initialise filtered_input to the raw request input; rules may mutate it 

47 if not self.filtered_input: 

48 self.filtered_input = self.request.input