Coverage for app / routers / skill_setup.py: 99%
86 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"""Generative skill creation — design one skill graph from a description.
3POST /skills/generate-config returns a proposal for review; it creates
4nothing. svc-core owns the rest: it records the invocation, validates the
5graph with the schema that guards a hand-built skill, asks once more with the
6problems when that fails, and persists only what the user accepts.
8The optional ``template`` names one of svc-ai's patterns
9(``app/skills/registry.py``), looked up here rather than trusted from the
10caller, so the model adapts the real graph.
11"""
13from __future__ import annotations
15import json
16from typing import Any
18from fastapi import APIRouter, Depends, HTTPException
19from langchain_core.messages import HumanMessage, SystemMessage
20from pydantic import BaseModel, Field
21from sqlalchemy.orm import Session
23from app import prompts
24from app.db.postgres.enums import InvocationEnum
25from app.dependency.base import get_db
26from app.models.spec import ModelConfig
27from app.routers.agent_setup import CatalogAgentDefinition
28from app.services.conversation import persist_llm_invocation
29from app.services.llm import build_langchain_llm
30from app.services.structured_generation import (
31 generate,
32)
33from app.skills import generation
34from app.skills.registry import BUILTIN_SKILL_TEMPLATES
35from app.tools.registry import BUILTIN_TOOLS, ToolCategory
36from app.util.logger import get_logger
38logger = get_logger(__name__)
40router = APIRouter(prefix="/skills", tags=["skill-setup"])
42GENERATION_BUDGET_S = 100.0
44#: Tools a generated tool node may call: every tool agents get by default,
45#: except ``ask_user`` — a node asks through ``ask_user`` on an agent node.
46_EXCLUDED_TOOLS = frozenset({"ask_user"})
49def node_tools() -> dict[str, Any]:
50 return {
51 name: defn
52 for name, defn in BUILTIN_TOOLS.items()
53 if defn.category == ToolCategory.GENERAL and name not in _EXCLUDED_TOOLS
54 }
57class SkillGenerationRequest(BaseModel):
58 description: str = Field(min_length=1, max_length=4000)
59 provider: str
60 model: str
61 model_id: str | None = None
62 #: A template (pattern) name to start from.
63 template: str | None = None
64 #: End the skill in a downloadable document (added deterministically).
65 as_document: bool = False
66 agent_definitions: list[CatalogAgentDefinition] = []
67 #: A repair round: the previous proposal and what was wrong with it.
68 previous: dict[str, Any] | None = None
69 feedback: list[str] = []
70 user_id: str = "system"
73class SkillGenerationResponse(BaseModel):
74 #: The model's proposal as it answered, for a repair round.
75 proposal: dict[str, Any]
76 #: The storable graph — only when ``problems`` is empty.
77 graph_definition: dict[str, Any] | None = None
78 name: str
79 description: str = ""
80 tags: list[str] = []
81 reasoning: str = ""
82 problems: list[str] = []
83 warnings: list[str] = []
86def _tool_catalogue() -> list[dict[str, Any]]:
87 out = []
88 for name, defn in node_tools().items():
89 params = (defn.schema.get("function") or {}).get("parameters") or {}
90 out.append(
91 {
92 "name": name,
93 "description": defn.description[:200],
94 "args": sorted((params.get("properties") or {}).keys()),
95 }
96 )
97 return out
100def _user_content(req: SkillGenerationRequest) -> str:
101 parts = [f"Description:\n{req.description}"]
102 if req.template:
103 template = BUILTIN_SKILL_TEMPLATES[req.template]
104 parts.append(
105 f"Start from this pattern — {template.display_name}: "
106 f"{template.description}\n"
107 + json.dumps(template.to_graph_definition(), indent=1)
108 )
109 if req.as_document:
110 parts.append(
111 "The skill must end in exactly ONE agent node that writes the "
112 "final report (a document step is appended after it "
113 "automatically; its output fields are set for you)."
114 )
115 parts.append(
116 "Workers:\n"
117 + "\n".join(f" - {d.model_dump_json()}" for d in req.agent_definitions)
118 )
119 parts.append(
120 "Tools for tool nodes:\n"
121 + "\n".join(f" - {json.dumps(t)}" for t in _tool_catalogue())
122 )
123 if req.previous is not None and req.feedback:
124 parts.append(
125 "Your previous attempt:\n"
126 + json.dumps(req.previous, indent=1)[:20_000]
127 + "\nIt had these problems — fix every one:\n"
128 + "\n".join(f" - {p}" for p in req.feedback)
129 )
130 return "\n\n".join(parts)
133@router.post("/generate-config", response_model=SkillGenerationResponse)
134async def generate_skill_config(
135 req: SkillGenerationRequest, db: Session = Depends(get_db)
136) -> SkillGenerationResponse:
137 """Design one skill in a single structured call."""
138 if req.template and req.template not in BUILTIN_SKILL_TEMPLATES:
139 raise HTTPException(
140 status_code=422, detail=f"Unknown pattern {req.template!r}."
141 )
142 agent_names = [d.name for d in req.agent_definitions]
143 tools = node_tools()
144 llm = build_langchain_llm(
145 ModelConfig(
146 provider=req.provider, model=req.model, temperature=0.2, max_tokens=8192
147 )
148 )
149 messages = [
150 SystemMessage(
151 content=prompts.build_skill_generator_prompt(agent_names, sorted(tools))
152 ),
153 HumanMessage(content=_user_content(req)),
154 ]
155 outcome = await generate(
156 llm,
157 generation.GeneratedSkill,
158 messages,
159 purpose="skill-setup",
160 budget_s=GENERATION_BUDGET_S,
161 )
162 skill: generation.GeneratedSkill | None = outcome.config
164 persist_llm_invocation(
165 db,
166 purpose="skill_generation",
167 provider=req.provider,
168 model=req.model,
169 user_id=req.user_id,
170 latency_ms=outcome.latency_ms,
171 status=InvocationEnum.Status.success
172 if skill is not None
173 else InvocationEnum.Status.error,
174 error_detail=outcome.failure if skill is None else None,
175 request_config={
176 "provider": req.provider,
177 "model": req.model,
178 "temperature": 0.2,
179 "max_tokens": 8192,
180 "flow": "skill_setup.generate_config",
181 "template": req.template,
182 "repair": bool(req.feedback),
183 },
184 output_preview=skill.model_dump_json(indent=2) if skill else None,
185 )
187 if skill is None:
188 raise HTTPException(
189 status_code=422,
190 detail=f"Skill generation failed: {outcome.user_message}",
191 )
193 problems = generation.check(skill, set(agent_names), set(tools))
194 warnings: list[str] = []
195 graph_definition = None
196 if not problems:
197 graph_definition = generation.to_graph_definition(skill)
198 if req.as_document:
199 warning = generation.attach_document(graph_definition)
200 if warning:
201 warnings.append(warning)
203 return SkillGenerationResponse(
204 proposal=skill.model_dump(),
205 graph_definition=graph_definition,
206 name=skill.name,
207 description=skill.description,
208 tags=skill.tags[:6],
209 reasoning=skill.explanation,
210 problems=problems,
211 warnings=warnings,
212 )