Coverage for app / services / agent_spec.py: 97%
105 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"""
2One agent turn as svc-ai runs it (cost-control plan, B2.1).
4Every path that runs one of the user's agents — its chat over the socket,
5the batch prompt, an evaluation cell, a dashboard tile — used to assemble
6svc-ai's request itself, and the four had drifted: an evaluation never ran
7the agent's skill graph (chat did), so its evidence described a different
8agent from the one people talk to; the batch path never told a skill graph
9the agent's model settings for the system nodes; and a new setting had to be
10threaded through four call sites. So the request is built here, once, and
11each path says only what is particular to it:
13``load(db, agent)``
14 What the agent brings to every turn: its instructions, the skill it
15 answers through, its knowledge, MCP servers and retrieval settings,
16 whether it checks a request's scope first, and its cost profile.
17``resolve_skill(db, setup, skill)``
18 That skill's graph as this deployment can run it — node pins it cannot
19 serve dropped, each with a note (``skill_graph.resolve_for_execution``).
20``build(setup, …)`` → :class:`AgentRequest`
21 svc-ai's ``type`` and ``spec``: the skill graph when the agent answers
22 through one, the agent itself otherwise. ``payload(…)`` adds the turn.
24An evaluation's variant may change the knowledge, the tools, the scripted
25tools, the prompt and the model settings (:class:`Overrides`). A skill graph
26takes all of them but one: its tools are its nodes', so a variant that names
27its own tools runs the agent as itself, and the run says which ran
28(``AgentRequest.skill_id``).
30``tests/test_agent_spec.py`` pins that every path builds through here.
31"""
33from __future__ import annotations
35from dataclasses import dataclass, field
36from types import SimpleNamespace
37from typing import Any, Literal
39from sqlalchemy.orm import Session
41from app.util import cost_profiles
44@dataclass(frozen=True)
45class AgentSetup:
46 """What an agent brings to every turn, read once from the database."""
48 id: str
49 name: str
50 system_prompt: str
51 clarify_scope: bool
52 cost_profile: str
53 #: The skills it holds, oldest first; a turn answers through the first.
54 skills: tuple[Any, ...]
55 knowledge_bases: list[dict]
56 mcp_servers: list[dict]
57 retrieval: dict
58 #: Its owner columns: the workspace its skill graph's tools read.
59 owner: SimpleNamespace = field(default_factory=SimpleNamespace)
60 #: The web sources its searches put first: the built-in agent's own list
61 #: (``system_resources/web_sources.py``), none for any other agent.
62 platform_sources: tuple[str, ...] = ()
65def default_prompt(name: str) -> str:
66 return f"You are {name}, a helpful AI assistant."
69#: The agent columns ``load`` reads — all a snapshot needs.
70SNAPSHOT_FIELDS = (
71 "id",
72 "name",
73 "system_prompt",
74 "clarify_scope",
75 "cost_profile",
76 "config",
77 "is_system",
78 "owner_user_id",
79 "owner_organisation_id",
80 "owner_project_id",
81)
84def snapshot(agent: Any) -> SimpleNamespace:
85 """The agent's columns ``load`` reads, copied now — for a caller that
86 loads later on another thread, where reading an expired ORM row would
87 query a session another thread is using (an evaluation's pool)."""
88 return SimpleNamespace(
89 **{name: getattr(agent, name, None) for name in SNAPSHOT_FIELDS}
90 )
93def load(db: Session, agent: Any) -> AgentSetup:
94 """What ``agent`` brings to a turn, read in ``db`` (the caller's session
95 — a chat socket reads it in a worker thread's own). ``agent`` is a row,
96 or its :func:`snapshot`."""
97 # Imported here: the agent transformers build on this module.
98 from app.router.app.agents import transformers
99 from app.services import mcp as mcp_service
100 from app.services.system_resources import web_sources
102 return AgentSetup(
103 id=str(agent.id),
104 name=str(agent.name),
105 system_prompt=agent.system_prompt or default_prompt(agent.name),
106 clarify_scope=bool(getattr(agent, "clarify_scope", False)),
107 cost_profile=str(
108 getattr(agent, "cost_profile", None) or cost_profiles.DEFAULT.value
109 ),
110 skills=tuple(transformers._load_agent_skills(db, agent)),
111 knowledge_bases=transformers._load_agent_knowledge_bases(db, agent),
112 mcp_servers=mcp_service.load_agent_mcp_descriptors(db, agent),
113 retrieval=transformers._load_agent_retrieval_config(agent),
114 owner=SimpleNamespace(
115 owner_user_id=agent.owner_user_id,
116 owner_organisation_id=agent.owner_organisation_id,
117 owner_project_id=agent.owner_project_id,
118 ),
119 # Only a built-in agent's config is the platform's: nobody can write
120 # one, so nothing a person sets on their own agent reaches here.
121 platform_sources=(
122 tuple(web_sources.preferred_of(getattr(agent, "config", None)))
123 if getattr(agent, "is_system", False)
124 else ()
125 ),
126 )
129def resolve_skill(db: Session, setup: AgentSetup, skill: Any) -> tuple[dict, list[str]]:
130 """``skill``'s graph as this deployment runs it, in the agent's own
131 workspace, and the notes to show for anything changed."""
132 from app.services import skill_graph
133 from app.services import workspace as workspace_service
135 notes: list[str] = []
136 graph = skill_graph.resolve_for_execution(
137 skill.graph_definition or {},
138 db,
139 workspace=workspace_service.home_of(db, setup.owner),
140 notes=notes,
141 )
142 return graph, notes
145@dataclass(frozen=True)
146class Overrides:
147 """What an evaluation's variant changes for one cell (its context)."""
149 #: The knowledge the agent may reach. None: its own; empty: none.
150 knowledge_bases: list[dict] | None = None
151 #: The tools it may call. None: its own (svc-ai's general set); a list:
152 #: exactly these — which only the agent itself can take, not a skill
153 #: graph, whose tools are its nodes'.
154 tools: list[dict] | None = None
155 #: Tools answered from a script, wherever a tool of the name is called.
156 tool_fixtures: list[dict] = field(default_factory=list)
157 #: A candidate prompt in place of the agent's own.
158 system_prompt: str | None = None
161@dataclass(frozen=True)
162class AgentRequest:
163 """svc-ai's ``type`` and ``spec`` for one turn of an agent."""
165 type: Literal["agent", "skill"]
166 spec: dict[str, Any]
167 #: The catalogue row of the lighter model an Economy profile does its
168 #: lighter work on (``services/lighter_model.py``), or None — what the
169 #: turn's record names when svc-ai says it wrote the answer.
170 lighter_model: dict[str, Any] | None = None
172 @property
173 def skill_id(self) -> str | None:
174 """The skill the turn answers through, if it does."""
175 return self.spec.get("skill_id") if self.type == "skill" else None
177 def payload(
178 self,
179 *,
180 prompt: str,
181 messages: list[dict],
182 user_id: str,
183 rules: list[dict] | None = None,
184 session_id: str | None = None,
185 conversation_id: str | None = None,
186 external_agent_id: str | None = None,
187 memory: bool = True,
188 may_ask: bool = True,
189 purpose: str | None = None,
190 reference: dict[str, str] | None = None,
191 attachments: list[dict[str, Any]] | None = None,
192 ) -> dict[str, Any]:
193 """The execute request for one turn of it. ``may_ask`` False: nobody
194 attends the turn (a dashboard tile), so svc-ai never offers it
195 ``ask_user`` nor runs the scope check. ``attachments`` are the
196 conversation's documents (``attachments.wire``), beside the words in
197 ``prompt``: sent only when there are some, so every other path's
198 request is as it was."""
199 from app.services import ai_client
201 return {
202 "type": self.type,
203 "spec": self.spec,
204 "input": prompt,
205 **({"attachments": attachments} if attachments else {}),
206 "messages": messages,
207 "user_id": user_id,
208 "rules": rules or [],
209 **({"session_id": session_id} if session_id else {}),
210 **({"conversation_id": conversation_id} if conversation_id else {}),
211 **({"external_agent_id": external_agent_id} if external_agent_id else {}),
212 **({} if memory else {"memory": False}),
213 **({} if may_ask else {"may_ask": False}),
214 **ai_client._trace_fields(purpose, reference),
215 }
218def skill_model(model_info: dict, config: dict | None = None) -> dict:
219 """The agent's model, for the nodes of its skill that name none — with
220 its sampling settings, so an evaluation's temperature or effort reaches
221 them as it reaches the agent."""
222 config = config or {}
223 model: dict = {
224 "provider": model_info["provider"]["name"],
225 "model": model_info["model_name"],
226 }
227 for key in ("temperature", "max_tokens", "effort"):
228 if config.get(key) is not None:
229 model[key] = config[key]
230 return model
233def build(
234 setup: AgentSetup,
235 *,
236 model_info: dict,
237 config: dict | None = None,
238 skill: Any = None,
239 graph_definition: dict | None = None,
240 interactive: bool = False,
241 output_format: str | None = None,
242 output_schema: str | None = None,
243 model_override: bool = False,
244 inputs: dict | None = None,
245 overrides: Overrides | None = None,
246 lighter: Any = None,
247 structured: Any = None,
248) -> AgentRequest:
249 """One turn of the agent ``setup`` describes, as svc-ai runs it.
251 ``skill`` is the skill it answers through (``setup.skills[0]``, a chat
252 command's, or None with the skill graph switched off), with its graph
253 from ``resolve_skill``. ``interactive``: a person can answer a pause, so
254 an agent that checks a request's scope may ask. ``model_override``: a
255 person chose the model for this turn, so every node runs on it — and no
256 lighter model does any of it. ``lighter`` is the lighter model an
257 Economy profile does its lighter work on (``lighter_model.for_turn``);
258 ``structured`` the native sibling that makes the turn's structured
259 system steps when their model cannot decode a schema
260 (``native_sibling.for_turn``) — neither when a person chose the model.
261 """
262 from app.services import lighter_model as lighter_service
263 from app.services import native_sibling
264 from app.services.ai_client import (
265 DEFAULT_MAX_TOKENS,
266 DEFAULT_TEMPERATURE,
267 _model_spec,
268 )
270 config = dict(config or {})
271 overrides = overrides or Overrides()
272 lighter_spec = (
273 lighter_service.spec(lighter, config)
274 if lighter is not None and not model_override
275 else None
276 )
277 lighter_row = lighter.model if lighter_spec else None
278 structured_spec = native_sibling.spec(structured) if not model_override else None
279 system_prompt = overrides.system_prompt or setup.system_prompt
280 knowledge = (
281 setup.knowledge_bases
282 if overrides.knowledge_bases is None
283 else overrides.knowledge_bases
284 )
285 fixtures = list(overrides.tool_fixtures or [])
286 clarify = bool(interactive and setup.clarify_scope)
288 if skill is not None and overrides.tools is None:
289 spec: dict[str, Any] = {
290 "skill_id": str(skill.id),
291 "name": skill.name,
292 "graph_definition": graph_definition
293 if graph_definition is not None
294 else (skill.graph_definition or {}),
295 "knowledge_bases": knowledge,
296 "retrieval": setup.retrieval,
297 # Persona: without these the skill pipeline answers generically,
298 # ignoring the agent's configured identity and instructions.
299 "agent_name": setup.name,
300 "agent_system_prompt": system_prompt,
301 "clarify_scope": clarify,
302 # Nodes that name no model run on the agent's (svc-ai's worker
303 # definitions name none); a pinned node keeps its pin.
304 "default_model": skill_model(model_info, config),
305 "inputs": dict(inputs or {}),
306 "cost_profile": setup.cost_profile,
307 }
308 if setup.platform_sources:
309 spec["platform_sources"] = list(setup.platform_sources)
310 if fixtures:
311 spec["tool_fixtures"] = fixtures
312 if output_format:
313 spec["output_format"] = output_format
314 if output_schema:
315 spec["output_schema"] = output_schema
316 if model_override:
317 spec["system_model_override"] = {
318 "provider": model_info["provider"]["name"],
319 "model": model_info["model_name"],
320 "temperature": config.get("temperature", DEFAULT_TEMPERATURE),
321 "max_tokens": config.get("max_tokens", DEFAULT_MAX_TOKENS),
322 }
323 if lighter_spec:
324 spec["lighter_model"] = lighter_spec
325 if structured_spec:
326 spec["structured_model"] = structured_spec
327 return AgentRequest("skill", spec, lighter_model=lighter_row)
329 model = _model_spec(
330 model_info["provider"]["name"], model_info["model_name"], config, system_prompt
331 )
332 if output_format:
333 model["output_format"] = output_format
334 if output_schema:
335 model["output_schema"] = output_schema
336 tools = overrides.tools
337 spec = {
338 "name": setup.name,
339 "role": "worker",
340 "model": model,
341 # Built-in tools are svc-ai's general set, bound to every agent; an
342 # explicit list is exactly the tools the turn may call.
343 "tools": [
344 {
345 "name": t["name"],
346 "type": t.get("type", "builtin"),
347 "config": t.get("config", {}),
348 }
349 for t in tools or []
350 ],
351 "tools_enabled": tools is None,
352 "knowledge_bases": knowledge,
353 "mcp_servers": setup.mcp_servers,
354 "retrieval": setup.retrieval,
355 "clarify_scope": clarify,
356 "cost_profile": setup.cost_profile,
357 }
358 if setup.platform_sources:
359 # The sources CHAIN-R puts first for its own agent, never a tool's
360 # config: svc-ai carries them in the run's config.
361 spec["platform_sources"] = list(setup.platform_sources)
362 if fixtures:
363 spec["tool_fixtures"] = fixtures
364 if lighter_spec:
365 spec["lighter_model"] = lighter_spec
366 if structured_spec:
367 spec["structured_model"] = structured_spec
368 return AgentRequest("agent", spec, lighter_model=lighter_row)