Coverage for app / services / scenarios / artifacts.py: 95%

160 statements  

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

1"""What a turn's answer delivered: its rendered artifacts and its documents. 

2 

3An artifact is a fenced block a render tool returns into the answer 

4(```chart, ```plot, ```mermaid, ```graph, ```map) — svc-ai's 

5``registry.RENDER_FENCE_LANGUAGES`` — or a ```document (``DOCUMENT_FENCE_LANGUAGE``), 

6which the chat draws as a card with a PDF download. They live only in the 

7stored answer's text, so this reads them from there, the way fe-core does. 

8 

9Nothing in the pipeline checks a visual fence a model wrote itself, so each 

10is checked here: one class per kind, against the shape its tool writes 

11(``svc-ai app/tools/registry.py``), and whether the turn called that tool. 

12A document is rendered to PDF as its download is (``ai_client. 

13render_document_pdf``) and its images counted: the PDF's bytes say nothing 

14of them, but the fence lists every image it stored beside the links its text 

15makes. 

16 

17Approximations, said where they are: mermaid's syntax is not checked 

18server-side (only that it opens with a type ``render_mermaid`` offers, which 

19itself refuses what it cannot read), and a PDF's pages are read from 

20reportlab's uncompressed page tree. 

21""" 

22 

23from __future__ import annotations 

24 

25import json 

26import re 

27from urllib.parse import unquote 

28from abc import ABC, abstractmethod 

29from typing import Any, ClassVar, Literal 

30 

31#: Every artifact kind, in svc-ai's order: the visual fences, then the 

32#: document (pinned to ``svc-ai app/tools/registry.py`` by the tests). 

33ArtifactKind = Literal["chart", "plot", "mermaid", "graph", "map", "document"] 

34ARTIFACT_KINDS: tuple[str, ...] = ( 

35 "chart", 

36 "plot", 

37 "mermaid", 

38 "graph", 

39 "map", 

40 "document", 

41) 

42 

43#: The kinds a document's body may draw: every artifact but the document. 

44VisualKind = Literal["chart", "plot", "mermaid", "graph", "map"] 

45VISUAL_KINDS: tuple[str, ...] = ARTIFACT_KINDS[:-1] 

46 

47#: Which tool makes each kind (svc-ai ``RENDER_FENCE_LANGUAGES``, inverted). 

48TOOL_OF: dict[str, str] = {kind: f"render_{kind}" for kind in ARTIFACT_KINDS} 

49 

50_FENCE = re.compile( 

51 r"```(" + "|".join(ARTIFACT_KINDS) + r")[ \t]*\n(.*?)\n```", re.DOTALL 

52) 

53#: A markdown image in a document's text, as the fence's ``images`` match it. 

54_IMAGE_LINK = re.compile(r"!\[[^\]]*\]\((https://[^)\s]+)\)") 

55 

56 

57class Kind(ABC): 

58 """One artifact kind: what a well-formed fence of it holds.""" 

59 

60 key: ClassVar[str] 

61 

62 @abstractmethod 

63 def problems(self, body: str) -> list[str]: ... 

64 

65 

66KINDS: dict[str, Kind] = {} 

67 

68 

69def _kind(cls: type[Kind]) -> type[Kind]: 

70 KINDS[cls.key] = cls() 

71 return cls 

72 

73 

74def _json_object(body: str) -> tuple[dict[str, Any] | None, list[str]]: 

75 try: 

76 value = json.loads(body) 

77 except ValueError: 

78 return None, ["not JSON"] 

79 if not isinstance(value, dict): 

80 return None, ["not a JSON object"] 

81 return value, [] 

82 

83 

84@_kind 

85class Chart(Kind): 

86 key = "chart" 

87 #: svc-ai ``registry.ChartType``. 

88 TYPES = ("bar", "grouped", "line", "area", "pie") 

89 

90 def problems(self, body): 

91 spec, problems = _json_object(body) 

92 if spec is None: 

93 return problems 

94 if spec.get("type") not in self.TYPES: 

95 problems.append(f"type {spec.get('type')!r} is no chart type") 

96 data = spec.get("data") 

97 if not isinstance(data, list) or not data: 

98 problems.append("no data") 

99 elif not all(isinstance(row, dict) for row in data): 

100 problems.append("data is not a list of records") 

101 return problems 

102 

103 

104@_kind 

105class Plot(Kind): 

106 key = "plot" 

107 #: svc-ai ``registry.PlotType``. 

108 TYPES = ("scatter", "line", "histogram") 

109 

110 def problems(self, body): 

111 spec, problems = _json_object(body) 

112 if spec is None: 

113 return problems 

114 if spec.get("type") not in self.TYPES: 

115 problems.append(f"type {spec.get('type')!r} is no plot type") 

116 series = spec.get("series") 

117 data = spec.get("data") 

118 points = [ 

119 point 

120 for item in (series if isinstance(series, list) else []) 

121 if isinstance(item, dict) 

122 for point in item.get("data") or [] 

123 ] 

124 if not points and not (isinstance(data, list) and data): 

125 problems.append("no data") 

126 return problems 

127 

128 

129@_kind 

130class Mermaid(Kind): 

131 key = "mermaid" 

132 #: The first words a diagram may open with: the types ``render_mermaid`` 

133 #: offers and a PDF draws (svc-ai ``documents/visuals/mermaid/ 

134 #: vocabulary.py`` ``MermaidKeyword``, pinned by the tests). Its syntax 

135 #: is not checked here: the tool refuses what it cannot read. 

136 TYPES = ( 

137 "flowchart", 

138 "flowchart-elk", 

139 "graph", 

140 "sequenceDiagram", 

141 "stateDiagram", 

142 "stateDiagram-v2", 

143 "classDiagram", 

144 "classDiagram-v2", 

145 "erDiagram", 

146 "pie", 

147 "gantt", 

148 ) 

149 

150 def problems(self, body): 

151 lines = [ 

152 line.strip() 

153 for line in body.splitlines() 

154 if line.strip() and not line.strip().startswith("%%") 

155 ] 

156 if not lines: 

157 return ["empty"] 

158 first = lines[0].split()[0] 

159 if first not in self.TYPES: 

160 return [f"opens with {first!r}, no mermaid diagram type"] 

161 return [] 

162 

163 

164@_kind 

165class Graph(Kind): 

166 key = "graph" 

167 

168 def problems(self, body): 

169 spec, problems = _json_object(body) 

170 if spec is None: 

171 return problems 

172 nodes = spec.get("nodes") 

173 if not isinstance(nodes, list) or not nodes: 

174 return [*problems, "no nodes"] 

175 ids = [n.get("id") for n in nodes if isinstance(n, dict)] 

176 if len(ids) != len(nodes) or any(i in (None, "") for i in ids): 

177 problems.append("a node without an id") 

178 if len(set(map(str, ids))) != len(ids): 

179 problems.append("node ids repeat") 

180 known = set(map(str, ids)) 

181 for edge in spec.get("edges") or []: 

182 if ( 

183 not isinstance(edge, dict) 

184 or not { 

185 str(edge.get("source")), 

186 str(edge.get("target")), 

187 } 

188 <= known 

189 ): 

190 problems.append("an edge names a node that is not there") 

191 break 

192 return problems 

193 

194 

195@_kind 

196class Map(Kind): 

197 key = "map" 

198 #: GeoJSON's types (svc-ai ``render_map`` accepts these). 

199 TYPES = ( 

200 "FeatureCollection", 

201 "Feature", 

202 "Point", 

203 "MultiPoint", 

204 "LineString", 

205 "MultiLineString", 

206 "Polygon", 

207 "MultiPolygon", 

208 "GeometryCollection", 

209 ) 

210 

211 def problems(self, body): 

212 spec, problems = _json_object(body) 

213 if spec is None: 

214 return problems 

215 # The tool writes {geojson, …}; fe-core also draws bare GeoJSON. 

216 geojson = spec.get("geojson", spec) 

217 if not isinstance(geojson, dict) or geojson.get("type") not in self.TYPES: 

218 problems.append("no GeoJSON of a known type") 

219 elif geojson.get("type") == "FeatureCollection" and not geojson.get("features"): 

220 problems.append("a FeatureCollection with no features") 

221 return problems 

222 

223 

224@_kind 

225class Document(Kind): 

226 key = "document" 

227 

228 def problems(self, body): 

229 spec, problems = _json_object(body) 

230 if spec is None: 

231 return problems 

232 if not str(spec.get("title") or "").strip(): 

233 problems.append("no title") 

234 return problems 

235 

236 

237def fences(text: str | None) -> list[tuple[str, str]]: 

238 """Every artifact fence in ``text``: ``(kind, body)``, in order.""" 

239 return [(m.group(1), m.group(2)) for m in _FENCE.finditer(text or "")] 

240 

241 

242def made_by_tool(tools: list[dict[str, Any]]) -> set[str]: 

243 """The kinds a render tool made in the turn. A render tool reports a 

244 refused input as its result (``[render_chart] 'data' must be…``), which 

245 the frame reads as a success, so a kind counts only when its tool's 

246 result opens with its fence.""" 

247 return { 

248 kind 

249 for call in tools 

250 for kind, tool in TOOL_OF.items() 

251 if call.get("tool") == tool 

252 and call.get("status") == "success" 

253 and str(call.get("output_preview") or "").startswith(f"```{kind}") 

254 } 

255 

256 

257def inventory(text: str | None, tools: list[dict[str, Any]]) -> list[dict[str, Any]]: 

258 """The answer's artifacts, each checked: its kind, whether it is 

259 well-formed (and why not), and whether its tool made it.""" 

260 from_tool = made_by_tool(tools) 

261 out = [] 

262 for kind, body in fences(text): 

263 problems = KINDS[kind].problems(body) 

264 out.append( 

265 { 

266 "kind": kind, 

267 "valid": not problems, 

268 "problems": problems, 

269 "from_tool": kind in from_tool, 

270 "chars": len(body), 

271 **( 

272 {"note": "mermaid syntax is not checked server-side"} 

273 if kind == "mermaid" 

274 else {} 

275 ), 

276 } 

277 ) 

278 return out 

279 

280 

281def images_of(document: dict[str, Any]) -> dict[str, Any]: 

282 """What a document's text links and what it embedded: the fence's 

283 ``images`` are the copies stored when it was made, keyed by the link as 

284 svc-ai's markdown parser normalised it, so both sides are compared 

285 percent-decoded.""" 

286 body = str(document.get("body") or "") 

287 linked = list(dict.fromkeys(_IMAGE_LINK.findall(body))) 

288 stored = { 

289 unquote(str(image.get("src"))) 

290 for image in document.get("images") or [] 

291 if isinstance(image, dict) and image.get("asset") 

292 } 

293 missing = [src for src in linked if unquote(src) not in stored] 

294 return { 

295 "linked": len(linked), 

296 "embedded": len(linked) - len(missing), 

297 "missing": missing[:20], 

298 } 

299 

300 

301def visuals_of( 

302 document: dict[str, Any], drawn: list[dict[str, Any]] | None 

303) -> list[dict[str, Any]]: 

304 """The visuals a document's body holds, a row a kind in the body's 

305 order: how many, how many well-formed (and why not), and how many its 

306 PDF drew. ``drawn`` is what svc-ai said it drew 

307 (``ai_client.render_document``); None when the PDF did not render, and 

308 then so is each row's ``drawn``.""" 

309 rows: dict[str, dict[str, Any]] = {} 

310 for kind, body in fences(str(document.get("body") or "")): 

311 if kind not in VISUAL_KINDS: 

312 continue 

313 row = rows.setdefault( 

314 kind, 

315 { 

316 "kind": kind, 

317 "count": 0, 

318 "valid": 0, 

319 "drawn": None if drawn is None else 0, 

320 "problems": [], 

321 }, 

322 ) 

323 row["count"] += 1 

324 problems = KINDS[kind].problems(body) 

325 if problems: 

326 row["problems"] = (row["problems"] + problems)[:5] 

327 else: 

328 row["valid"] += 1 

329 for visual in drawn or []: 

330 row = rows.get(str(visual.get("kind"))) 

331 if row is not None and visual.get("drawn"): 

332 row["drawn"] += 1 

333 return list(rows.values()) 

334 

335 

336_OBJECT_END = re.compile(rb"\bendobj\b") 

337_PAGE_TREE = re.compile(rb"/Type\s*/Pages\b") 

338_COUNT = re.compile(rb"/Count\s+(\d+)") 

339_PAGE = re.compile(rb"/Type\s*/Page\b(?!s)") 

340 

341 

342def pdf_pages(data: bytes) -> int | None: 

343 """A PDF's pages, read from its page tree (reportlab writes it 

344 uncompressed): the root node's ``/Count``, else its page objects. None 

345 when the bytes are no PDF this can read.""" 

346 if not data.startswith(b"%PDF"): 

347 return None 

348 counts = [ 

349 int(match.group(1)) 

350 for chunk in _OBJECT_END.split(data) 

351 if _PAGE_TREE.search(chunk) 

352 for match in [_COUNT.search(chunk)] 

353 if match 

354 ] 

355 if counts: 

356 return max(counts) 

357 return len(_PAGE.findall(data)) or None