Coverage for app / router / app / skills / setup.py: 86%
136 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Generative skill creation.
4POST /app/skills/generate — design one skill from a description,
5 an optional pattern (a template name) and an optional document ending.
6 svc-ai proposes a graph; it is validated here with ``_GraphDefinitionSchema``,
7 the schema that guards a hand-built skill. A proposal that fails is sent
8 back once with the problems, and if it fails again the request fails with
9 them. Nothing is repaired here: every fix is the model's own second
10 attempt, validated again. Creates nothing.
12POST /app/skills/create-from-config — persist a reviewed proposal as one
13 skill, stamped with its GenerationRun and versioned, after the same
14 checks as ``POST /app/skills`` (worker, MCP and model-pin access).
16Skills generated here run only svc-ai's built-in workers and the caller's own
17custom workers, and call only the default tools (svc-ai ``node_tools``).
18"""
20from __future__ import annotations
22import logging
23from typing import Any
24from uuid import UUID, uuid4
26from fastapi import APIRouter, Depends, HTTPException, status
27from pydantic import BaseModel, Field, ValidationError, field_validator
28from sqlalchemy.exc import IntegrityError
29from sqlalchemy.orm import Session
31from app.db.postgres.crud_schemas import Schema, _GraphDefinitionSchema
32from app.db.postgres.enums import GenerationEnum, HistoryEnum
33from app.db.postgres.models import CustomWorker, Skill, User
34from app.dependency.base import get_db
35from app.dependency.workspace import owner_for, request_workspace
36from app.dependency.user.context import get_current_user
37from app.router.app.agents.setup import (
38 MAX_CATALOG_ITEMS,
39 GenerationModelInfo,
40 _dedupe_name,
41 _resolve_generation_model,
42 _truncate,
43)
44from app.services import ai_client, skill_graph
45from app.services import generation as generation_service
46from app.services import history as history_service
47from app.services.ai_client import AIServiceError, GenerationFailedError
49logger = logging.getLogger(__name__)
51skill_setup_router = APIRouter(prefix="/skills", tags=["App - Skill Setup"])
53#: One proposal, then one attempt to fix what was wrong with it.
54MAX_ATTEMPTS = 2
57class GenerateSkillRequest(BaseModel):
58 description: str = Field(min_length=10, max_length=4000)
59 #: A template (pattern) to start from — svc-ai's ``GET /skills/available``.
60 template: str | None = Field(default=None, max_length=100)
61 #: End the skill in a downloadable document.
62 as_document: bool = False
63 ai_model_id: UUID | None = None
66class SkillGenerationProposal(BaseModel):
67 name: str
68 description: str = ""
69 tags: list[str] = []
70 reasoning: str = ""
71 graph_definition: dict[str, Any]
72 template: str | None = None
73 as_document: bool = False
74 warnings: list[str] = []
75 model: GenerationModelInfo
76 # Echoed back on create-from-config; see app.services.generation.
77 generation_id: UUID
80class CreateSkillFromConfigRequest(BaseModel):
81 name: str = Field(min_length=1, max_length=255)
82 description: str | None = None
83 tags: list[str] = []
84 graph_definition: dict
85 generation_id: UUID | None = None
87 @field_validator("graph_definition", mode="before")
88 @classmethod
89 def _valid_graph(cls, v: Any) -> Any:
90 # The reviewed graph comes back from the client: hold it to the
91 # schema a hand-built skill is held to.
92 _GraphDefinitionSchema(**(v or {}))
93 return v
96def schema_problems(graph: dict[str, Any] | None) -> list[str]:
97 """What ``_GraphDefinitionSchema`` refuses in ``graph``, as plain lines."""
98 if graph is None:
99 return ["no graph was produced"]
100 try:
101 _GraphDefinitionSchema(**graph)
102 except ValidationError as exc:
103 return [
104 str(e.get("msg", "")).removeprefix("Value error, ") for e in exc.errors()
105 ]
106 return []
109@skill_setup_router.post("/generate", response_model=SkillGenerationProposal)
110def generate_skill(
111 body: GenerateSkillRequest,
112 db: Session = Depends(get_db),
113 current_user: User = Depends(get_current_user),
114):
115 """Design one skill for review. Records the invocation; creates no skill."""
116 try:
117 model_info = _resolve_generation_model(body.ai_model_id)
118 except AIServiceError as exc:
119 run = generation_service.start(
120 db,
121 flow=GenerationEnum.Flow.skill_setup,
122 actor=current_user,
123 arguments=body.model_dump(),
124 )
125 generation_service.fail(db, run, error=str(exc))
126 db.commit()
127 raise HTTPException(
128 status_code=status.HTTP_502_BAD_GATEWAY,
129 detail=f"Could not resolve a generation model: {exc}",
130 )
131 provider = model_info["provider"]["name"]
132 model_name = model_info["model_name"]
134 run = generation_service.start(
135 db,
136 flow=GenerationEnum.Flow.skill_setup,
137 actor=current_user,
138 arguments=body.model_dump(),
139 model_info=model_info,
140 )
141 warnings: list[str] = []
143 try:
144 definitions = ai_client.list_agent_definitions(is_builtin=True)
145 except AIServiceError as exc:
146 logger.warning("Could not fetch agent definitions from svc-ai: %s", exc)
147 generation_service.fail(db, run, error=str(exc))
148 db.commit()
149 raise HTTPException(
150 status_code=status.HTTP_502_BAD_GATEWAY,
151 detail="Could not reach svc-ai for the worker catalogue.",
152 )
153 custom_workers = (
154 db.query(CustomWorker)
155 .filter(
156 request_workspace(db, current_user).owns(CustomWorker),
157 CustomWorker.definition_name.isnot(None),
158 )
159 .limit(MAX_CATALOG_ITEMS)
160 .all()
161 )
163 payload: dict[str, Any] = {
164 "description": body.description,
165 "provider": provider,
166 "model": model_name,
167 "model_id": str(model_info["id"]) if model_info.get("id") else None,
168 "template": body.template,
169 "as_document": body.as_document,
170 "agent_definitions": [
171 {
172 "name": d.get("name", ""),
173 "role": d.get("role", "worker"),
174 "description": _truncate(d.get("description")),
175 }
176 for d in definitions
177 ]
178 + [
179 {
180 "name": w.definition_name,
181 "role": w.role or "worker",
182 "description": _truncate(
183 f"{w.name} (your custom worker): {w.description or ''}"
184 ),
185 }
186 for w in custom_workers
187 ],
188 "user_id": str(current_user.id),
189 }
191 result: dict[str, Any] = {}
192 problems: list[str] = []
193 try:
194 with generation_service.metered(db, run):
195 for attempt in range(MAX_ATTEMPTS):
196 result = ai_client.generate_skill_config(payload)
197 problems = list(result.get("problems") or []) or schema_problems(
198 result.get("graph_definition")
199 )
200 if not problems:
201 break
202 if attempt + 1 < MAX_ATTEMPTS:
203 warnings.append(
204 "The first design had problems and was redesigned: "
205 + "; ".join(problems[:5])
206 )
207 payload = {
208 **payload,
209 "previous": result.get("proposal"),
210 "feedback": problems,
211 }
212 except GenerationFailedError as exc:
213 generation_service.fail(db, run, error=str(exc))
214 db.commit()
215 raise HTTPException(
216 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
217 )
218 except AIServiceError as exc:
219 logger.error("Skill generation failed: %s", exc)
220 generation_service.fail(db, run, error=str(exc))
221 db.commit()
222 raise HTTPException(
223 status_code=status.HTTP_502_BAD_GATEWAY,
224 detail="Could not reach svc-ai to generate the skill.",
225 )
227 if problems:
228 error = "The generated skill was not valid: " + "; ".join(problems[:8])
229 generation_service.fail(db, run, error=error)
230 db.commit()
231 raise HTTPException(
232 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
233 detail=f"{error}. Try rewording the description, or another model.",
234 )
236 warnings.extend(result.get("warnings") or [])
237 taken = {
238 name
239 for (name,) in db.query(Skill.name)
240 # Unique among the skills of the workspace it is created in.
241 .filter(request_workspace(db, current_user).owns(Skill))
242 .all()
243 }
244 proposed_name = (result.get("name") or "New skill").strip()[:255] or "New skill"
245 name = _dedupe_name(proposed_name, taken)
246 if name != proposed_name:
247 warnings.append(
248 f"Renamed '{proposed_name}' to '{name}' to avoid a name conflict."
249 )
251 generation_service.record_warnings(run, warnings)
252 db.commit()
254 return SkillGenerationProposal(
255 name=name,
256 description=result.get("description") or "",
257 tags=[str(t) for t in (result.get("tags") or [])][:6],
258 reasoning=result.get("reasoning") or "",
259 graph_definition=result["graph_definition"],
260 template=body.template,
261 as_document=body.as_document,
262 warnings=warnings,
263 model=GenerationModelInfo(
264 provider=provider,
265 model_name=model_name,
266 ai_model_id=model_info.get("id"),
267 ),
268 generation_id=run.id,
269 )
272@skill_setup_router.post(
273 "/create-from-config",
274 response_model=Schema.Skill.Read,
275 status_code=status.HTTP_201_CREATED,
276)
277def create_skill_from_config(
278 body: CreateSkillFromConfigRequest,
279 db: Session = Depends(get_db),
280 current_user: User = Depends(get_current_user),
281):
282 """Persist a reviewed generated skill, stamped with its invocation."""
283 # Same worker / MCP / model-pin checks as a hand-built skill.
284 skill_graph.validate_node_overrides(body.graph_definition, db, current_user)
285 run = generation_service.resolve(db, body.generation_id, current_user)
287 skill = Skill(
288 id=uuid4(),
289 name=body.name.strip(),
290 description=body.description,
291 tags=body.tags,
292 graph_definition=body.graph_definition,
293 **owner_for(db, current_user, model=Skill),
294 )
295 generation_service.stamp([skill], run)
296 # This endpoint only ever persists generated output, so the flag holds
297 # even for a client that did not echo an id back.
298 skill.is_ai_generated = True
299 try:
300 db.add(skill)
301 db.flush()
302 db.add(
303 history_service.build_version(
304 db,
305 resource_type=HistoryEnum.ResourceType.skill,
306 model=Skill,
307 resource=skill,
308 action=HistoryEnum.Action.created,
309 actor=current_user,
310 )
311 )
312 generation_service.apply(
313 db,
314 run,
315 target_resource_type=HistoryEnum.ResourceType.skill,
316 target_resource_id=skill.id,
317 )
318 db.commit()
319 except IntegrityError:
320 db.rollback()
321 raise HTTPException(
322 status_code=status.HTTP_409_CONFLICT,
323 detail=f"You already have a skill named '{body.name}'. Rename it and try again.",
324 )
325 except Exception:
326 db.rollback()
327 logger.exception("Failed to create skill from generated config")
328 raise
329 db.refresh(skill)
330 return skill