Coverage for app / db / postgres / crud_schemas.py: 99%
203 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
1from uuid import UUID
2from datetime import date
3from decimal import Decimal
4from typing import Literal
6from pydantic import BaseModel, computed_field, field_validator
8from .enums import ModelEnum
10from app.agents.enums import AgentRole
11from app.util.time import UTCDateTime
14def _validate_interface_schema(v: list[dict] | None) -> list[dict] | None:
15 """Validate a worker input/output schema and return it normalised."""
16 if v is None:
17 return None
18 from app.agents.interfaces import normalise_schema, schema_to_dicts
20 try:
21 return schema_to_dicts(normalise_schema(v))
22 except Exception as exc: # noqa: BLE001 — surface as a 422
23 raise ValueError(f"invalid interface schema: {exc}") from exc
26def _provider_name(provider: object) -> str:
27 """A provider's name as the capability table keys it."""
28 name = getattr(provider, "name", provider)
29 return str(getattr(name, "value", name))
32class Schema:
33 # --------------------------------------------------------------------------
34 # Provider
35 # --------------------------------------------------------------------------
36 class Provider:
37 class Base(BaseModel):
38 name: ModelEnum.Provider
39 display_name: str
40 base_url: str | None = None
41 is_enabled: bool = True
42 is_default: bool = False
43 config: dict | None = None
45 class Create(Base):
46 pass
48 class Update(BaseModel):
49 display_name: str | None = None
50 base_url: str | None = None
51 is_enabled: bool | None = None
52 config: dict | None = None
53 is_default: bool | None = None
55 class Read(Base):
56 id: UUID
57 created_at: UTCDateTime
58 updated_at: UTCDateTime
60 class Config:
61 from_attributes = True
63 # --------------------------------------------------------------------------
64 # LLM Model
65 # --------------------------------------------------------------------------
66 class LLMModel:
67 class Base(BaseModel):
68 provider_id: UUID
69 model_name: str
70 display_name: str | None = None
71 description: str | None = None
72 is_chat: bool = True
73 is_embedding: bool = False
74 is_vision: bool = False
75 is_available: bool = True
76 is_default: bool = False
77 is_recommended: bool = False
78 context_window: int | None = None
79 max_output_tokens: int | None = None
80 input_cost_per_token: Decimal | None = None
81 output_cost_per_token: Decimal | None = None
82 cache_read_cost_per_token: Decimal | None = None
83 cache_write_cost_per_token: Decimal | None = None
84 cache_write_1h_cost_per_token: Decimal | None = None
85 long_context_threshold: int | None = None
86 long_context_input_multiplier: Decimal | None = None
87 long_context_output_multiplier: Decimal | None = None
88 data_region: ModelEnum.DataRegion | None = None
89 # Provider-independent reasoning tier, comparative speed band, and
90 # the reliable knowledge cutoff the provider publishes. All three
91 # are optional: a model registered by hand states what it knows.
92 effort: ModelEnum.Effort | None = None
93 latency: ModelEnum.Latency | None = None
94 knowledge_cutoff: date | None = None
95 config: dict | None = None
97 class Create(Base):
98 pass
100 class Update(BaseModel):
101 display_name: str | None = None
102 description: str | None = None
103 is_chat: bool | None = None
104 is_embedding: bool | None = None
105 is_vision: bool | None = None
106 is_available: bool | None = None
107 is_default: bool | None = None
108 is_recommended: bool | None = None
109 context_window: int | None = None
110 max_output_tokens: int | None = None
111 input_cost_per_token: Decimal | None = None
112 output_cost_per_token: Decimal | None = None
113 cache_read_cost_per_token: Decimal | None = None
114 cache_write_cost_per_token: Decimal | None = None
115 cache_write_1h_cost_per_token: Decimal | None = None
116 long_context_threshold: int | None = None
117 long_context_input_multiplier: Decimal | None = None
118 long_context_output_multiplier: Decimal | None = None
119 data_region: ModelEnum.DataRegion | None = None
120 effort: ModelEnum.Effort | None = None
121 latency: ModelEnum.Latency | None = None
122 knowledge_cutoff: date | None = None
123 config: dict | None = None
125 class Read(Base):
126 id: UUID
127 created_at: UTCDateTime
128 updated_at: UTCDateTime
129 #: Set when the model was taken out of the catalogue; served only
130 #: to a read that asked for archived models.
131 archived_at: UTCDateTime | None = None
133 # Seeded with the platform (providers/registry.py) rather than
134 # added by an operator. svc-core's platform benchmark scores every
135 # built-in chat model, and an id pattern is not a contract.
136 @computed_field # type: ignore[prop-decorator]
137 @property
138 def is_builtin(self) -> bool:
139 from app.db.postgres.providers.registry import BUILTIN_MODELS
141 return str(self.id) in BUILTIN_MODELS
143 class Config:
144 from_attributes = True
146 class ReadWithProvider(Read):
147 provider: "Schema.Provider.Read"
149 # Which request controls this model honours — read off the one
150 # table every call path consults (services/model_capabilities.py).
151 # A caller offering "temperature 0.7" on a model that rejects the
152 # parameter would otherwise show a setting that is silently
153 # dropped, and a temperature sweep over it would measure noise.
154 @computed_field # type: ignore[prop-decorator]
155 @property
156 def supports_temperature(self) -> bool:
157 from app.services.model_capabilities import capabilities_for
159 return capabilities_for(
160 _provider_name(self.provider), self.model_name
161 ).supports_temperature
163 @computed_field # type: ignore[prop-decorator]
164 @property
165 def supports_effort(self) -> bool:
166 from app.services.model_capabilities import capabilities_for
168 return capabilities_for(
169 _provider_name(self.provider), self.model_name
170 ).supports_effort
172 # Whose service runs this model on this deployment: the vendor's
173 # own API (``direct``) or Amazon Bedrock (``bedrock``,
174 # services/inference_routes.py). A model keeps its vendor as its
175 # identity on either, so the provider alone no longer says who
176 # receives a prompt; fe-core's Settings → Data names the
177 # processor from this.
178 @computed_field # type: ignore[prop-decorator]
179 @property
180 def inference_backend(self) -> Literal["direct", "bedrock"]:
181 from app.services import inference_routes
183 if _provider_name(self.provider) == inference_routes.BEDROCK:
184 return inference_routes.BEDROCK
185 return inference_routes.backend()
187 # Whether the model called here is one fixed version (a dated
188 # snapshot, a versioned Bedrock id), which cannot change under
189 # its name. svc-core's platform benchmark re-measures only models
190 # that can. A flag only: the id itself names a vendor.
191 @computed_field # type: ignore[prop-decorator]
192 @property
193 def version_pinned(self) -> bool:
194 from app.services import inference_routes
196 return inference_routes.version_pinned(
197 _provider_name(self.provider), self.model_name
198 )
200 # Who made the model: the provider, or for a model registered
201 # under ``bedrock`` the vendor its id names
202 # (``inference_routes.maker_of``). Every model Bedrock alone
203 # serves is registered under ``bedrock``, so svc-core compares
204 # this, not the provider, wherever "the same maker" matters
205 # (lighter model, native sibling, the platform benchmark).
206 @computed_field # type: ignore[prop-decorator]
207 @property
208 def maker(self) -> str:
209 from app.services import inference_routes
211 return inference_routes.maker_of(
212 _provider_name(self.provider), self.model_name
213 )
215 # Whether the model decodes a reply to a JSON schema natively on
216 # this deployment's route (``model_capabilities``): Bedrock's
217 # card, not the vendor's. svc-core reads it to choose a native
218 # sibling for an agent whose model cannot
219 # (``services/native_sibling.py`` in both services).
220 @computed_field # type: ignore[prop-decorator]
221 @property
222 def decodes_natively(self) -> bool:
223 from app.services.model_capabilities import capabilities_for
225 return capabilities_for(
226 _provider_name(self.provider), self.model_name
227 ).native_structured_output
229 class Config:
230 from_attributes = True
232 # --------------------------------------------------------------------------
233 # Worker Agent Definition
234 # --------------------------------------------------------------------------
235 class WorkerAgentDefinition:
236 class Base(BaseModel):
237 name: str
238 display_name: str
239 description: str
240 role: AgentRole
241 system_prompt: str
242 default_model_config: dict
243 tools_enabled: bool = True
244 mcp_servers: list[dict] = []
245 default_tools: list[dict] = []
246 input_schema: list[dict] = []
247 output_schema: list[dict] = []
248 tags: list[str] = []
249 is_builtin: bool = True
251 class Create(BaseModel):
252 """Simplified creation contract for custom workers.
254 A worker is: name + prompt (+ optional role, model override,
255 tools toggle, MCP servers). ``base`` clones an existing
256 definition first, so "customise a builtin" is one field plus
257 whatever you want to change.
258 """
260 name: str
261 display_name: str = ""
262 description: str = ""
263 role: AgentRole | None = None
264 system_prompt: str = ""
265 base: str | None = None # clone defaults from this definition
266 default_model_config: dict | None = None
267 tools_enabled: bool | None = None
268 mcp_servers: list[dict] | None = None
269 input_schema: list[dict] | None = None
270 output_schema: list[dict] | None = None
271 tags: list[str] = []
273 @field_validator("input_schema", "output_schema")
274 @classmethod
275 def _valid_schema(cls, v: list[dict] | None) -> list[dict] | None:
276 return _validate_interface_schema(v)
278 @field_validator("name")
279 @classmethod
280 def _valid_name(cls, v: str) -> str:
281 import re as _re
283 if not _re.fullmatch(r"[a-z][a-z0-9_]{2,254}", v):
284 raise ValueError(
285 "name must be snake_case: lowercase letters, digits and "
286 "underscores, starting with a letter (3-255 chars)"
287 )
288 return v
290 class Update(BaseModel):
291 display_name: str | None = None
292 description: str | None = None
293 role: AgentRole | None = None
294 system_prompt: str | None = None
295 default_model_config: dict | None = None
296 tools_enabled: bool | None = None
297 mcp_servers: list[dict] | None = None
298 default_tools: list[dict] | None = None
299 input_schema: list[dict] | None = None
300 output_schema: list[dict] | None = None
301 tags: list[str] | None = None
303 @field_validator("input_schema", "output_schema")
304 @classmethod
305 def _valid_schema(cls, v: list[dict] | None) -> list[dict] | None:
306 return _validate_interface_schema(v)
308 class Read(Base):
309 id: UUID
310 created_at: UTCDateTime
312 class Config:
313 from_attributes = True