Coverage for app / agents / answer_artifacts.py: 96%

204 statements  

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

1"""What an answer shows that nothing checked: hand-written fences, unseen images. 

2 

3The first capabilities scenario run delivered: 

4- a pie chart the agent wrote by hand, copying the fence of its earlier 

5 answer instead of calling ``render_chart`` — it happened to be well formed, 

6 but nothing had checked it, and a wrong one draws nothing; 

7- an image in each chart answer, ``![](https://i.imgur.com/…)``, that no tool 

8 had returned and no one had sent: the model made the address up. 

9 

10Both are read off the draft before the quality check reads it: 

11- :func:`remake_written_fences` takes each visual fence the run's tools did 

12 not return, turns its spec back into its render tool's arguments 

13 (``FENCE_ARGS``, one entry a kind) and calls the tool. The tool's own fence 

14 replaces it; one the tool refuses is removed, so the check sees the visual 

15 missing and the agent is sent back to draw it. 

16- :func:`drop_unseen_images` removes a markdown image outside code whose 

17 address no tool result, retrieved evidence, earlier turn or the person's 

18 own words held. Documents keep their own images: ``render_document`` 

19 fetches, checks and stores each one. 

20""" 

21 

22from __future__ import annotations 

23 

24import json 

25import re 

26from collections.abc import Callable, Iterable 

27from dataclasses import dataclass, field 

28from typing import Any 

29from urllib.parse import unquote 

30 

31from app.tools.registry import RENDER_FENCE_LANGUAGES, resolve_tool 

32from app.util import safe_json 

33from app.util.logger import get_logger 

34 

35logger = get_logger(__name__) 

36 

37#: Each visual kind's render tool (``RENDER_FENCE_LANGUAGES`` turned round). 

38TOOL_OF: dict[str, str] = {kind: tool for tool, kind in RENDER_FENCE_LANGUAGES.items()} 

39 

40_FENCE = re.compile( 

41 r"```(" + "|".join(map(re.escape, TOOL_OF)) + r")[ \t]*\n(.*?)\n```", re.DOTALL 

42) 

43_CODE = re.compile(r"```.*?(?:```|$)|`[^`\n]*`", re.DOTALL) 

44_IMAGE = re.compile( 

45 r"!\[[^\]\n]*\]\(\s*<?(https?://[^\s)>]+)>?(?:\s+\"[^\"\n]*\")?\s*\)" 

46) 

47 

48 

49def _object(body: str) -> dict[str, Any]: 

50 # A fence's body is the whole of what a tool wrote, or nothing a tool 

51 # would accept: read whole (``loads_exact``), never a span from inside. 

52 value = safe_json.loads_exact(body) 

53 if not isinstance(value, dict): 

54 raise ValueError("not a JSON object") 

55 return value 

56 

57 

58def _chart(body: str) -> dict[str, Any]: 

59 spec = _object(body) 

60 return { 

61 "chart_type": spec.get("type"), 

62 "data": spec.get("data"), 

63 "x_key": spec.get("x_key"), 

64 "series": spec.get("series"), 

65 "title": spec.get("title"), 

66 } 

67 

68 

69def _plot(body: str) -> dict[str, Any]: 

70 spec = _object(body) 

71 args: dict[str, Any] = { 

72 "plot_type": spec.get("type"), 

73 "title": spec.get("title"), 

74 "x_label": spec.get("xlabel"), 

75 "y_label": spec.get("ylabel"), 

76 } 

77 if spec.get("type") == "histogram": 

78 args |= {"histogram_data": spec.get("data"), "bins": spec.get("bins")} 

79 else: 

80 args |= { 

81 "series": [ 

82 { 

83 "name": s.get("name"), 

84 "data": s.get("data"), 

85 "color": s.get("color"), 

86 "best_fit": s.get("bestFit"), 

87 } 

88 for s in spec.get("series") or [] 

89 if isinstance(s, dict) 

90 ], 

91 "best_fit": spec.get("bestFit"), 

92 } 

93 return args 

94 

95 

96def _graph(body: str) -> dict[str, Any]: 

97 spec = _object(body) 

98 return { 

99 "nodes": spec.get("nodes"), 

100 "edges": spec.get("edges") or [], 

101 "graph_type": spec.get("type") or "2d", 

102 "title": spec.get("title"), 

103 "directed": spec.get("directed"), 

104 "geo": spec.get("geo"), 

105 } 

106 

107 

108def _map(body: str) -> dict[str, Any]: 

109 spec = _object(body) 

110 return { 

111 "geojson": spec.get("geojson", spec), 

112 "title": spec.get("title"), 

113 "center": spec.get("center"), 

114 "zoom": spec.get("zoom"), 

115 } 

116 

117 

118#: A fence's spec as its tool's arguments: each tool writes its arguments 

119#: into its fence under its own keys (``registry``'s ``render_*``). 

120FENCE_ARGS: dict[str, Callable[[str], dict[str, Any]]] = { 

121 "chart": _chart, 

122 "plot": _plot, 

123 "mermaid": lambda body: {"diagram": body}, 

124 "graph": _graph, 

125 "map": _map, 

126} 

127 

128 

129#: The note a replayed visual once stood as ("[chart drawn by render_chart 

130#: — call render_chart again to change it: {…}]", 28 October 2026): models 

131#: copied it into answers, a pie chart as ``![](chart)`` and the note, and a 

132#: map as the bare "[map drawn by render_map]". 

133_NOTE_HEAD = re.compile( 

134 r"\[(" + "|".join(map(re.escape, TOOL_OF)) + r") drawn by render_\w+" 

135 r"(?:\s*[—–-]+\s*call render_\w+ again to change it)?" 

136) 

137 

138 

139def notes_to_fences(text: str) -> str: 

140 """``text`` with each copied visual note turned back into the fence its 

141 spec stands for, and a note with no spec removed: what the note named 

142 is the tool's to draw (``remake_written_fences`` then makes it).""" 

143 out: list[str] = [] 

144 last = 0 

145 decoder = json.JSONDecoder() 

146 for match in _NOTE_HEAD.finditer(text): 

147 if match.start() < last: 

148 continue 

149 kind, at = match.group(1), match.end() 

150 rest = text[at:] 

151 stripped = rest.lstrip(" :") 

152 offset = len(rest) - len(stripped) 

153 replacement, end = "", None 

154 if stripped.startswith("{"): 

155 try: 

156 spec, used = decoder.raw_decode(stripped) 

157 except ValueError: 

158 spec, used = None, 0 

159 tail = stripped[used:].lstrip() 

160 if isinstance(spec, dict) and tail.startswith("]"): 

161 body = safe_json.dumps(spec, ensure_ascii=False) 

162 replacement = f"```{kind}\n{body}\n```" 

163 end = at + offset + used + (len(stripped[used:]) - len(tail)) + 1 

164 if end is None: 

165 close = text.find("]", at) 

166 if close < 0 or "\n\n" in text[at:close]: 

167 continue 

168 end = close + 1 

169 out.append(text[last : match.start()]) 

170 out.append(replacement) 

171 last = end 

172 if not out: 

173 return text 

174 out.append(text[last:]) 

175 return re.sub(r"\n{3,}", "\n\n", "".join(out)).strip() 

176 

177 

178#: A link or image whose target is no web address: what a model writes for 

179#: a file it imagines it made (``sandbox:/mnt/data/brief.pdf``) or a name it 

180#: gives a visual (``![](chart)``). fe-core can open none of them. 

181_NO_ADDRESS = re.compile( 

182 r"(!?)\[([^\]\n]*)\]\(\s*<?(?!https?://|mailto:|tel:|#)([^\s)>]*)>?\s*\)" 

183) 

184 

185 

186def drop_dead_links(text: str) -> tuple[str, int]: 

187 """``text`` without the links and images, outside code, that point at no 

188 web address: an image goes, a link keeps its words. Citation anchors, 

189 mail and phone links are left.""" 

190 dropped = 0 

191 

192 def fix(match: re.Match[str]) -> str: 

193 nonlocal dropped 

194 dropped += 1 

195 return "" if match.group(1) else match.group(2) 

196 

197 out: list[str] = [] 

198 last = 0 

199 for code in _CODE.finditer(text): 

200 out.append(_NO_ADDRESS.sub(fix, text[last : code.start()])) 

201 out.append(code.group(0)) 

202 last = code.end() 

203 out.append(_NO_ADDRESS.sub(fix, text[last:])) 

204 if not dropped: 

205 return text, 0 

206 logger.info("[artifacts] removed %d link(s) with no web address", dropped) 

207 return re.sub(r"\n{3,}", "\n\n", "".join(out)), dropped 

208 

209 

210def _key(fence: str) -> str: 

211 return re.sub(r"\s+", "", fence) 

212 

213 

214#: The most a tool's refusal is quoted back to the model. 

215_SAID_CHARS = 300 

216 

217 

218async def remake_fence(kind: str, body: str) -> tuple[str | None, str]: 

219 """The fence ``kind``'s render tool makes of a fence's ``body``, or None 

220 and what the tool said in refusing it.""" 

221 tool = TOOL_OF[kind] 

222 try: 

223 args = {k: v for k, v in FENCE_ARGS[kind](body).items() if v is not None} 

224 except ValueError: 

225 return None, f"[{tool}] the fence's JSON could not be read" 

226 try: 

227 output = await resolve_tool(tool).ainvoke(args) 

228 except Exception as exc: # noqa: BLE001 — a bad fence is refused, not raised 

229 return None, f"[{tool}] {type(exc).__name__}" 

230 if isinstance(output, str) and output.startswith(f"```{kind}"): 

231 return output, "" 

232 return None, str(output)[:_SAID_CHARS] 

233 

234 

235async def remake_written_fences( 

236 draft: str, artifacts: Iterable[str] 

237) -> tuple[str, list[str]]: 

238 """``draft`` with each visual fence its tools did not return re-made by 

239 its tool (or removed when the tool refuses it), and the fences re-made.""" 

240 made = {_key(fence) for fence in artifacts} 

241 remade: list[str] = [] 

242 

243 async def one(kind: str, whole: str, body: str) -> str: 

244 if _key(whole) in made: 

245 return whole 

246 output, _ = await remake_fence(kind, body) 

247 if output is not None: 

248 remade.append(output) 

249 logger.info("[artifacts] re-made a hand-written %s fence", kind) 

250 return output 

251 logger.info( 

252 "[artifacts] removed a hand-written %s fence its tool refused", kind 

253 ) 

254 return "" 

255 

256 parts: list[str] = [] 

257 last = 0 

258 for match in _FENCE.finditer(draft): 

259 parts.append(draft[last : match.start()]) 

260 parts.append(await one(match.group(1), match.group(0), match.group(2))) 

261 last = match.end() 

262 if not parts: 

263 return draft, [] 

264 parts.append(draft[last:]) 

265 return re.sub(r"\n{3,}", "\n\n", "".join(parts)).strip(), remade 

266 

267 

268def _plain(url: str) -> str: 

269 return unquote(url).rstrip("/").lower() 

270 

271 

272def drop_unseen_images(text: str, seen: Iterable[str]) -> tuple[str, int]: 

273 """``text`` without the markdown images, outside code, whose address 

274 appears nowhere in ``seen`` (the run's tool results, evidence, earlier 

275 turns and the person's words), and how many went.""" 

276 haystack = "\n".join(s for s in seen if s) 

277 known = { 

278 _plain(m.group(0)) for m in re.finditer(r"https?://[^\s\"'<>)\]]+", haystack) 

279 } 

280 dropped = 0 

281 

282 def keep(match: re.Match[str]) -> str: 

283 nonlocal dropped 

284 if _plain(match.group(1)) in known: 

285 return match.group(0) 

286 dropped += 1 

287 return "" 

288 

289 out: list[str] = [] 

290 last = 0 

291 for code in _CODE.finditer(text): 

292 out.append(_IMAGE.sub(keep, text[last : code.start()])) 

293 out.append(code.group(0)) 

294 last = code.end() 

295 out.append(_IMAGE.sub(keep, text[last:])) 

296 if not dropped: 

297 return text, 0 

298 logger.info("[artifacts] removed %d image(s) no tool or message held", dropped) 

299 return re.sub(r"\n{3,}", "\n\n", "".join(out)), dropped 

300 

301 

302# --------------------------------------------------------------------------- 

303# Visuals in a document's body 

304# --------------------------------------------------------------------------- 

305 

306 

307@dataclass(frozen=True) 

308class RefusedVisual: 

309 """A visual fence a document's body held that its tool refused.""" 

310 

311 kind: str 

312 #: Its line in the body, from 1. 

313 line: int 

314 said: str 

315 

316 

317@dataclass 

318class BodyVisuals: 

319 """A document's body with its visuals re-made by their tools.""" 

320 

321 body: str 

322 kept: int = 0 

323 refused: list[RefusedVisual] = field(default_factory=list) 

324 

325 def note(self) -> str | None: 

326 """What the model is told when a visual was not kept.""" 

327 if not self.refused: 

328 return None 

329 total = self.kept + len(self.refused) 

330 lines = "\n".join(f"- {r.kind} (line {r.line}): {r.said}" for r in self.refused) 

331 return ( 

332 f"Visuals: {self.kept} of {total} kept. Not kept — fix each and call " 

333 f"render_document again:\n{lines}" 

334 ) 

335 

336 

337def _container_prefix(prefix: str) -> str: 

338 """The prefix a fence's later lines take inside its container: a quote's 

339 markers kept, a list item's indent as spaces.""" 

340 return "".join(ch if ch == ">" else " " for ch in prefix) 

341 

342 

343async def remake_body_fences(body: str) -> BodyVisuals: 

344 """``body`` with each visual fence re-made by its render tool, wherever 

345 it sits — in a list item or a quote too — so a document holds only 

346 visuals a tool made; one a tool refuses is removed and reported. 

347 

348 Read from markdown-it's tokens, not a pattern: ``_FENCE`` takes a fence 

349 in a quote with its ``>`` markers inside the JSON, and puts a re-made 

350 one in a list item back without its indent, out of the list.""" 

351 from app.documents.markdown import MD 

352 from app.documents.visuals import kind_of 

353 

354 fences = [ 

355 t 

356 for t in MD.parse(body or "") 

357 if t.type == "fence" and t.map and kind_of(t.info) in TOOL_OF 

358 ] 

359 result = BodyVisuals(body) 

360 if not fences: 

361 return result 

362 lines = body.split("\n") 

363 refused: list[RefusedVisual] = [] 

364 for token in reversed(fences): 

365 start, end = token.map 

366 kind = kind_of(token.info) or "" 

367 opening = lines[start] 

368 at = opening.find(token.markup) 

369 prefix = opening[:at] if at >= 0 else "" 

370 fence, said = await remake_fence(kind, token.content.rstrip("\n")) 

371 if fence is None: 

372 refused.append(RefusedVisual(kind, start + 1, said)) 

373 lines[start:end] = [] 

374 continue 

375 first, *rest = fence.split("\n") 

376 lines[start:end] = [ 

377 prefix + first, 

378 *(_container_prefix(prefix) + r for r in rest), 

379 ] 

380 result.kept += 1 

381 result.refused = list(reversed(refused)) 

382 result.body = re.sub(r"\n{3,}", "\n\n", "\n".join(lines)) 

383 if refused: 

384 logger.info("[artifacts] a document's body lost %d visual(s)", len(refused)) 

385 return result 

386 

387 

388def visual_fences_in(documents: Iterable[str]) -> set[str]: 

389 """Each visual fence the documents' bodies hold, as ``_key`` compares 

390 them: a visual the reply's document carries is not the reply's to 

391 restore (``graph._restore_missing_artifacts``).""" 

392 from app.documents import parse_document_fences 

393 

394 keys: set[str] = set() 

395 for fence in documents: 

396 for document in parse_document_fences(fence): 

397 for match in _FENCE.finditer(document.body or ""): 

398 keys.add(_key(match.group(0))) 

399 return keys