Coverage for app / routers / skillset_setup.py: 99%

67 statements  

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

1""" 

2One-shot generative skillset setup. 

3 

4A narrower sibling of agent_setup.py's agent generation: svc-core sends a 

5description of the capability a user wants, together with catalogs of the 

6tenant's existing skills (the built-in ones included) and the agent-definition registry; 

7a single structured-output LLM call returns a proposed skillset (name, 

8description, selected/proposed skills) for the user to review. 

9 

10Skills-only by construction: this schema has no fields for tools or MCP 

11servers, so a generated skillset can never bundle either — those carry 

12credentials only a human should curate. 

13""" 

14 

15from fastapi import APIRouter, Depends, HTTPException 

16from langchain_core.messages import HumanMessage, SystemMessage 

17from pydantic import BaseModel, Field 

18from sqlalchemy.orm import Session 

19 

20from app import prompts 

21from app.services.structured_output import ModelOutput 

22from app.db.postgres.enums import InvocationEnum 

23from app.dependency.base import get_db 

24from app.models.spec import ModelConfig 

25from app.routers.agent_setup import ( 

26 CatalogAgentDefinition, 

27 CatalogSkill, 

28 ProposedSkill, 

29 ProposedSkillOut, 

30 _to_graph_definition, 

31 _validate_proposed_graph, 

32) 

33from app.services.conversation import persist_llm_invocation 

34from app.services.llm import build_langchain_llm 

35from app.services.structured_generation import ( 

36 generate, 

37) 

38from app.util.logger import get_logger 

39 

40logger = get_logger(__name__) 

41 

42router = APIRouter(prefix="/skillsets", tags=["skillset-setup"]) 

43 

44# Same budget as agent_setup — must undercut svc-core's client timeout. 

45GENERATION_BUDGET_S = 100.0 

46 

47 

48# --------------------------------------------------------------------------- 

49# Request models 

50# --------------------------------------------------------------------------- 

51 

52 

53class SkillsetConfigGenerationRequest(BaseModel): 

54 problem_description: str = Field(min_length=1) 

55 provider: str 

56 model: str 

57 # llm_models.id of the generation model, for the invocation trace 

58 model_id: str | None = None 

59 existing_skills: list[CatalogSkill] = [] 

60 agent_definitions: list[CatalogAgentDefinition] = [] 

61 user_id: str = "system" 

62 

63 

64# --------------------------------------------------------------------------- 

65# Structured-output schema — skills-only, no tool/MCP-server fields at all 

66# --------------------------------------------------------------------------- 

67 

68 

69class GeneratedSkillsetConfig(ModelOutput): 

70 """The complete proposal the LLM must produce.""" 

71 

72 name: str 

73 description: str = "" 

74 explanation: str = Field( 

75 default="", 

76 description="Why this proposal — written to the user.", 

77 # The model fills "explanation" (a field named for its reasoning can 

78 # be refused by Claude 5.x); svc-core reads it as "reasoning". 

79 serialization_alias="reasoning", 

80 ) 

81 selected_skill_ids: list[str] = [] 

82 proposed_skills: list[ProposedSkill] = [] 

83 

84 

85class GeneratedSkillsetConfigOut(BaseModel): 

86 name: str 

87 description: str = "" 

88 reasoning: str = "" 

89 selected_skill_ids: list[str] = [] 

90 proposed_skills: list[ProposedSkillOut] = [] 

91 

92 

93class GenerateSkillsetConfigResponse(BaseModel): 

94 config: GeneratedSkillsetConfigOut 

95 warnings: list[str] = [] 

96 

97 

98# --------------------------------------------------------------------------- 

99# Endpoint 

100# --------------------------------------------------------------------------- 

101 

102 

103def _build_user_content(req: SkillsetConfigGenerationRequest) -> str: 

104 def section(title: str, items: list[BaseModel]) -> str: 

105 if not items: 

106 return f"{title}: (none)" 

107 lines = "\n".join(f" - {item.model_dump_json()}" for item in items) 

108 return f"{title}:\n{lines}" 

109 

110 return ( 

111 f"Capability description:\n{req.problem_description}\n\n" 

112 + section("Existing skills catalog", req.existing_skills) 

113 + "\n\n" 

114 + section( 

115 "Available agent definitions for new skill graphs", 

116 req.agent_definitions, 

117 ) 

118 ) 

119 

120 

121@router.post("/generate-config", response_model=GenerateSkillsetConfigResponse) 

122async def generate_skillset_config( 

123 req: SkillsetConfigGenerationRequest, db: Session = Depends(get_db) 

124) -> GenerateSkillsetConfigResponse: 

125 """Generate a complete proposed skillset configuration in one structured call.""" 

126 system_prompt = prompts.build_skillset_config_generator_prompt( 

127 [d.name for d in req.agent_definitions] 

128 ) 

129 llm = build_langchain_llm( 

130 ModelConfig( 

131 provider=req.provider, 

132 model=req.model, 

133 temperature=0.2, 

134 max_tokens=8192, 

135 ) 

136 ) 

137 messages = [ 

138 SystemMessage(content=system_prompt), 

139 HumanMessage(content=_build_user_content(req)), 

140 ] 

141 

142 outcome = await generate( 

143 llm, 

144 GeneratedSkillsetConfig, 

145 messages, 

146 purpose="skillset-setup", 

147 budget_s=GENERATION_BUDGET_S, 

148 ) 

149 config = outcome.config 

150 

151 # The generation call is a real LLM invocation — trace it (success or 

152 # failure) so it appears in the activity view like any execution. 

153 persist_llm_invocation( 

154 db, 

155 purpose="skillset_generation", 

156 provider=req.provider, 

157 model=req.model, 

158 user_id=req.user_id, 

159 latency_ms=outcome.latency_ms, 

160 status=InvocationEnum.Status.success 

161 if config is not None 

162 else InvocationEnum.Status.error, 

163 error_detail=outcome.failure if config is None else None, 

164 request_config={ 

165 "provider": req.provider, 

166 "model": req.model, 

167 "temperature": 0.2, 

168 "max_tokens": 8192, 

169 "flow": "skillset_setup.generate_config", 

170 }, 

171 output_preview=config.model_dump_json(indent=2) if config else None, 

172 ) 

173 

174 if config is None: 

175 raise HTTPException( 

176 status_code=422, 

177 detail=f"Skillset configuration generation failed: {outcome.user_message}", 

178 ) 

179 

180 warnings: list[str] = [] 

181 definition_names = {d.name for d in req.agent_definitions} 

182 

183 proposed_skills: list[ProposedSkillOut] = [] 

184 for skill in config.proposed_skills: 

185 problems = _validate_proposed_graph(skill.graph, definition_names) 

186 if problems: 

187 warnings.append( 

188 f"Dropped proposed skill '{skill.name}': {'; '.join(problems)}" 

189 ) 

190 continue 

191 proposed_skills.append( 

192 ProposedSkillOut( 

193 name=skill.name, 

194 description=skill.description, 

195 tags=skill.tags, 

196 graph_definition=_to_graph_definition(skill.graph), 

197 ) 

198 ) 

199 

200 return GenerateSkillsetConfigResponse( 

201 config=GeneratedSkillsetConfigOut( 

202 name=config.name, 

203 description=config.description, 

204 reasoning=config.explanation, 

205 selected_skill_ids=config.selected_skill_ids, 

206 proposed_skills=proposed_skills, 

207 ), 

208 warnings=warnings, 

209 )