Coverage for app / diagnostics / reply_probe.py: 41%

104 statements  

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

1"""How a model's replies arrive on this deployment's route: run by hand. 

2 

3gpt-oss-120b on Bedrock Converse returned its analysis channel as answer 

4text, and what svc-ai does about it (``reply_formats.GptOss``: an envelope, 

5then a cleaner) was built without a trace of the raw wire. This probe 

6records it: a small matrix of real calls, each summarised as one JSON line — 

7the content block types and their sizes, the first characters of each text 

8block, the stop reason, and which markers the reply carried. No credentials 

9and no full text are printed. It spends real money, a few cents in all, and 

10is run only with approval:: 

11 

12 docker compose exec svc-ai python -m app.diagnostics.reply_probe \\ 

13 --provider openai --model gpt-oss-120b 

14 

15Cases: streamed and not × without tools and with one scripted 

16``web_search`` (the tool round, then the answer round) × no 

17``reasoning_effort`` and each level × without and with the envelope 

18contract; plus LiteLLM's ``bedrock/converse`` route, which model chat takes. 

19Paste the lines back: whether Bedrock returns ``reasoning_content`` blocks 

20once ``reasoning_effort`` is set decides whether the envelope stays on 

21(``docs/guides/agent-graph.md#what-a-tool-loop-delivers``). 

22""" 

23 

24from __future__ import annotations 

25 

26import argparse 

27import asyncio 

28import json 

29import time 

30from typing import Any 

31 

32from app.services.reply_formats import cleaning 

33 

34#: What each case asks: current events, so the model wants its tool. 

35PROMPT = "whats in the news" 

36#: What the scripted search returns: a block shaped like web_search's. 

37SEARCH_RESULT = ( 

38 'Web search: "news today" (type=news, past day) — 1 result(s).\n\n' 

39 "Title: French cities to impose partial curfews\n" 

40 "URL: https://www.bbc.co.uk/news/live/c893v4gx2e47t\n" 

41 "Published: 2026-10-19\n" 

42 "Snippet: The Prime Minister gave mayors authority to introduce curfews." 

43) 

44EFFORTS: tuple[str | None, ...] = (None, "low", "medium", "high") 

45PREFIX = 80 

46 

47 

48def summarise(message: Any, *, case: dict[str, Any], seconds: float) -> dict[str, Any]: 

49 """One reply as a JSON-able line: its shape, never its whole text.""" 

50 content = getattr(message, "content", message) 

51 blocks: list[dict[str, Any]] = [] 

52 texts: list[str] = [] 

53 if isinstance(content, str): 

54 blocks.append( 

55 {"type": "str", "chars": len(content), "starts": content[:PREFIX]} 

56 ) 

57 texts.append(content) 

58 else: 

59 for block in content or []: 

60 if not isinstance(block, dict): 

61 blocks.append({"type": type(block).__name__}) 

62 continue 

63 kind = str(block.get("type")) 

64 entry: dict[str, Any] = {"type": kind} 

65 if isinstance(block.get("text"), str): 

66 entry["chars"] = len(block["text"]) 

67 entry["starts"] = block["text"][:PREFIX] 

68 texts.append(block["text"]) 

69 reasoning = block.get("reasoning_content") or block.get("thinking") 

70 if isinstance(reasoning, dict): 

71 entry["reasoning_chars"] = len(str(reasoning.get("text") or "")) 

72 elif isinstance(reasoning, str): 

73 entry["reasoning_chars"] = len(reasoning) 

74 if block.get("phase"): 

75 entry["phase"] = block["phase"] 

76 blocks.append(entry) 

77 text = "".join(texts) 

78 meta = getattr(message, "response_metadata", None) or {} 

79 usage = getattr(message, "usage_metadata", None) or {} 

80 return { 

81 **case, 

82 "seconds": round(seconds, 2), 

83 "blocks": blocks, 

84 "tool_calls": [ 

85 c.get("name") for c in getattr(message, "tool_calls", None) or [] 

86 ], 

87 "stop": meta.get("stopReason") 

88 or meta.get("stop_reason") 

89 or meta.get("finish_reason"), 

90 "output_tokens": usage.get("output_tokens"), 

91 "found": { 

92 "harmony": cleaning.harmony_final(text) is not None, 

93 "envelope": cleaning.envelope(text) is not None, 

94 "tags": cleaning.strip_tags(text) != text, 

95 "seam": cleaning.seam(text) is not None, 

96 }, 

97 } 

98 

99 

100def cases() -> list[dict[str, Any]]: 

101 """The matrix, as the probe runs it.""" 

102 return [ 

103 {"stream": stream, "tools": tools, "effort": effort, "envelope": envelope} 

104 for stream in (False, True) 

105 for tools in (False, True) 

106 for effort in EFFORTS 

107 for envelope in (False, True) 

108 ] 

109 

110 

111async def _call(llm: Any, messages: list[Any], *, stream: bool) -> Any: 

112 if not stream: 

113 return await llm.ainvoke(messages) 

114 merged = None 

115 async for chunk in llm.astream(messages): 

116 merged = chunk if merged is None else merged + chunk 

117 return merged 

118 

119 

120async def _run_case(base: Any, case: dict[str, Any]) -> list[dict[str, Any]]: 

121 from langchain_core.messages import HumanMessage, SystemMessage, ToolMessage 

122 from langchain_core.tools import StructuredTool 

123 

124 from app import prompts 

125 

126 llm = base 

127 if case["effort"]: 

128 llm = llm.model_copy(update={"reasoning_effort": case["effort"]}) 

129 system = "You are a helpful assistant. Cite what you use." 

130 if case["envelope"]: 

131 system += "\n\n" + prompts.REPLY_ENVELOPE_CONTRACT 

132 messages: list[Any] = [SystemMessage(content=system), HumanMessage(content=PROMPT)] 

133 lines = [] 

134 if case["tools"]: 

135 

136 def web_search(query: str) -> str: 

137 """Search the live web.""" 

138 return SEARCH_RESULT 

139 

140 llm = llm.bind_tools([StructuredTool.from_function(web_search)]) 

141 started = time.monotonic() 

142 first = await _call(llm, messages, stream=case["stream"]) 

143 lines.append( 

144 summarise( 

145 first, 

146 case={**case, "round": "tool"}, 

147 seconds=time.monotonic() - started, 

148 ) 

149 ) 

150 calls = getattr(first, "tool_calls", None) or [] 

151 if not calls: 

152 return lines 

153 messages += [ 

154 first, 

155 ToolMessage(content=SEARCH_RESULT, tool_call_id=calls[0]["id"]), 

156 ] 

157 started = time.monotonic() 

158 reply = await _call(llm, messages, stream=case["stream"]) 

159 lines.append( 

160 summarise( 

161 reply, case={**case, "round": "answer"}, seconds=time.monotonic() - started 

162 ) 

163 ) 

164 return lines 

165 

166 

167async def _litellm(provider: str, model: str) -> dict[str, Any]: 

168 import litellm 

169 

170 from app.services import inference_routes, llm as llm_service 

171 

172 target = llm_service._litellm_target(inference_routes.resolve(provider, model)) 

173 started = time.monotonic() 

174 response = await litellm.acompletion( 

175 messages=[{"role": "user", "content": PROMPT}], max_tokens=2000, **target 

176 ) 

177 message = response.choices[0].message 

178 text = message.content or "" 

179 return { 

180 "route": "litellm", 

181 "seconds": round(time.monotonic() - started, 2), 

182 "content_chars": len(text), 

183 "starts": text[:PREFIX], 

184 "reasoning_content_chars": len( 

185 getattr(message, "reasoning_content", None) or "" 

186 ), 

187 "found": { 

188 "harmony": cleaning.harmony_final(text) is not None, 

189 "seam": cleaning.seam(text) is not None, 

190 }, 

191 } 

192 

193 

194async def main(provider: str, model: str, *, litellm_only: bool = False) -> None: 

195 from app.models.spec import ModelConfig 

196 from app.services.llm import build_langchain_llm 

197 

198 if not litellm_only: 

199 base = build_langchain_llm( 

200 ModelConfig(provider=provider, model=model, max_tokens=2000) 

201 ) 

202 for case in cases(): 

203 try: 

204 for line in await _run_case(base, case): 

205 print(json.dumps(line, ensure_ascii=False)) 

206 except Exception as exc: # noqa: BLE001 — one failed case, the rest still run 

207 print(json.dumps({**case, "error": type(exc).__name__})) 

208 print(json.dumps(await _litellm(provider, model), ensure_ascii=False)) 

209 

210 

211if __name__ == "__main__": 

212 parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) 

213 parser.add_argument("--provider", default="openai") 

214 parser.add_argument("--model", default="gpt-oss-120b") 

215 parser.add_argument("--litellm-only", action="store_true") 

216 args = parser.parse_args() 

217 asyncio.run(main(args.provider, args.model, litellm_only=args.litellm_only))