Coverage for app / skills / generation.py: 91%
201 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""
2Generative skill creation — the schema a model fills in, and its conversion
3to a storable ``graph_definition``.
5The skillset and agent setups propose skills as plain chains of agent nodes
6(``agent_setup.ProposedGraphDefinition``). A single generated skill needs the
7techniques the templates teach — typed outputs, conditional branches, tool
8and transform nodes, an approval gate, a declared interface — so it has its
9own schema here, still bounded: a fixed node vocabulary, a closed operator
10list, at most :data:`MAX_NODES` nodes.
12Nothing here trusts the model. :func:`check` reports structural problems (the
13router refuses the proposal, and svc-core asks once more with them as
14feedback), and svc-core validates the converted graph again with the same
15``_GraphDefinitionSchema`` that guards a hand-built skill.
17``as_document`` is applied deterministically by :func:`attach_document`, not
18left to the model: the final node is given the report fields and a
19``render_document`` tool node is appended after it.
20"""
22from __future__ import annotations
24import re
25from typing import Any, Literal
27from pydantic import BaseModel, Field
29from app.services.structured_output import ModelOutput
30from app.documents.spec import REPORT_OUTPUT_SCHEMA
31from app.util import vocab
33MAX_NODES = 8
34#: Guidance, not enforced: a Run form past this many fields stops being a
35#: shortcut, and a skill tagged more than this is tagged for nobody.
36MAX_INPUTS = 4
37MAX_TAGS = 4
39_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
40_PATH = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)*$")
42BINARY_OPS = (
43 "eq", "ne", "gt", "gte", "lt", "lte", "in", "not_in",
44 "contains", "not_contains", "starts_with", "ends_with", "matches",
45) # fmt: skip
46UNARY_OPS = ("exists", "not_exists", "empty", "not_empty", "truthy", "falsy")
48#: Built from the two tuples above, so a branch operator exists in exactly one
49#: place.
50ConditionOp = Literal[BINARY_OPS + UNARY_OPS] # type: ignore[valid-type]
52#: What a node can be, and what a model is told each one is for.
53NodeKind = Literal["agent", "tool", "transform"]
55#: The two transforms, as the ``transform`` field and the skill prompt
56#: describe them.
57Transform = Literal["select", "template"]
58TRANSFORMS: dict[str, str] = {
59 "select": "copies one variable (keeps its type)",
60 "template": "renders text from {placeholders}",
61}
62vocab.check(TRANSFORMS, Transform)
65# ---------------------------------------------------------------------------
66# What the model fills in
67# ---------------------------------------------------------------------------
70class GenField(BaseModel):
71 """A typed field — a skill input, or one field of a node's structured output."""
73 name: str = Field(description="snake_case identifier")
74 type: Literal["string", "number", "integer", "boolean", "enum", "array"] = "string"
75 description: str = ""
76 required: bool = False
77 values: list[str] = Field(
78 default_factory=list, description="enum only: the allowed values"
79 )
80 items: Literal["string", "number", "integer", "boolean"] | None = Field(
81 default=None, description="array only: the element type"
82 )
85class GenOutput(BaseModel):
86 """A declared skill output, projected from a variable when the run ends."""
88 name: str = Field(description="snake_case output name")
89 source: str = Field(
90 description="Variable path it comes from, e.g. 'write.summary' or 'final_response'"
91 )
94class GenToolArg(BaseModel):
95 name: str
96 value: str = Field(
97 description="A literal, or exactly one {placeholder} to pass a variable "
98 "with its type, e.g. '{write.title}'"
99 )
102class GenNode(BaseModel):
103 id: str = Field(description="Short snake_case id, unique in the graph")
104 kind: NodeKind = "agent"
105 description: str = Field(default="", description="What this node does, one line")
106 # agent
107 agent_name: str = Field(
108 default="", description="agent: a worker from the provided list"
109 )
110 system_prompt: str = Field(
111 default="", description="agent: the node's role and rules (optional)"
112 )
113 prompt_template: str = Field(
114 default="",
115 description="agent: the node's task, with {placeholders} for variables",
116 )
117 output_schema: list[GenField] = Field(
118 default_factory=list,
119 description="agent: fields of a structured result; empty = free text",
120 )
121 approval_message: str = Field(
122 default="",
123 description="agent: if set, the run pauses for a person to approve "
124 "before this node runs, showing this message",
125 )
126 ask_user: bool = Field(
127 default=False, description="agent: may ask the person clarifying questions"
128 )
129 # tool
130 tool_name: str = Field(default="", description="tool: a tool from the list")
131 tool_args: list[GenToolArg] = Field(default_factory=list)
132 # transform
133 transform: Transform | None = Field(
134 default=None,
135 description="transform: "
136 + vocab.guide(
137 TRANSFORMS,
138 Transform,
139 indent="",
140 sep=" ",
141 quote="'",
142 align=False,
143 joiner="; ",
144 ), # fmt: skip
145 )
146 transform_source: str = Field(
147 default="",
148 description="transform: the variable path (select) or the text (template)",
149 )
150 output_key: str = Field(
151 default="", description="State key this node's result is written to"
152 )
155class GenBranch(BaseModel):
156 key: str = Field(description="Short label for the branch")
157 target: str = Field(description="Node id to run, or 'end'")
158 var: str = Field(description="Variable path tested, e.g. 'review.verdict'")
159 op: ConditionOp
160 value: str | float | bool | None = Field(
161 default=None, description="Compared value (binary operators only)"
162 )
165class GenRoute(BaseModel):
166 """Conditional routing out of one node — first matching branch wins."""
168 source: str
169 branches: list[GenBranch] = Field(min_length=1)
170 default_target: str = Field(description="Node id when no branch holds, or 'end'")
173class GeneratedSkill(ModelOutput):
174 name: str
175 description: str = ""
176 tags: list[str] = Field(default_factory=list)
177 explanation: str = Field(
178 default="",
179 description="Why the graph is shaped this way",
180 # A field named for the model's reasoning can be refused by Claude 5.x.
181 serialization_alias="reasoning",
182 )
183 inputs: list[GenField] = Field(
184 default_factory=list, description="The skill's declared inputs (its Run form)"
185 )
186 outputs: list[GenOutput] = Field(
187 default_factory=list, description="The skill's declared outputs"
188 )
189 nodes: list[GenNode] = Field(min_length=1, max_length=MAX_NODES)
190 edges: list[list[str]] = Field(
191 default_factory=list, description="[from_id, to_id] pairs; no cycles"
192 )
193 routes: list[GenRoute] = Field(default_factory=list)
194 start_node: str
195 end_nodes: list[str] = Field(min_length=1)
198# ---------------------------------------------------------------------------
199# Checks
200# ---------------------------------------------------------------------------
203def check(
204 skill: GeneratedSkill, agent_names: set[str], tool_names: set[str]
205) -> list[str]:
206 """Structural problems; empty means convertible. Never repairs."""
207 problems: list[str] = []
208 ids = [n.id for n in skill.nodes]
209 id_set = set(ids)
210 if len(ids) != len(id_set):
211 problems.append("node ids are not unique")
212 for n in skill.nodes:
213 if not _IDENT.match(n.id):
214 problems.append(f"node id {n.id!r} is not an identifier")
215 if n.output_key and not _IDENT.match(n.output_key):
216 problems.append(f"node {n.id!r} output_key is not an identifier")
217 if n.kind == "agent":
218 if n.agent_name not in agent_names:
219 problems.append(f"node {n.id!r} runs unknown worker {n.agent_name!r}")
220 _check_fields(n.output_schema, f"node {n.id!r} output_schema", problems)
221 elif n.kind == "tool":
222 if n.tool_name not in tool_names:
223 problems.append(f"node {n.id!r} calls unknown tool {n.tool_name!r}")
224 elif n.kind == "transform":
225 if n.transform is None or not n.transform_source:
226 problems.append(f"transform node {n.id!r} needs transform and source")
227 elif n.transform == "select" and not _PATH.match(n.transform_source):
228 problems.append(f"transform node {n.id!r} select source is not a path")
229 if n.kind != "agent" and (n.approval_message or n.ask_user):
230 problems.append(f"only agent nodes can pause for a person ({n.id!r})")
232 _check_fields(skill.inputs, "inputs", problems)
233 for out in skill.outputs:
234 if not _IDENT.match(out.name) or not _PATH.match(out.source):
235 problems.append(f"output {out.name!r} is malformed")
237 if skill.start_node not in id_set:
238 problems.append(f"start_node {skill.start_node!r} is not a node")
239 for end in skill.end_nodes:
240 if end not in id_set:
241 problems.append(f"end node {end!r} is not a node")
243 adjacency: dict[str, set[str]] = {i: set() for i in id_set}
245 def target_ok(target: str, where: str) -> bool:
246 if target == "end" or target in id_set:
247 return True
248 problems.append(f"{where} targets {target!r}, which is not a node")
249 return False
251 for edge in skill.edges:
252 if len(edge) != 2 or edge[0] not in id_set:
253 problems.append(f"malformed edge {edge}")
254 continue
255 if target_ok(edge[1], f"edge from {edge[0]!r}") and edge[1] != "end":
256 adjacency[edge[0]].add(edge[1])
257 sources = set()
258 for route in skill.routes:
259 if route.source not in id_set:
260 problems.append(f"route source {route.source!r} is not a node")
261 continue
262 if route.source in sources:
263 problems.append(f"node {route.source!r} has more than one route")
264 sources.add(route.source)
265 for target in [route.default_target, *(b.target for b in route.branches)]:
266 if target_ok(target, f"route from {route.source!r}") and target != "end":
267 adjacency[route.source].add(target)
268 for b in route.branches:
269 if not _PATH.match(b.var):
270 problems.append(
271 f"route from {route.source!r} tests malformed {b.var!r}"
272 )
273 if b.op in BINARY_OPS and b.value is None:
274 problems.append(f"route from {route.source!r}: {b.op} needs a value")
275 if any(e[0] == route.source for e in skill.edges if len(e) == 2):
276 problems.append(f"node {route.source!r} has both edges and a route")
278 if not problems and _has_cycle(adjacency):
279 problems.append("the graph has a cycle; skills must be acyclic")
280 return problems
283def _check_fields(fields: list[GenField], where: str, problems: list[str]) -> None:
284 seen: set[str] = set()
285 for f in fields:
286 if not _IDENT.match(f.name):
287 problems.append(f"{where}: {f.name!r} is not an identifier")
288 if f.name in seen:
289 problems.append(f"{where}: {f.name!r} declared twice")
290 seen.add(f.name)
291 if f.type == "enum" and not f.values:
292 problems.append(f"{where}: enum {f.name!r} has no values")
295def _has_cycle(adjacency: dict[str, set[str]]) -> bool:
296 state: dict[str, int] = {}
298 def visit(node: str) -> bool:
299 state[node] = 1
300 for nxt in adjacency.get(node, ()):
301 if state.get(nxt) == 1 or (state.get(nxt) is None and visit(nxt)):
302 return True
303 state[node] = 2
304 return False
306 return any(state.get(n) is None and visit(n) for n in adjacency)
309# ---------------------------------------------------------------------------
310# Conversion
311# ---------------------------------------------------------------------------
314def _field_spec(f: GenField) -> dict[str, Any]:
315 spec: dict[str, Any] = {"name": f.name, "type": f.type, "required": f.required}
316 if f.description:
317 spec["description"] = f.description
318 if f.type == "enum":
319 spec["values"] = list(f.values)
320 if f.type == "array" and f.items:
321 spec["items"] = f.items
322 return spec
325def _node(n: GenNode) -> dict[str, Any]:
326 node: dict[str, Any] = {"description": n.description}
327 if n.kind == "agent":
328 node.update(
329 type="agent",
330 agent_name=n.agent_name,
331 prompt_template=n.prompt_template,
332 config_overrides=(
333 {"system_prompt": n.system_prompt} if n.system_prompt else {}
334 ),
335 )
336 if n.output_schema:
337 node["output_schema"] = [_field_spec(f) for f in n.output_schema]
338 if n.approval_message:
339 node["approval"] = {"message": n.approval_message[:1000]}
340 if n.ask_user:
341 node["ask_user"] = True
342 elif n.kind == "tool":
343 node.update(
344 type="tool",
345 agent_name="",
346 tool={"name": n.tool_name, "args": {a.name: a.value for a in n.tool_args}},
347 )
348 else:
349 operation = (
350 {"op": "select", "key": n.transform_source}
351 if n.transform == "select"
352 else {"op": "template", "template": n.transform_source}
353 )
354 node.update(type="transform", agent_name="", operation=operation)
355 if n.output_key:
356 node["output_key"] = n.output_key
357 return node
360def to_graph_definition(skill: GeneratedSkill) -> dict[str, Any]:
361 """The storable graph — call only after :func:`check` found nothing."""
362 definition: dict[str, Any] = {
363 "nodes": {n.id: _node(n) for n in skill.nodes},
364 "edges": [list(e) for e in skill.edges if e[1] != "end"],
365 "start_node": skill.start_node,
366 "end_nodes": list(dict.fromkeys(skill.end_nodes)),
367 "interface": {
368 "inputs": [_field_spec(f) for f in skill.inputs],
369 "outputs": [{"name": o.name, "from": o.source} for o in skill.outputs],
370 },
371 }
372 if skill.routes:
373 definition["conditional_edges"] = {
374 r.source: {
375 "branches": [
376 {
377 "key": b.key,
378 "target": b.target,
379 "when": {"var": b.var, "op": b.op}
380 | ({"value": b.value} if b.op in BINARY_OPS else {}),
381 }
382 for b in r.branches
383 ],
384 "default": r.default_target,
385 }
386 for r in skill.routes
387 }
388 return definition
391def attach_document(definition: dict[str, Any]) -> str | None:
392 """End the graph in a downloadable document, in place.
394 The single end node — which must be an agent node — is given the report
395 fields as its structured output, and a ``render_document`` tool node is
396 appended after it, binding each field. The skill's outputs become the
397 report. Returns a warning instead when the graph has no single agent end
398 node to write the report.
399 """
400 ends = definition["end_nodes"]
401 writer = definition["nodes"].get(ends[0]) if len(ends) == 1 else None
402 if writer is None or writer.get("type") != "agent":
403 return (
404 "Could not add a document step: the skill does not end in a single "
405 "agent node to write the report."
406 )
407 writer["output_schema"] = [dict(f) for f in REPORT_OUTPUT_SCHEMA]
408 names = [f["name"] for f in REPORT_OUTPUT_SCHEMA]
409 source = ends[0]
410 publish = "publish" if "publish" not in definition["nodes"] else "publish_document"
411 definition["nodes"][publish] = {
412 "type": "tool",
413 "agent_name": "",
414 "description": "Attach the report as a downloadable document.",
415 "tool": {
416 "name": "render_document",
417 "args": {name: f"{{{source}.{name}}}" for name in names},
418 },
419 "output_key": "document",
420 }
421 definition["edges"].append([source, publish])
422 definition["end_nodes"] = [publish]
423 definition["interface"]["outputs"] = [
424 {"name": name, "from": f"{source}.{name}"} for name in names
425 ]
426 return None