Coverage for app / inference / engines / skill.py: 95%
62 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"""
2SkillEngine — executes a stored Skill's graph_definition as a LangGraph.
4Handles ExecuteRequest(type="skill"). The skill graph runs as a subgraph
5inside the standard agent execution pipeline (gate → recon → planning →
6retrieval → SKILL GRAPH → synthesis → evaluator): the user-designed nodes
7form the skill region, with dispatch PINNED so the planner contributes
8per-node goals and tool guidance but cannot prune or reorder the workflow.
10Schema v2 graphs additionally support typed nodes (agent | tool | transform),
11a user-declared state contract carried in GraphState.state_vars, prompt
12templates over state, and fan-out/fan-in parallelism — see
13AgentFactory.from_graph_definition for the full format.
14"""
16from __future__ import annotations
18from typing import Any
20from app.inference.context import InferenceContext
21from app.inference.engines.graph_based import GraphBasedEngine
22from app.models.spec import SkillSpec
23from app.util.logger import get_logger
25logger = get_logger(__name__)
28class SkillEngine(GraphBasedEngine):
29 """
30 Executes a stored Skill's graph_definition via the unified graph template.
31 """
33 @staticmethod
34 def _seed_interface_inputs(
35 interface: dict[str, Any], provided: dict[str, Any]
36 ) -> dict[str, Any]:
37 """Validate caller inputs against ``interface.inputs`` → state seed."""
38 from app.agents.interfaces import normalise_schema, validate_inputs
40 provided = dict(provided or {})
41 try:
42 specs = normalise_schema((interface or {}).get("inputs"))
43 except ValueError as exc:
44 logger.warning("[skill] invalid interface.inputs ignored: %s", exc)
45 return provided
46 if not specs:
47 return provided
48 coerced, problems = validate_inputs(specs, provided)
49 if problems:
50 logger.warning("[skill] interface input problems: %s", problems)
51 return {k: v for k, v in coerced.items() if v is not None}
53 def _build_builder(
54 self, ctx: InferenceContext
55 ) -> tuple[Any, list[dict], dict[str, Any]]:
56 from app.agents import effort as effort_registry
57 from app.agents.factory import AgentFactory
58 from app.agents.fixtures import apply_to_graph as apply_fixtures
59 from app.inference.output_shape import AnswerShape
60 from app.models.spec import ModelConfig
61 from app.services.llm import build_format_instruction, build_langchain_llm
63 spec: SkillSpec = ctx.request.spec # type: ignore[assignment]
64 logger.info(
65 "[skill] executing skill graph skill_id=%s name=%r",
66 spec.skill_id,
67 spec.name,
68 )
70 # Append format instruction to the input if needed
71 task_input = ctx.filtered_input
72 if spec.output_format and spec.output_format != "markdown":
73 format_instr = build_format_instruction(
74 spec.output_format, spec.output_schema
75 )
76 if format_instr:
77 task_input = f"{task_input}\n\n---\n\n{format_instr}"
78 ctx.filtered_input = task_input
80 llm_override = None
81 override_cfg: ModelConfig | None = None
82 if spec.system_model_override:
83 try:
84 override_cfg = ModelConfig(**spec.system_model_override)
85 llm_override = build_langchain_llm(override_cfg)
86 logger.info(
87 "[skill] LLM override: provider=%s model=%s",
88 override_cfg.provider,
89 override_cfg.model,
90 )
91 except Exception as exc:
92 logger.warning(
93 "[skill] LLM override failed (%s) — using stored model configs", exc
94 )
96 builder = AgentFactory.from_graph_definition(
97 spec.graph_definition,
98 self.db,
99 llm_override=llm_override,
100 default_model=spec.default_model,
101 )
102 builder.clarify_scope = spec.clarify_scope
103 # Asked for as JSON, the skill's answer is held to it once the run
104 # ends, on the model its nodes run on by default (``output_shape``).
105 builder.answer_shape = AnswerShape.of(
106 spec.output_format,
107 spec.output_schema,
108 override_cfg if llm_override is not None else spec.default_model,
109 )
110 builder.cost_profile = spec.cost_profile.value
111 # An Economy profile's lighter model, for the steps nobody reads; a
112 # stored graph's nodes keep their own models.
113 builder.lighter_model = spec.lighter_model
114 # A native sibling for its structured system steps; the nodes' own
115 # typed outputs stay on their models (``native_sibling``).
116 builder.structured_model = spec.structured_model
117 # The platform's web sources, when the built-in agent answers
118 # through a skill (``tools/web/platform_sources.py``).
119 builder.platform_sources = frozenset(spec.platform_sources)
120 # An evaluation case's scripted tools, wherever a node binds or calls
121 # one of their name — as a plain agent's are bound.
122 apply_fixtures(builder, spec.tool_fixtures)
124 # Seed user-declared state defaults (schema v2 "state" block) so
125 # templates and operations can reference keys before any node has
126 # written them. Picked up by GraphBasedEngine when constructing
127 # the initial GraphState.
128 state_spec: dict[str, Any] = spec.graph_definition.get("state") or {}
129 initial_state_vars: dict[str, Any] = {
130 key: field.get("default")
131 for key, field in state_spec.items()
132 if isinstance(field, dict) and "default" in field
133 }
134 # Schema v3 — the skill's declared input interface. Caller-supplied
135 # values are validated and coerced against it; declared defaults fill
136 # gaps; problems are logged (the skill still runs — the node-level
137 # binding surfaces missing values as warnings in the trace).
138 initial_state_vars.update(
139 self._seed_interface_inputs(builder.skill_interface, spec.inputs)
140 )
141 builder._initial_state_vars = initial_state_vars
143 knowledge_bases = [kb.model_dump() for kb in spec.knowledge_bases]
144 extra_context: dict[str, Any] = {
145 "skill_id": spec.skill_id,
146 "skill_name": spec.name,
147 "retrieval_config": spec.retrieval.model_dump(),
148 # The skill graph is the user's explicit workflow — pin dispatch
149 # so the planner cannot prune nodes (see planning node in graph.py).
150 "pinned_node_ids": list(builder.nodes.keys()),
151 # Persona of the owning agent, threaded into GraphState by
152 # GraphBasedEngine so all nodes respond in-persona.
153 "agent_name": spec.agent_name,
154 "agent_system_prompt": spec.agent_system_prompt,
155 # How much pipeline work the turn does (app/agents/effort.py).
156 effort_registry.CONTEXT_KEY: spec.cost_profile.value,
157 }
159 return builder, knowledge_bases, extra_context