Coverage for app / services / dashboards / generator.py: 97%
298 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"""Generative dashboard setup.
3A user describes what they want to watch — "monitor the market and news so I
4know what stocks to look at" — and this proposes a whole board: which widgets,
5configured how, laid out where.
7Two things make that safe to hand to a model:
9*The catalogue is generated from the registry.* Every widget type's
10``config_schema`` is written next to the ``validate_config`` that enforces it,
11so the prompt cannot drift from what the backend accepts, and a newly
12registered type becomes generatable with no change here.
14*Nothing the model returns is trusted.* Every proposed widget is re-validated
15through its own renderer; a tile that fails is sent back once with what was
16wrong, and dropped with a warning if it fails again, rather than failing the
17board. The agent a model-backed tile runs on is picked by the model from a
18fixed list of handles for the workspace's agents, which the server maps to
19ids — the model never supplies one — and feed URLs are checked before they
20are accepted. Layout is recomputed here because models pack grids badly.
22*It is told what it is building with.* The catalogue offers only what this
23deployment can draw and this workspace can run, the agents are described by
24what they can reach, and the platform's own licence-checked feeds are offered
25before any the model would have to remember.
27Generation runs in svc-core rather than through svc-ai's ``generate_*_config``
28endpoints (as agent/skillset/toolkit setup do) because the widget registry
29being described lives here; routing it through svc-ai would mean keeping a
30copy of this catalogue in another service.
31"""
33from __future__ import annotations
35import functools
36import logging
37import time
38from collections.abc import Mapping
39from dataclasses import dataclass
40from typing import Any, Literal, Optional
41from uuid import UUID
43from pydantic import Field, OnErrorOmit, create_model
44from sqlalchemy.orm import Session
46from app.db.postgres.enums import DashboardEnum
47from app.db.postgres.models import Agent
48from app.services import appearance, structured_reply
49from app.util import vocab
50from app.util.model_output import ModelOutput
52from .widgets import (
53 WidgetConfigError,
54 WidgetRenderer,
55 catalogue,
56 get_renderer,
57 renderers,
58 validate_widget,
59)
61logger = logging.getLogger(__name__)
63#: What svc-ai records the board-design call as — the other generative flows
64#: record ``agent_generation`` and the like, and this one used to inherit
65#: "evaluation" from the target it borrows.
66GENERATION_TRACE_PURPOSE = "dashboard_generation"
68#: Widgets a single generated board may contain. Enough for a rich board,
69#: few enough that one refresh cannot fan out into dozens of vendor calls.
70MAX_WIDGETS = 12
71#: The fewest a proposal is asked for — and the size a good board usually is.
72MIN_WIDGETS = 3
73IDEAL_WIDGETS = (6, 9)
75#: A dynamic tile's shortest refresh cadence; anything quicker is reset to the
76#: type's default. A type may set a longer floor of its own
77#: (``WidgetRenderer.min_refresh_interval_seconds``).
78MIN_REFRESH_INTERVAL_SECONDS = 60
80#: The board designer's output budget. A board is up to twelve tiles, each
81#: config written as escaped JSON text, and a model that reasons first
82#: spends part of the budget thinking: at 4,096 a full board was cut off,
83#: and so was its correction. svc-ai caps it to the model's own limit.
84GENERATION_MAX_TOKENS = 16_384
86#: The workspace's agents the designer may put a tile on, at most.
87MAX_AGENT_CHOICES = 12
89#: A correction round is skipped once this much of the request has gone: the
90#: person is waiting on it, and svc-bff, nginx and fe-core all give up at
91#: three minutes (``PROXY_TIMEOUT_LONG``) — a second call started later would
92#: be paid for and never seen.
93CORRECTION_CUTOFF_S = 90.0
95#: The grid the frontend renders against.
96GRID_COLUMNS = 12
98#: Boards are named by the model; keep it to something that fits a nav item.
99MAX_NAME_LENGTH = 60
101#: Presentation vocabulary lives in `app.services.appearance` because agents
102#: are styled from the same palette; only the icon set is board-specific.
103ICONS = appearance.DASHBOARD_ICONS
104ACCENTS = appearance.ACCENTS
107class DashboardGenerationError(RuntimeError):
108 """The model could not produce a usable board — the description is the
109 thing to change (a 422)."""
112class DashboardGenerationUnavailable(RuntimeError):
113 """The model could not be asked at all — svc-ai unreachable, or the model
114 refused for a reason the message names (a 502). Its message is safe to
115 show."""
118# ---------------------------------------------------------------------------
119# Prompt
120# ---------------------------------------------------------------------------
123#: What each kind of tile content is, as the catalogue tells the model —
124#: one entry per data kind, checked at import.
125_DATA_KINDS: dict[DashboardEnum.DataKind, str] = {
126 DashboardEnum.DataKind.stored: "content the user writes or saves",
127 DashboardEnum.DataKind.platform: "EXACT data from the platform's own records",
128 DashboardEnum.DataKind.feed: "EXACT data from a named external source",
129 DashboardEnum.DataKind.generated: "a model's judgement, not fact",
130}
131vocab.check(_DATA_KINDS, DashboardEnum.DataKind)
134def offered_renderers(*, has_target: bool = True) -> list[WidgetRenderer]:
135 """The types the designer may propose here: never one that keeps a
136 user's content (a model writing it would read as something the user
137 saved), never one this deployment cannot draw (a market tile with no
138 vendor), and a model-backed one only when something can run it — a
139 field the model may not fill is left out of what it is shown."""
140 return [
141 renderer
142 for renderer in renderers()
143 if renderer.generatable
144 and renderer.available()
145 and (has_target or renderer.data_kind != DashboardEnum.DataKind.generated)
146 ]
149def _shown_hints(renderer: WidgetRenderer) -> dict[str, str]:
150 """A type's config hints without the fields the model is never shown:
151 the resource ids it cannot know, and the target the server picks."""
152 hidden = {*renderer.reference_fields, "target"}
153 return {k: v for k, v in renderer.config_hints().items() if k not in hidden}
156def _shown_defaults(renderer: WidgetRenderer) -> dict[str, Any]:
157 hidden = {*renderer.reference_fields, "target"}
158 return {k: v for k, v in renderer.default_config.items() if k not in hidden}
161def _min_interval(renderer: WidgetRenderer) -> int:
162 return max(MIN_REFRESH_INTERVAL_SECONDS, renderer.min_refresh_interval_seconds)
165def catalogue_prompt(offered: list[WidgetRenderer] | None = None) -> str:
166 """The widget catalogue, rendered for the model from the live registry."""
167 import json
169 lines: list[str] = []
170 for renderer in offered if offered is not None else offered_renderers():
171 kind = _DATA_KINDS[renderer.data_kind]
173 lines.append(f"\n### {renderer.type} ({kind})")
174 lines.append(renderer.description)
175 size = renderer.default_size
176 lines.append(
177 f"Typical size: w={size['w']}, h={size['h']} "
178 f"(grid is {GRID_COLUMNS} columns wide)."
179 )
180 if renderer.is_dynamic:
181 lines.append(
182 "Refreshes on a cadence; set refresh_interval_seconds "
183 f"(default {renderer.default_refresh_interval_seconds}s, minimum "
184 f"{_min_interval(renderer)})."
185 )
186 hints = _shown_hints(renderer)
187 if hints:
188 lines.append("config fields:")
189 for field, hint in hints.items():
190 lines.append(f" - {field}: {hint}")
191 defaults = _shown_defaults(renderer)
192 if defaults:
193 lines.append(
194 "Defaults, for any field you leave out: "
195 + json.dumps(defaults, ensure_ascii=False)
196 )
197 else:
198 lines.append("config: {}")
199 return "\n".join(lines)
202def feeds_prompt() -> str:
203 """The platform's own licence-checked publisher feeds, offered for RSS
204 tiles before any the model would have to remember — a feed it guessed
205 at, on a real domain, passed every check and then showed nothing.
206 Filtered by the deployment's allowlist, which is also stated."""
207 from app.services.system_resources.news import NEWS_SOURCES
209 from . import feeds
211 allowed = feeds.allowed_domains()
212 lines = [
213 f"- {source.publisher} — {source.covers} ({source.region}): {source.feed_url}"
214 for source in NEWS_SOURCES
215 if feeds.allowlisted_url(source.feed_url)
216 ]
217 out = []
218 if lines:
219 out.append(
220 "Publisher feeds known to work (prefer these for an RSS tile "
221 "when one fits):\n" + "\n".join(lines)
222 )
223 if allowed:
224 out.append(
225 "Only feeds on these domains are accepted: "
226 + vocab.listing(allowed, sep=", ")
227 + "."
228 )
229 return "\n\n".join(out)
232SYSTEM_PROMPT = f"""\
233You design dashboards for an AI operations platform. You are given a user's \
234description of what they want to watch and a catalogue of widget types, and \
235you propose a board.
237Design principles you must follow:
2391. Pair exact data with interpretation. Where you add a widget that is a \
240model's judgement, add a widget carrying the underlying facts next to it, so \
241the user can check one against the other. A board of only generated tiles is \
242a bad board.
2432. Prefer specific over generic. For a feed, one of the publisher feeds you \
244are given when one fits, else only a publisher's feed you are confident \
245exists; concrete tickers; named subjects on a comparison's axes.
2463. Every widget must earn its place. {IDEAL_WIDGETS[0]} to {IDEAL_WIDGETS[1]} \
247well-chosen tiles beat {MAX_WIDGETS} padded ones.
2484. Give each widget a short, human title — what it shows, not its type.
2495. Put each model-backed tile on the agent best placed to answer it, by its \
250handle from the agents you are given: one whose purpose and knowledge fit the \
251tile. Never write an id, and never a target object.
2526. A model-backed tile runs on a schedule with nobody to ask, so its prompt \
253must say everything the answer needs.
254"""
257def catalogue_types() -> tuple[str, ...]:
258 """Every registered widget type, as the catalogue serves them — what a
259 proposed widget may be. Fixed for the life of the process, so the schema
260 built from it is too."""
261 return vocab.values([spec["type"] for spec in catalogue()])
264class ProposedWidget(ModelOutput):
265 """One tile, as the model proposes it. Re-validated by its renderer
266 (``normalise_proposal``) before anything is kept."""
268 widget_type: Literal[catalogue_types()] = Field( # type: ignore[valid-type]
269 description="A type from the catalogue"
270 )
271 title: str = Field(description="What the tile shows, not its type")
272 # Text, not an object: each type's config has its own fields, which a
273 # strict schema cannot type, and every renderer validates its own.
274 config_json: str = Field(
275 default="{}",
276 description="The widget's config, as a JSON object of its type's config fields",
277 )
278 w: int | None = Field(default=None, description="Width in grid columns")
279 h: int | None = Field(default=None, description="Height in grid rows")
280 refresh_interval_seconds: int | None = Field(
281 default=None, description="Seconds between refreshes, for a type that refreshes"
282 )
283 # ``purpose``, not ``rationale`` (``RESERVED_FIELD_NAMES``); stored as
284 # the tile's rationale.
285 purpose: str = Field(default="", description="Why this tile is on the board")
288class ProposedBoard(ModelOutput):
289 """What the board designer is asked to fill — the shape every request's
290 own schema (``proposal_schema``) narrows."""
292 name: str = Field(
293 description=f"A short board name, at most {MAX_NAME_LENGTH} characters"
294 )
295 description: str = Field(
296 default="", description="One sentence on what this board is for"
297 )
298 icon: Literal[vocab.values(ICONS)] = appearance.DEFAULT_DASHBOARD_ICON # type: ignore[valid-type]
299 accent: Literal[vocab.values(ACCENTS)] = appearance.DEFAULT_ACCENT # type: ignore[valid-type]
300 # ``summary``, not ``reasoning`` (``RESERVED_FIELD_NAMES``); stored as
301 # the proposal's reasoning.
302 summary: str = Field(
303 default="", description="Two or three sentences on how you composed it"
304 )
305 widgets: list[OnErrorOmit[ProposedWidget]] = Field(
306 description=f"Between {MIN_WIDGETS} and {MAX_WIDGETS} widgets"
307 )
310def agent_handles(count: int) -> tuple[str, ...]:
311 """Positional handles for the agents a request offers: the schema then
312 depends only on how many there are, so a route's compiled grammar is
313 shared by every workspace with that many."""
314 return tuple(f"agent_{n}" for n in range(1, count + 1))
317@functools.lru_cache(maxsize=64)
318def proposal_schema(
319 widget_types: tuple[str, ...], agent_count: int
320) -> type[ProposedBoard]:
321 """``ProposedBoard`` for one request: its widgets only the types offered
322 (``offered_renderers``), and — when the workspace has agents — a choice
323 of which one runs each model-backed tile. Cached: the same offer is the
324 same class, and the same schema svc-ai has already compiled."""
325 widget_fields: dict[str, Any] = {
326 "widget_type": (
327 Literal[widget_types], # type: ignore[valid-type]
328 Field(description="A type from the catalogue"),
329 )
330 }
331 if agent_count:
332 widget_fields["agent"] = (
333 Optional[Literal[agent_handles(agent_count)]], # type: ignore[valid-type]
334 Field(
335 default=None,
336 description="The handle of the agent that runs a model-backed "
337 "tile; null for any other",
338 ),
339 )
340 widget = create_model(
341 "ProposedWidget",
342 __base__=ProposedWidget,
343 __module__=__name__,
344 **widget_fields,
345 )
346 return create_model(
347 "ProposedBoard",
348 __base__=ProposedBoard,
349 __module__=__name__,
350 widgets=(
351 list[OnErrorOmit[widget]], # type: ignore[valid-type]
352 Field(description=f"Between {MIN_WIDGETS} and {MAX_WIDGETS} widgets"),
353 ),
354 )
357def raw_proposal(board: ProposedBoard, warnings: list[str]) -> dict:
358 """``board`` in the shape ``normalise_proposal`` reads: each widget's
359 config read from its text, and one that is not a JSON object dropped
360 with a warning."""
361 widgets: list[dict] = []
362 for index, widget in enumerate(board.widgets, start=1):
363 config = structured_reply.json_object(widget.config_json)
364 if config is None:
365 warnings.append(
366 f"Dropped widget {index} ('{widget.title}'): its config was not "
367 "a JSON object."
368 )
369 continue
370 widgets.append(
371 {
372 "widget_type": widget.widget_type,
373 "title": widget.title,
374 "config": config,
375 "w": widget.w,
376 "h": widget.h,
377 "refresh_interval_seconds": widget.refresh_interval_seconds,
378 "rationale": widget.purpose,
379 "agent": getattr(widget, "agent", None),
380 }
381 )
382 return {
383 "name": board.name,
384 "description": board.description,
385 "icon": board.icon,
386 "accent": board.accent,
387 "reasoning": board.summary,
388 "widgets": widgets,
389 }
392def build_prompt(
393 description: str,
394 *,
395 offered: list[WidgetRenderer] | None = None,
396 agents: list[AgentChoice] | None = None,
397) -> str:
398 """The user-side prompt: their description, the agents a model-backed
399 tile can run on, the feeds known to work, and the catalogue."""
400 offered = offered if offered is not None else offered_renderers()
401 feeds = feeds_prompt()
402 return (
403 f"The user wants a dashboard for:\n\n{description}\n"
404 + (f"\n{agents_prompt(agents)}\n" if agents else "")
405 + (f"\n{feeds}\n" if feeds else "")
406 + f"\nAllowed icons: {vocab.listing(ICONS, sep=', ')}\n"
407 f"Allowed accents: {vocab.listing(ACCENTS, sep=', ')}\n"
408 f"\nWidget catalogue:\n{catalogue_prompt(offered)}\n"
409 f"\nReturn between {MIN_WIDGETS} and {MAX_WIDGETS} widgets."
410 )
413# ---------------------------------------------------------------------------
414# The agents a tile can run on
415# ---------------------------------------------------------------------------
418@dataclass(frozen=True)
419class AgentChoice:
420 """An agent a model-backed tile may run on, as the designer is shown it
421 — by a handle, never its id."""
423 handle: str
424 agent_id: str
425 name: str
426 #: Its purpose, and the skillsets and knowledge it holds, in one line.
427 summary: str
430def workspace_agents(
431 db: Session, user_id: UUID, workspace: Any = None
432) -> list[AgentChoice]:
433 """The agents a tile on a board made in ``workspace`` can run on: the
434 workspace's own, then the built-in ones — exactly what a tile's target
435 admits (``targets._reachable_by``), so a tile is never put on an agent
436 that would refuse it at its first refresh. An inherited agent is not
437 one: the board's owner is the project, not its organisation."""
438 from sqlalchemy import or_
440 from app.db.postgres.models import (
441 AgentRepository,
442 AgentSkillset,
443 KnowledgeRepository,
444 Skillset,
445 )
447 own = (
448 workspace.owns(Agent)
449 if workspace is not None
450 else Agent.owner_user_id == user_id
451 )
452 rows = (
453 db.query(Agent)
454 .filter(or_(own, Agent.is_system.is_(True)))
455 .order_by(Agent.is_system.asc(), Agent.created_at.asc())
456 .limit(MAX_AGENT_CHOICES)
457 .all()
458 )
459 if not rows:
460 return []
461 ids = [row.id for row in rows]
462 held: dict[Any, dict[str, list[str]]] = {
463 i: {"skills": [], "knows": []} for i in ids
464 }
465 for agent_id, name in (
466 db.query(AgentSkillset.agent_id, Skillset.name)
467 .join(Skillset, Skillset.id == AgentSkillset.skillset_id)
468 .filter(AgentSkillset.agent_id.in_(ids))
469 .all()
470 ):
471 held.get(agent_id, {}).setdefault("skills", []).append(str(name))
472 for agent_id, name in (
473 db.query(AgentRepository.agent_id, KnowledgeRepository.name)
474 .join(
475 KnowledgeRepository, KnowledgeRepository.id == AgentRepository.repository_id
476 )
477 .filter(AgentRepository.agent_id.in_(ids))
478 .all()
479 ):
480 held.get(agent_id, {}).setdefault("knows", []).append(str(name))
482 choices = []
483 for handle, row in zip(agent_handles(len(rows)), rows):
484 parts = [_clean_str(row.description, "", 200) or "No description."]
485 skills = held[row.id]["skills"][:3]
486 knows = held[row.id]["knows"][:3]
487 if skills:
488 parts.append(f"Skillsets: {vocab.listing(skills, sep=', ')}.")
489 if knows:
490 parts.append(f"Knowledge: {vocab.listing(knows, sep=', ')}.")
491 choices.append(
492 AgentChoice(
493 handle=handle,
494 agent_id=str(row.id),
495 name=_clean_str(row.name, "Agent", 100),
496 summary=" ".join(parts),
497 )
498 )
499 return choices
502def agents_prompt(choices: list[AgentChoice]) -> str:
503 """The agents, as data the designer picks from by handle."""
504 lines = [
505 f"- {choice.handle}: {choice.name} — {choice.summary}" for choice in choices
506 ]
507 return (
508 "Agents a model-backed tile can run on (each has the platform's general "
509 "tools, web search among them; set a tile's `agent` to the handle of "
510 "the best fit):\n" + "\n".join(lines)
511 )
514# ---------------------------------------------------------------------------
515# Target resolution
516# ---------------------------------------------------------------------------
519def resolve_target(
520 db: Session, user_id: UUID, model_id: Optional[str], *, workspace: Any = None
521) -> Optional[dict]:
522 """What model-backed widgets on this board should run on.
524 Resolved from the resources of the workspace the board is made in
525 (``workspace``; the user's Personal without one), never from the
526 model's output: an agent brings its tools, knowledge and rules, and
527 falls back to the model that did the generating. An organisation's board
528 never borrows a member's personal agent.
529 """
530 agent = (
531 db.query(Agent)
532 .filter(
533 workspace.owns(Agent)
534 if workspace is not None
535 else Agent.owner_user_id == user_id
536 )
537 .order_by(Agent.created_at)
538 .first()
539 )
540 if agent is not None:
541 return {"type": "agent", "agent_id": str(agent.id)}
542 if model_id:
543 return {"type": "model", "model_id": str(model_id)}
544 return None
547# ---------------------------------------------------------------------------
548# Layout
549# ---------------------------------------------------------------------------
552def pack_layout(widgets: list[dict], columns: int = GRID_COLUMNS) -> list[dict]:
553 """Place widgets left-to-right, wrapping into rows.
555 Recomputed rather than taken from the model: models routinely emit
556 overlapping or off-grid coordinates, and the result is a board the user
557 has to tidy before it is usable.
558 """
559 x = y = row_height = 0
560 packed = []
562 for widget in widgets:
563 w = max(1, min(columns, int(widget.get("w") or 4)))
564 h = max(2, int(widget.get("h") or 4))
566 if x + w > columns:
567 x = 0
568 y += row_height
569 row_height = 0
571 packed.append({**widget, "x": x, "y": y, "w": w, "h": h})
572 x += w
573 row_height = max(row_height, h)
575 return packed
578# ---------------------------------------------------------------------------
579# Proposal assembly
580# ---------------------------------------------------------------------------
583def _clean_str(value: Any, fallback: str = "", limit: int = 500) -> str:
584 return (str(value).strip() if isinstance(value, str) else fallback)[:limit]
587def _one_of(value: Any, allowed: list[str], fallback: str) -> str:
588 return value if isinstance(value, str) and value in allowed else fallback
591def normalise_proposal(
592 raw: dict,
593 *,
594 target: Optional[dict],
595 warnings: list[str],
596 agents: Mapping[str, AgentChoice] | None = None,
597 target_name: str | None = None,
598 problems: list[str] | None = None,
599) -> dict:
600 """Turn a model's reply into a board proposal the API would accept.
602 Every widget is re-validated through its own renderer. A tile that does
603 not survive is dropped and reported — a board missing one tile is far
604 better than a generation that fails outright — and, when ``problems`` is
605 given, what was wrong with it is listed there, one line a tile, for the
606 correction round to send back.
608 A model-backed tile runs on the agent whose handle it named
609 (``agents``), else on ``target`` (called ``target_name``).
610 """
611 proposed = raw.get("widgets")
612 if not isinstance(proposed, list) or not proposed:
613 raise DashboardGenerationError(
614 "The model did not propose any widgets for this board."
615 )
616 agents = agents or {}
618 kept: list[dict] = []
619 for index, entry in enumerate(proposed[:MAX_WIDGETS]):
620 if not isinstance(entry, dict):
621 warnings.append(f"Dropped widget {index + 1}: not an object.")
622 continue
624 widget_type = entry.get("widget_type")
625 try:
626 renderer = get_renderer(widget_type)
627 except WidgetConfigError:
628 warnings.append(f"Dropped unknown widget type '{widget_type}'.")
629 continue
631 config = entry.get("config")
632 config = dict(config) if isinstance(config, dict) else {}
633 runs_on: str | None = None
635 # Model-backed widgets run on the workspace's own resources: the
636 # agent whose handle the model chose, never an id it wrote.
637 if renderer.data_kind == DashboardEnum.DataKind.generated:
638 chosen = agents.get(str(entry.get("agent") or ""))
639 tile_target = (
640 {"type": "agent", "agent_id": chosen.agent_id} if chosen else target
641 )
642 if tile_target is None:
643 warnings.append(
644 f"Dropped '{renderer.label}': no agent or model is "
645 "available to run it."
646 )
647 continue
648 config["target"] = tile_target
649 runs_on = chosen.name if chosen else target_name
651 # Ids of the user's own resources are never taken from the model:
652 # the tile falls back to its documented default (every agent, the
653 # newest source) and the user narrows it afterwards.
654 config, invented = renderer.without_model_ids(config)
655 if invented:
656 warnings.append(
657 f"'{renderer.label}' shows its default view — the model's "
658 "choice of agent or source was not kept. Narrow it after saving."
659 )
661 title = _clean_str(entry.get("title"), renderer.label, 255)
662 try:
663 config = validate_widget(widget_type, config)
664 except WidgetConfigError as exc:
665 warnings.append(f"Dropped '{renderer.label}': {exc}")
666 if problems is not None:
667 problems.append(
668 f"Widget {index + 1} ('{title}', {renderer.type}): {exc}"
669 )
670 continue
672 interval = entry.get("refresh_interval_seconds")
673 if not isinstance(interval, int) or interval < MIN_REFRESH_INTERVAL_SECONDS:
674 interval = renderer.default_refresh_interval_seconds
675 elif interval < renderer.min_refresh_interval_seconds:
676 # A vendor's quota or a model's cost sets a type's floor.
677 interval = renderer.min_refresh_interval_seconds
678 if not renderer.is_dynamic:
679 interval = None
681 size = renderer.default_size
682 kept.append(
683 {
684 "widget_type": str(widget_type),
685 "title": title,
686 "config": config,
687 "w": entry.get("w") or size["w"],
688 "h": entry.get("h") or size["h"],
689 "refresh_interval_seconds": interval,
690 "rationale": _clean_str(entry.get("rationale"), "", 280),
691 "data_kind": renderer.data_kind,
692 "runs_on": runs_on,
693 }
694 )
696 if not kept:
697 raise DashboardGenerationError(
698 "None of the proposed widgets could be configured. "
699 + (" ".join(warnings[:3]) if warnings else "")
700 )
702 widgets = pack_layout(kept)
703 for position, widget in enumerate(widgets):
704 widget["position"] = position
706 # A board of pure inference is exactly what the prompt forbids; say so
707 # rather than letting it through silently.
708 if all(w["data_kind"] == DashboardEnum.DataKind.generated for w in widgets):
709 warnings.append(
710 "Every tile on this board is AI-generated. Consider adding a feed "
711 "or metric widget so there is something factual to check it against."
712 )
714 return {
715 "name": _clean_str(raw.get("name"), "New dashboard", MAX_NAME_LENGTH)
716 or "New dashboard",
717 "description": _clean_str(raw.get("description"), "", 500),
718 "icon": _one_of(raw.get("icon"), ICONS, appearance.DEFAULT_DASHBOARD_ICON),
719 "accent": _one_of(raw.get("accent"), ACCENTS, appearance.DEFAULT_ACCENT),
720 "reasoning": _clean_str(raw.get("reasoning"), "", 1000),
721 "widgets": widgets,
722 "warnings": warnings,
723 }
726def _raise_call_failure(result: Any) -> None:
727 """Raise what a failed call to the designer means for the person.
729 A budget's stop is re-raised as itself, so ``generation.metered`` ends
730 the run as the 403 a used-up budget is; a refusal is a 502 with the
731 refusal's own message (written to be shown); anything else a 502 that
732 says the service could not be reached — never the exception's text,
733 which carried svc-ai's response body. All of these used to be a 422
734 telling the person to change their description.
735 """
736 if not result.failed_call:
737 return
738 from app.services import ai_client
740 last = result.last
741 raised = getattr(last, "raised", None)
742 if isinstance(raised, ai_client.SpendLimitReached):
743 raise raised
744 if isinstance(raised, ai_client.ModelRefusedError):
745 raise DashboardGenerationUnavailable(raised.user_message)
746 if getattr(last, "blocked", False) and last.error:
747 raise DashboardGenerationUnavailable(last.error)
748 if raised is not None:
749 logger.warning("Dashboard generation call failed: %s", type(raised).__name__)
750 raise DashboardGenerationUnavailable(UNREACHABLE_MESSAGE)
753#: What a person is told when the designer's model could not be reached.
754UNREACHABLE_MESSAGE = "Could not reach the model service to generate the dashboard."
757def correction_prompt(problems: list[str]) -> str:
758 """The one message sent back when tiles of a board could not be used:
759 the validators' own words, one tile a line, and the whole board asked
760 for again. The model's configs are never repaired in code."""
761 listed = "\n".join(f"- {problem}" for problem in problems)
762 return (
763 "These widgets on your board could not be used:\n"
764 f"{listed}\n\n"
765 "Return the whole board again, with each of them fixed or replaced by "
766 "a widget that works, and the rest as they were."
767 )
770def generate_dashboard(
771 db: Session,
772 *,
773 description: str,
774 user_id: UUID,
775 provider: str,
776 model_name: str,
777 model_id: Optional[str] = None,
778 generation_id: Optional[UUID] = None,
779 workspace: Any = None,
780) -> dict:
781 """Ask a model to compose a board, then make it safe to create.
783 ``generation_id`` is the run the router opened for this invocation, put
784 on the trace so the call links to it from the activity feed.
785 ``workspace`` is where the board will be created.
787 Raises :class:`DashboardGenerationError` when the model's board was not
788 usable (a 422), :class:`DashboardGenerationUnavailable` when the model
789 could not be asked (a 502), and ``ai_client.SpendLimitReached`` when a
790 budget stopped it.
791 """
792 # Imported lazily to keep the agent stack out of module import.
793 from app.services.evaluation.context import EvaluationContext
794 from app.services.evaluation.targets import ModelTarget, invoke_structured
796 started = time.monotonic()
797 base_warnings: list[str] = []
798 choices = workspace_agents(db, user_id, workspace)
799 target = resolve_target(db, user_id, model_id, workspace=workspace)
800 if target is None and choices:
801 # A workspace with no agent of its own and no model to fall back on
802 # can still run a tile on a built-in agent.
803 target = {"type": "agent", "agent_id": choices[0].agent_id}
804 if target is None:
805 base_warnings.append(
806 "You have no agents yet, so this board was built from live "
807 "sources and metrics only. Create an agent to add automations."
808 )
809 target_name = (
810 next((c.name for c in choices if c.agent_id == target.get("agent_id")), None)
811 if target and target.get("agent_id")
812 else (model_name if target else None)
813 )
814 offered = offered_renderers(has_target=target is not None)
815 agents = choices if target is not None else []
816 schema = proposal_schema(vocab.values([r.type for r in offered]), len(agents))
817 by_handle = {choice.handle: choice for choice in agents}
819 generator = ModelTarget(
820 provider=provider,
821 model_name=model_name,
822 model_id=model_id,
823 # Board design benefits from a little variety, but not enough to
824 # wander off the requested schema.
825 temperature=0.4,
826 max_tokens=GENERATION_MAX_TOKENS,
827 )
828 generator.attribute(
829 # Ungoverned, like every other generative flow, so the trace has no
830 # owner to borrow — without the user it lands in nobody's feed.
831 purpose=GENERATION_TRACE_PURPOSE,
832 user_id=str(user_id),
833 reference={"generation_id": str(generation_id) if generation_id else ""},
834 )
836 def proposal_from(board: Any, problems: list[str]) -> dict | None:
837 warnings = list(base_warnings)
838 try:
839 return normalise_proposal(
840 raw_proposal(board, warnings),
841 target=target,
842 warnings=warnings,
843 agents=by_handle,
844 target_name=target_name,
845 problems=problems,
846 )
847 except DashboardGenerationError:
848 if not problems:
849 raise
850 return None
852 prompt = build_prompt(description, offered=offered, agents=agents)
853 result = invoke_structured(generator, prompt, SYSTEM_PROMPT, schema)
854 _raise_call_failure(result)
855 if result.value is None:
856 raise DashboardGenerationError(
857 f"The model's board did not match its schema: {result.failure}"
858 )
859 problems: list[str] = []
860 proposal = proposal_from(result.value, problems)
862 # One round with what was wrong, when a tile failed its validator and
863 # there is time left: the generative-skill pattern, and never a repair.
864 if problems and time.monotonic() - started < CORRECTION_CUTOFF_S:
865 history = [
866 {"role": "user", "content": prompt},
867 {"role": "assistant", "content": result.last.output},
868 ]
869 second = invoke_structured(
870 generator,
871 correction_prompt(problems),
872 SYSTEM_PROMPT,
873 schema,
874 context=EvaluationContext(history=history),
875 )
876 from app.services import ai_client
878 if second.failed_call and isinstance(
879 getattr(second.last, "raised", None), ai_client.SpendLimitReached
880 ):
881 raise second.last.raised
882 corrected = None
883 if second.value is not None:
884 try:
885 corrected = proposal_from(second.value, [])
886 except DashboardGenerationError:
887 corrected = None # the first board stands
888 if corrected is not None and (
889 proposal is None or len(corrected["widgets"]) >= len(proposal["widgets"])
890 ):
891 proposal = corrected
892 if proposal is None:
893 raise DashboardGenerationError(
894 "None of the proposed widgets could be configured. "
895 + " ".join(problems[:3])
896 )
898 proposal["model"] = {
899 "provider": provider,
900 "model_name": model_name,
901 "ai_model_id": model_id,
902 }
903 return proposal