Coverage for app / util / schema.py: 97%

115 statements  

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

1"""Auto-generate tool schemas and prompt documentation from Pydantic models. 

2 

3The guiding principle: Pydantic models with ``Field(description=...)`` annotations 

4are the **single source of truth** for all parameter documentation. This module 

5derives three artefacts from those models automatically: 

6 

7 openai_schema_from_model — OpenAI function-calling schema dict (for tool 

8 registration and svc-core display / caching) 

9 tool_description — StructuredTool description string fed to the LLM 

10 so it can decide when and how to call the tool 

11 hint_section — one section of RENDERING_FORMATS_HINT, shown in 

12 every agent system prompt 

13 

14Adding a parameter means updating exactly one Field() annotation; every 

15downstream consumer (LLM schema, tool description, agent hint) updates 

16automatically. 

17""" 

18 

19from __future__ import annotations 

20 

21import inspect 

22import types 

23from enum import Enum 

24from typing import Any, Literal, Union, get_args, get_origin 

25 

26from pydantic import BaseModel 

27 

28 

29# --------------------------------------------------------------------------- 

30# Private helpers — annotation → JSON Schema / human label 

31# --------------------------------------------------------------------------- 

32 

33 

34def _unwrap_optional(annotation: Any) -> Any: 

35 """Strip Optional / X | None wrapper and return the inner type.""" 

36 origin = get_origin(annotation) 

37 is_union = origin is Union or ( 

38 hasattr(types, "UnionType") and isinstance(annotation, types.UnionType) 

39 ) 

40 if not is_union: 

41 return annotation 

42 args = get_args(annotation) 

43 non_none = [a for a in args if a is not type(None)] 

44 if len(non_none) == 1: 

45 return non_none[0] 

46 # Multiple non-None types — reconstruct a union without None 

47 return Union[tuple(non_none)] # type: ignore[return-value] 

48 

49 

50def _type_label(annotation: Any) -> str: 

51 """Compact human-readable type label for documentation (not used in schemas).""" 

52 inner = _unwrap_optional(annotation) 

53 origin = get_origin(inner) 

54 args = get_args(inner) 

55 

56 if origin is Literal: 

57 return " | ".join(f"'{v}'" for v in args) 

58 if inspect.isclass(inner) and issubclass(inner, Enum): 

59 return " | ".join(f"'{m.value}'" for m in inner) 

60 if origin is list: 

61 item = args[0] if args else Any 

62 # Use "object" for nested Pydantic models — internal class names are 

63 # not meaningful to the LLM; the full schema is in the OpenAI schema. 

64 if inspect.isclass(item) and issubclass(item, BaseModel): 

65 return "list[object]" 

66 return f"list[{_type_label(item)}]" 

67 if inspect.isclass(inner) and issubclass(inner, BaseModel): 

68 return "object" 

69 

70 _PRIMITIVES = {str: "string", int: "integer", float: "number", bool: "boolean"} 

71 return _PRIMITIVES.get(inner, getattr(inner, "__name__", str(inner))) 

72 

73 

74def _to_json_schema(annotation: Any) -> dict[str, Any]: 

75 """Recursively convert a Python type annotation to an inline JSON Schema fragment. 

76 

77 All nested BaseModel subclasses are inlined (no $defs/$ref) so the output 

78 is compatible with all OpenAI-style providers without post-processing. 

79 """ 

80 inner = _unwrap_optional(annotation) 

81 origin = get_origin(inner) 

82 args = get_args(inner) 

83 

84 if origin is Literal: 

85 return {"type": "string", "enum": list(args)} 

86 if inspect.isclass(inner) and issubclass(inner, Enum): 

87 return {"type": "string", "enum": [m.value for m in inner]} 

88 if origin is list: 

89 item = args[0] if args else Any 

90 return {"type": "array", "items": _to_json_schema(item)} 

91 if inspect.isclass(inner) and issubclass(inner, BaseModel): 

92 return _model_object_schema(inner) 

93 

94 _PRIMITIVES = {str: "string", int: "integer", float: "number", bool: "boolean"} 

95 if inner in _PRIMITIVES: 

96 return {"type": _PRIMITIVES[inner]} 

97 return {} 

98 

99 

100def _model_object_schema(model: type[BaseModel]) -> dict[str, Any]: 

101 """Produce an inline JSON Schema *object* fragment from a Pydantic model. 

102 

103 Field descriptions, types, and required/optional status all come from the 

104 model's ``Field(description=...)`` annotations — no manual duplication. 

105 """ 

106 props: dict[str, Any] = {} 

107 required: list[str] = [] 

108 

109 for name, fi in model.model_fields.items(): 

110 prop = _to_json_schema(fi.annotation) 

111 if fi.description: 

112 prop["description"] = fi.description 

113 props[name] = prop 

114 if fi.is_required(): 

115 required.append(name) 

116 

117 result: dict[str, Any] = {"type": "object", "properties": props} 

118 if required: 

119 result["required"] = required 

120 return result 

121 

122 

123def _first_line(text: str) -> str: 

124 """Return the first non-empty line of a multi-line string.""" 

125 for line in text.splitlines(): 

126 stripped = line.strip() 

127 if stripped: 

128 return stripped 

129 return "" 

130 

131 

132def _hint_desc(text: str, max_len: int = 160) -> str: 

133 """Return a table-friendly excerpt from a field description. 

134 

135 Joins all non-empty lines, then truncates at ``max_len`` characters at a 

136 word boundary. Multi-line field descriptions (e.g. those with embedded 

137 examples) are collapsed to their first prose sentence so the hint table 

138 stays scannable rather than showing a wall of JSON. 

139 """ 

140 # Collapse newlines and strip example JSON (lines starting with { or [) 

141 prose = " ".join( 

142 line.strip() 

143 for line in text.splitlines() 

144 if line.strip() and not line.strip().startswith(("{", "[", "'", '"')) 

145 ) 

146 if len(prose) <= max_len: 

147 return prose 

148 truncated = prose[:max_len].rsplit(" ", 1)[0] 

149 return truncated + "…" 

150 

151 

152# --------------------------------------------------------------------------- 

153# Public API 

154# --------------------------------------------------------------------------- 

155 

156 

157def openai_schema_from_model( 

158 tool_name: str, 

159 description: str, 

160 model: type[BaseModel], 

161) -> dict[str, Any]: 

162 """Generate an OpenAI function-calling schema dict from a Pydantic input model. 

163 

164 Replaces hand-written ``_*_SCHEMA`` dicts throughout the tool registry. 

165 Field-level documentation is derived from ``Field(description=...)`` 

166 annotations, so adding or changing a parameter only requires touching the 

167 Pydantic model. 

168 

169 Args: 

170 tool_name: Tool identifier, e.g. ``"web_search"``. 

171 description: Brief one-line description shown to the LLM and svc-core. 

172 model: Pydantic model whose fields define the parameters. 

173 

174 Example:: 

175 

176 _WEB_SEARCH_SCHEMA = openai_schema_from_model( 

177 "web_search", "Search the web for current information", WebSearchInput 

178 ) 

179 """ 

180 return { 

181 "type": "function", 

182 "function": { 

183 "name": tool_name, 

184 "description": description, 

185 "parameters": _model_object_schema(model), 

186 }, 

187 } 

188 

189 

190def tool_description(model: type[BaseModel], summary: str) -> str: 

191 """Generate a ``StructuredTool(description=...)`` string from a Pydantic model. 

192 

193 Combines ``summary`` with per-field entries derived from each field's 

194 ``Field(description=...)``. Required fields are marked with ``*``. 

195 If the model has a class docstring it is prepended as semantic context 

196 (e.g. "when to use / when NOT to use this tool"). 

197 

198 Args: 

199 model: Pydantic input model with ``Field(description=...)`` annotations. 

200 summary: One-line action statement, e.g. "Return a ```chart code fence.". 

201 

202 Example:: 

203 

204 description = tool_description( 

205 RenderChartInput, 

206 "Render a categorical chart. Include the returned fence verbatim." 

207 ) 

208 """ 

209 req_lines: list[str] = [] 

210 opt_lines: list[str] = [] 

211 

212 for name, fi in model.model_fields.items(): 

213 label = _type_label(fi.annotation) 

214 # Use only the first non-empty line so long descriptions stay readable 

215 desc = _first_line(fi.description or "") 

216 entry = ( 

217 f" {name}* ({label}): {desc}" 

218 if fi.is_required() 

219 else f" {name} ({label}): {desc}" 

220 ) 

221 (req_lines if fi.is_required() else opt_lines).append(entry) 

222 

223 parts: list[str] = [] 

224 if model.__doc__: 

225 doc = inspect.cleandoc(model.__doc__) 

226 if doc: 

227 parts.append(doc) 

228 parts.append("") 

229 parts.append(summary) 

230 if req_lines: 

231 parts += ["", "Required:"] + req_lines 

232 if opt_lines: 

233 parts += ["", "Optional:"] + opt_lines 

234 

235 return "\n".join(parts) 

236 

237 

238def hint_section( 

239 tool_name: str, 

240 model: type[BaseModel], 

241 *, 

242 example: str = "", 

243) -> str: 

244 """Generate one ``RENDERING_FORMATS_HINT`` section for a render tool. 

245 

246 Produces a parameter table whose rows are derived entirely from the model's 

247 ``Field(description=...)`` annotations, plus an optional code-fence example. 

248 The fence language is inferred from the tool name (``render_X`` → ``X``). 

249 

250 Args: 

251 tool_name: Tool name, e.g. ``"render_chart"``. 

252 model: Pydantic input model. 

253 example: Raw JSON string to display as a code-fence example. 

254 """ 

255 fence_lang = tool_name.replace("render_", "") 

256 lines: list[str] = [f"#### `{tool_name}`"] 

257 

258 if model.__doc__: 

259 doc = inspect.cleandoc(model.__doc__) 

260 first = _first_line(doc) 

261 if first: 

262 lines.append(f"*{first}*") 

263 

264 lines += [ 

265 "", 

266 "| Parameter | Type | Req | Description |", 

267 "|-----------|------|:---:|-------------|", 

268 ] 

269 

270 for name, fi in model.model_fields.items(): 

271 label = _type_label(fi.annotation) 

272 req = "✱" if fi.is_required() else "" 

273 desc = _hint_desc(fi.description or "").replace("|", "\\|") 

274 lines.append(f"| `{name}` | `{label}` | {req} | {desc} |") 

275 

276 if example: 

277 lines += ["", f"```{fence_lang}", example, "```"] 

278 

279 return "\n".join(lines)