Coverage for app / services / reply_formats / cleaning.py: 98%

129 statements  

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

1"""Separating a model's answer from the reasoning it wrote as text. 

2 

3Pure — ``re`` and ``unicodedata`` only, no settings, no logging — so a 

4migration can import it (svc-ai migration 30 cleans stored memory episodes 

5with it) and every reply format (``reply_formats``) shares one copy. 

6 

7Three ways reasoning arrives inside text, in the order they are tried: 

8 

9* **Harmony markers.** gpt-oss is trained on OpenAI's harmony format, whose 

10 channels are delimited by special tokens: ``<|channel|>analysis<|message|> 

11 … <|end|><|start|>assistant<|channel|>final<|message|> …``. A server that 

12 passes them through, or strips only the brackets (``analysis…assistantfinal 

13 …``), leaves the channel names in the text. 

14* **The answer envelope.** A model whose reasoning may arrive as text is 

15 told to write its reply between :data:`ENVELOPE_OPEN` and 

16 :data:`ENVELOPE_CLOSE` (``reply_formats.GptOss.contract``). The answer is 

17 the text after the **last** opener, up to its closer or the end of the 

18 text — the last, because reasoning written as text can name the tag before 

19 the reply uses it; and up to the end, because a reply cut off at the token 

20 cap may not have closed it. The stream filter applies the same rule, so 

21 what streams and what is stored cannot differ. 

22* **Tagged blocks** — ``<think>``, ``<thinking>``, ``<reasoning>`` — anywhere, 

23 including a closer with no opener (a model whose chat template opens the 

24 block in the prompt writes only ``…</think>``). 

25 

26When none of them is present, :func:`seam` is the last resort for gpt-oss: 

27its analysis channel arrives as text run straight into the answer with no 

28break — "…Now produce final answer.Here’s a quick roundup…". It looks for 

29that seam, and removes only what it can tell apart: a stop straight after a 

30whole lower-case word, then a capital (curly apostrophes included) or a 

31markdown opener, early in the text, after at least three words of plain 

32prose. It never guesses where analysis ends. 

33""" 

34 

35from __future__ import annotations 

36 

37import re 

38import unicodedata 

39from dataclasses import dataclass 

40 

41#: The answer envelope. Distinctive, so an answer never contains it by 

42#: accident; matched case-insensitively and with spaces inside the brackets. 

43ENVELOPE_TAG = "reply_to_user" 

44ENVELOPE_OPEN = f"<{ENVELOPE_TAG}>" 

45ENVELOPE_CLOSE = f"</{ENVELOPE_TAG}>" 

46_OPEN = re.compile(rf"<\s*{ENVELOPE_TAG}\s*>", re.IGNORECASE) 

47_CLOSE = re.compile(rf"<\s*/\s*{ENVELOPE_TAG}\s*>", re.IGNORECASE) 

48 

49#: The tags open-weight models put their reasoning between. 

50REASONING_TAGS = ("think", "thinking", "reasoning") 

51_TAG_NAMES = "|".join(REASONING_TAGS) 

52_TAG_PAIR = re.compile( 

53 rf"<\s*({_TAG_NAMES})\s*>.*?<\s*/\s*\1\s*>\s*", re.DOTALL | re.IGNORECASE 

54) 

55_TAG_OPEN = re.compile(rf"<\s*({_TAG_NAMES})\s*>", re.IGNORECASE) 

56_TAG_CLOSE = re.compile(rf"<\s*/\s*({_TAG_NAMES})\s*>\s*", re.IGNORECASE) 

57 

58#: DeepSeek's own tool-call markup (``<|DSML|function_calls>`` and the 

59#: invocations inside it, with a full-width bar), which Converse leaves at 

60#: the end of a tool turn's text after parsing the call into a tool-use 

61#: block (reply probe, 31 October 2026). 

62DSML_MARKER = "<|DSML|" 

63_DSML = re.compile(r"<\s*|\s*DSML\s*|", re.IGNORECASE) 

64 

65#: Harmony, with its special tokens: the final channel's message. 

66_HARMONY_FINAL = re.compile( 

67 r"<\|channel\|>\s*final\s*(?:<\|constrain\|>[^<]*)?<\|message\|>", re.IGNORECASE 

68) 

69#: Harmony with the token brackets stripped: ``analysis…assistantfinal…``. 

70_HARMONY_BARE = re.compile(r"^\s*analysis.*?assistantfinal", re.DOTALL) 

71#: Any special token left over. 

72_HARMONY_TOKEN = re.compile(r"<\|[a-z_]+\|>", re.IGNORECASE) 

73#: Tokens that end a harmony message. 

74_HARMONY_END = re.compile(r"(?:<\|(?:end|return|call)\|>)+\s*$", re.IGNORECASE) 

75 

76#: How far into the text the seam may be: the analysis that ends a turn is a 

77#: few sentences. Past this the text is the answer's own. 

78SEAM_WITHIN = 1500 

79#: What may follow the capitalised word that starts the answer. 

80_AFTER_WORD = " \t\n,.!?:;" + "—–-" 

81#: Markdown that may start an answer straight after the stop. 

82_MARKDOWN_OPENERS = re.compile(r"(?:#{1,6} |\*\*|[-*] |\| |> |\d+[.)] )") 

83#: What analysis never holds and an answer may: markdown structure at the 

84#: start of a line, or code. A head with any of it is kept. 

85_ANSWER_STRUCTURE = re.compile( 

86 r"^[ \t]*(?:#{1,6} |[-*+] |\d+[.)] |\||>)|`", re.MULTILINE 

87) 

88 

89 

90@dataclass(frozen=True) 

91class Cleaned: 

92 """What :func:`answer` found: the answer and how it was told apart.""" 

93 

94 text: str 

95 #: ``text`` (nothing removed), ``harmony``, ``envelope``, ``tags`` or ``seam``. 

96 path: str 

97 removed: int 

98 

99 

100def harmony_final(text: str) -> str | None: 

101 """The final channel's message when ``text`` carries harmony markers, or 

102 None when it carries none.""" 

103 found = list(_HARMONY_FINAL.finditer(text)) 

104 if found: 

105 body = text[found[-1].end() :] 

106 return _HARMONY_TOKEN.sub("", _HARMONY_END.sub("", body)).strip() 

107 bare = _HARMONY_BARE.match(text) 

108 if bare: 

109 return _HARMONY_TOKEN.sub("", text[bare.end() :]).strip() 

110 if _HARMONY_TOKEN.search(text): 

111 return _HARMONY_TOKEN.sub("", text).strip() 

112 return None 

113 

114 

115def envelope(text: str) -> str | None: 

116 """The text after the last envelope opener, up to its closer or the end; 

117 None when there is no opener.""" 

118 last = None 

119 for last in _OPEN.finditer(text): 

120 pass 

121 if last is None: 

122 return None 

123 rest = text[last.end() :] 

124 close = _CLOSE.search(rest) 

125 return (rest[: close.start()] if close else rest).strip() 

126 

127 

128def complete_envelope(text: str) -> str | None: 

129 """The last *closed* envelope's content, or None.""" 

130 found = None 

131 for opener in _OPEN.finditer(text): 

132 close = _CLOSE.search(text, opener.end()) 

133 if close: 

134 found = text[opener.end() : close.start()].strip() 

135 return found 

136 

137 

138def unwrap(text: str) -> str: 

139 """``text`` without any envelope tags — for text that must never show one.""" 

140 return _CLOSE.sub("", _OPEN.sub("", text)) 

141 

142 

143def strip_tags(text: str, *, leading_only: bool = False) -> str: 

144 """``text`` without its tagged reasoning blocks. 

145 

146 ``leading_only`` removes only a complete block the text starts with — for 

147 models that never write one mid-answer, where a later one is content (an 

148 answer about such tags). Otherwise every complete block goes, and a 

149 closer with no opener before it takes everything up to it.""" 

150 if leading_only: 

151 match = _TAG_PAIR.match(text.lstrip()) 

152 return text.lstrip()[match.end() :] if match else text 

153 cleaned = _TAG_PAIR.sub("", text) 

154 close = _TAG_CLOSE.search(cleaned) 

155 if close and not _TAG_OPEN.search(cleaned, 0, close.start()): 

156 cleaned = cleaned[close.end() :] 

157 return cleaned 

158 

159 

160def strip_dsml(text: str) -> str: 

161 """``text`` up to DeepSeek's tool-call markup: what follows the marker is 

162 a call Bedrock has already parsed, never answer.""" 

163 match = _DSML.search(text) 

164 return text[: match.start()].rstrip() if match else text 

165 

166 

167def tag_spellings() -> tuple[str, ...]: 

168 """Every reasoning tag as written, opener and closer.""" 

169 return tuple(t for name in REASONING_TAGS for t in (f"<{name}>", f"</{name}>")) 

170 

171 

172def strip_tags_so_far(text: str) -> str: 

173 """:func:`strip_tags` for a reply still arriving: a block that has opened 

174 and not yet closed hides everything after its opener.""" 

175 cleaned = strip_tags(text) 

176 opener = _TAG_OPEN.search(cleaned) 

177 return cleaned[: opener.start()] if opener else cleaned 

178 

179 

180def _word_start(text: str, end: int) -> int: 

181 """Where the run of letters ending at ``end`` (exclusive) starts.""" 

182 start = end 

183 while start > 0 and text[start - 1].isalpha(): 

184 start -= 1 

185 return start 

186 

187 

188def _opens_answer(text: str, at: int) -> bool: 

189 """Whether an answer starts at ``at``: a markdown opener, or a 

190 capitalised word followed by a space or any punctuation — Unicode's, so 

191 "Here’s" (U+2019) reads as "Here's" does. #396's version took only an 

192 ASCII apostrophe, and gpt-oss writes the curly one.""" 

193 if _MARKDOWN_OPENERS.match(text, at): 

194 return True 

195 if at >= len(text) or not text[at].isupper(): 

196 return False 

197 i = at + 1 

198 while i < len(text) and text[i].isalpha(): 

199 i += 1 

200 if i >= len(text): 

201 return False 

202 return text[i] in _AFTER_WORD or unicodedata.category(text[i]).startswith("P") 

203 

204 

205def seam(text: str, within: int = SEAM_WITHIN) -> int | None: 

206 """Where the answer starts after leading analysis run into it, or None. 

207 

208 A candidate is a ``.``, ``!`` or ``?`` straight after a whole lower-case 

209 word of two letters or more (not part of a dotted name such as 

210 ``os.path`` or an abbreviation such as ``U.S.``), followed with no space 

211 by the start of an answer (:func:`_opens_answer`). The head before it 

212 must be at least three words of plain prose — no markdown structure, no 

213 code — and there must be an answer after it. The first candidate wins. 

214 """ 

215 limit = min(len(text) - 1, within) 

216 for i in range(1, limit): 

217 if text[i] not in ".!?": 

218 continue 

219 start = _word_start(text, i) 

220 word = text[start:i] 

221 if len(word) < 2 or not word.islower(): 

222 continue 

223 if start > 0 and (text[start - 1].isalnum() or text[start - 1] in "._"): 

224 continue 

225 if not _opens_answer(text, i + 1): 

226 continue 

227 head, tail = text[: i + 1], text[i + 1 :] 

228 if len(head.split()) < 3 or _ANSWER_STRUCTURE.search(head): 

229 return None 

230 return i + 1 if tail.strip() else None 

231 return None 

232 

233 

234def answer(text: str, *, use_envelope: bool, use_seam: bool) -> Cleaned: 

235 """The answer in ``text``, trying harmony, the envelope, tags and the seam 

236 in that order (see the module notes).""" 

237 original = text 

238 final = harmony_final(text) 

239 path = "text" 

240 if final is not None: 

241 text, path = final, "harmony" 

242 if use_envelope: 

243 inside = envelope(text) 

244 if inside is not None: 

245 return Cleaned(inside, "envelope", len(original) - len(inside)) 

246 tagless = strip_tags(text) 

247 if tagless != text: 

248 text, path = tagless, "tags" if path == "text" else path 

249 if use_seam: 

250 at = seam(text) 

251 if at is not None: 

252 text, path = text[at:], "seam" 

253 text = unwrap(text).strip() if use_envelope else text.strip() 

254 return Cleaned(text, path, max(0, len(original.strip()) - len(text)))