Coverage for app / inference / engine.py: 90%

93 statements  

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

1""" 

2InferenceEngine — abstract base class for all svc-ai execution types. 

3 

4Template method pattern: 

5 

6 infer(ctx) → _pre_infer → _do_infer → _post_infer 

7 infer_stream(ctx) → _pre_infer → _do_infer_stream 

8 

9Cross-cutting concerns applied at the base: 

10 • Rules enforcement — policy rules filter/block the input; audit rules 

11 filter/flag the output. 

12 • Cost monitoring — token usage tracked per invocation via UsageAccumulator. 

13 • Inference tracing — OTEL root span + structured LLMSpan logging. 

14 

15Subclasses implement _do_infer (and optionally _do_infer_stream); they never 

16call the rules/monitor/tracer directly. 

17""" 

18 

19from __future__ import annotations 

20 

21import logging 

22from abc import ABC, abstractmethod 

23from typing import Any, AsyncIterator, ClassVar 

24 

25from app.models.spec import ExecuteResponse 

26from app.util import attachments as attachment_util 

27from app.util import safe_json 

28from app.inference.context import InferenceContext 

29from app.inference.rules import ( 

30 RulesEnforcer, 

31 RuleBlock, 

32 audit_done_frame, 

33 block_payload, 

34 output_figures, 

35 stream_guard, 

36) 

37from app.inference.monitor import UsageAccumulator 

38from app.inference.tracer import InferenceTracer 

39 

40logger = logging.getLogger(__name__) 

41 

42 

43def _sse(data: dict[str, Any]) -> str: 

44 """One SSE frame. Never raises: a value the encoder refuses is converted 

45 rather than ending the stream (``app.util.safe_json``).""" 

46 return f"data: {safe_json.dumps(data)}\n\n" 

47 

48 

49class InferenceEngine(ABC): 

50 """ 

51 Abstract base for every svc-ai inference engine. 

52 

53 Constructor parameters are injected by ``InferenceEngineFactory`` so 

54 subclasses only need to implement ``_do_infer`` (and optionally 

55 ``_do_infer_stream``). 

56 """ 

57 

58 def __init__( 

59 self, 

60 rules: RulesEnforcer, 

61 monitor: UsageAccumulator, 

62 tracer: InferenceTracer, 

63 ) -> None: 

64 self.rules = rules 

65 self.monitor = monitor 

66 self.tracer = tracer 

67 

68 # ── Public entry points ─────────────────────────────────────────────────── 

69 

70 async def infer(self, ctx: InferenceContext) -> ExecuteResponse: 

71 """ 

72 Full batch inference lifecycle with cross-cutting concerns applied. 

73 

74 Raises: 

75 RuleBlock — propagated from policy rule enforcement. 

76 ValueError — if the engine does not support this execution type. 

77 Exception — any error from the underlying LLM/graph call. 

78 """ 

79 with self.tracer.root_span( 

80 ctx.request.type, 

81 user_id=ctx.request.user_id, 

82 session_id=ctx.request.session_id, 

83 ) as span: 

84 self.tracer.set_input(span, ctx.request.input) 

85 

86 await self._pre_infer(ctx) 

87 

88 try: 

89 response = await self._do_infer(ctx) 

90 except Exception as exc: 

91 self.tracer.set_error(span, exc) 

92 raise 

93 

94 response = await self._post_infer(ctx, response) 

95 self.tracer.set_output(span, response.output) 

96 self.tracer.set_usage(span, response.usage) 

97 # Hand the enforcement trail back to svc-core — it owns 

98 # persistence and display, and without this the record of what 

99 # was enforced here dies at the service boundary. 

100 if ctx.rule_events: 

101 response = response.model_copy( 

102 update={"rule_events": list(ctx.rule_events)} 

103 ) 

104 return response 

105 

106 async def infer_stream(self, ctx: InferenceContext) -> AsyncIterator[str]: 

107 """ 

108 Streaming inference lifecycle. Yields SSE data lines. 

109 

110 Policy rules are applied before the stream starts. A RuleBlock emits 

111 an error SSE frame and terminates the stream rather than raising, so 

112 the FastAPI streaming response can still be sent to the client. 

113 

114 Audit rules are applied to the final output carried by the terminal 

115 ``done`` frame (individual token frames stream through unmodified; 

116 the ``done`` output is the authoritative response that callers 

117 persist and display). 

118 """ 

119 try: 

120 await self._pre_infer(ctx) 

121 except RuleBlock as exc: 

122 yield _sse({"type": "error", **block_payload(exc)}) 

123 return 

124 

125 rule_ctx = self._rule_context(ctx) 

126 # A redact_pii rule redacts what streams, not only the final answer. 

127 guard = stream_guard(self.rules, rule_ctx) 

128 async for raw in self._do_infer_stream(ctx): 

129 for frame in guard.process(raw) if guard else (raw,): 

130 # Policy events fired before the stream opened; the done frame 

131 # is the only place left to carry them to svc-core. 

132 frame, audit_events = audit_done_frame( 

133 self.rules, 

134 frame, 

135 rule_ctx, 

136 prior_events=ctx.rule_events, 

137 started=ctx.started_at, 

138 ) 

139 ctx.rule_events.extend(audit_events) 

140 yield frame 

141 if guard: 

142 for frame in guard.flush(): 

143 yield frame 

144 

145 # ── Lifecycle hooks ─────────────────────────────────────────────────────── 

146 

147 #: Whether this engine reads a turn's documents apart from the person's 

148 #: words (the graph engines: ``GraphBasedEngine``). The others are given 

149 #: them pasted before the words, as svc-core used to send them. 

150 takes_attachments: ClassVar[bool] = False 

151 

152 async def _pre_infer(self, ctx: InferenceContext) -> None: 

153 """Apply policy rules to the input. Mutates ctx.filtered_input.""" 

154 rule_ctx = self._rule_context(ctx) 

155 filtered, events = self.rules.apply_input(ctx.filtered_input, rule_ctx) 

156 ctx.filtered_input = filtered 

157 ctx.rule_events.extend(events) 

158 # What the rules read; conditions go on reading it after the 

159 # documents are taken apart from the words. 

160 ctx.governed_input = filtered 

161 self._take_attachments(ctx, rule_ctx) 

162 

163 def _take_attachments( 

164 self, ctx: InferenceContext, rule_ctx: dict[str, Any] 

165 ) -> None: 

166 """Take the turn's documents apart from the person's words 

167 (``attachments.gather``), or paste them before the words for an 

168 engine that reads one prompt.""" 

169 sent = list(ctx.request.attachments or []) 

170 redactor = self.rules.input_redactor(rule_ctx) if sent else None 

171 words, history, docs = attachment_util.gather( 

172 ctx.filtered_input, ctx.request.messages or [], sent, redactor=redactor 

173 ) 

174 if history != list(ctx.request.messages or []): 

175 ctx.request = ctx.request.model_copy(update={"messages": history}) 

176 if self.takes_attachments: 

177 ctx.filtered_input = words 

178 ctx.attachments = docs 

179 elif docs: 

180 # One prompt, no tools: the documents go before the words, within 

181 # what the model's window can spare for them. 

182 block = attachment_util.render_for_model(docs, self._attachment_window(ctx)) 

183 ctx.filtered_input = f"{block}\n\n{words}" if words else block 

184 

185 def _attachment_window(self, ctx: InferenceContext) -> int | None: 

186 """The context window of the model a non-graph engine calls, for the 

187 documents' budget; None when it cannot be told.""" 

188 return None 

189 

190 async def _post_infer( 

191 self, 

192 ctx: InferenceContext, 

193 response: ExecuteResponse, 

194 ) -> ExecuteResponse: 

195 """Apply audit rules to the output and record usage.""" 

196 rule_ctx = { 

197 **self._rule_context(ctx), 

198 **output_figures({"usage": response.usage}, ctx.started_at), 

199 } 

200 filtered_output, audit_events = self.rules.apply_output( 

201 response.output, rule_ctx 

202 ) 

203 ctx.rule_events.extend(audit_events) 

204 

205 if audit_events: 

206 response = response.model_copy(update={"output": filtered_output}) 

207 

208 return response 

209 

210 # ── Abstract ────────────────────────────────────────────────────────────── 

211 

212 @abstractmethod 

213 async def _do_infer(self, ctx: InferenceContext) -> ExecuteResponse: 

214 """Subclasses implement the actual inference logic for batch execution.""" 

215 

216 async def _do_infer_stream(self, ctx: InferenceContext) -> AsyncIterator[str]: 

217 """Subclasses override to support streaming; default falls back to batch.""" 

218 response = await self._do_infer(ctx) 

219 if response.citations: 

220 yield _sse({"type": "citations", "citations": response.citations}) 

221 yield _sse({"type": "done", "output": response.output, "usage": response.usage}) 

222 

223 # ── Helpers ─────────────────────────────────────────────────────────────── 

224 

225 def _rule_context(self, ctx: InferenceContext) -> dict[str, Any]: 

226 """Build the evaluation context dict for rule condition matching.""" 

227 req = ctx.request 

228 return { 

229 "prompt": ctx.governed_input or ctx.filtered_input, 

230 "user_id": str(req.user_id or ""), 

231 "execution_type": req.type, 

232 "conversation_id": str(req.conversation_id or ""), 

233 "external_agent_id": str(req.external_agent_id or ""), 

234 } 

235 

236 

237class DbEngineMixin: 

238 """ 

239 Constructor for every engine that also needs direct DB access. 

240 

241 ``AgentEngine``, ``GraphEngine``, ``SkillEngine`` (via 

242 ``GraphBasedEngine``) and ``PipelineEngine`` all took an identical 

243 ``(db, rules, monitor, tracer)`` constructor that did nothing but thread 

244 ``db`` through to ``self.db`` — this is that constructor, shared once. 

245 """ 

246 

247 def __init__( 

248 self, 

249 db: Any, 

250 rules: RulesEnforcer, 

251 monitor: UsageAccumulator, 

252 tracer: InferenceTracer, 

253 ) -> None: 

254 super().__init__(rules, monitor, tracer) 

255 self.db = db