Coverage for app / agents / interfaces.py: 94%
301 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"""
2Worker interfaces — typed input/output contracts for skill-graph nodes.
4A worker (``WorkerAgentDefinition`` / custom worker) may declare:
6 input_schema — the named, typed values it expects to receive. Skill
7 graph nodes bind these from state / upstream outputs
8 (``GraphNode.inputs``); the bound values are validated,
9 coerced and surfaced to the LLM as a structured block.
10 output_schema — the named, typed values it produces. When present the
11 worker returns a ``dict`` matching the schema instead of
12 free text, so downstream nodes and conditional edges can
13 reference individual fields (``{node_id.field}``).
15Schema format (JSON-serialisable, stored on the definition row)::
17 [
18 {"name": "risk_level", "type": "enum", "values": ["low", "medium", "high"],
19 "description": "Overall risk", "required": true},
20 {"name": "score", "type": "number", "description": "0-1 confidence"},
21 {"name": "issues", "type": "array", "items": "string"},
22 {"name": "summary", "type": "string"}
23 ]
25The same format is validated in svc-core (``_FieldSpec`` in crud_schemas)
26so a definition is rejected at save time, never at execution time.
27"""
29from __future__ import annotations
31import re
32from enum import Enum
33from typing import Any, Literal
35from pydantic import (
36 BaseModel,
37 ConfigDict,
38 Field,
39 ValidationError,
40 create_model,
41 field_validator,
42 model_validator,
43)
45from app.util import safe_json
46from app.util.logger import get_logger
47from app.util.model_output import RESERVED_FIELD_NAMES, ModelOutput
49logger = get_logger(__name__)
51_NAME_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
54class FieldType(str, Enum):
55 STRING = "string"
56 NUMBER = "number"
57 INTEGER = "integer"
58 BOOLEAN = "boolean"
59 ENUM = "enum"
60 ARRAY = "array"
61 OBJECT = "object"
64class FieldSpec(BaseModel):
65 """One typed field of a worker input or output interface."""
67 name: str
68 type: FieldType = FieldType.STRING
69 description: str = ""
70 required: bool = True
71 default: Any = None
72 # enum only — the closed set of allowed string values
73 values: list[str] = Field(default_factory=list)
74 # array only — element type (scalar types only; defaults to string)
75 items: FieldType = FieldType.STRING
77 @field_validator("name")
78 @classmethod
79 def _valid_name(cls, v: str) -> str:
80 if not _NAME_RE.fullmatch(v):
81 raise ValueError(
82 f"field name {v!r} must be an identifier (letters, digits, underscore)"
83 )
84 return v
86 @field_validator("values")
87 @classmethod
88 def _dedupe(cls, v: list[str]) -> list[str]:
89 seen: list[str] = []
90 for item in v:
91 s = str(item)
92 if s not in seen:
93 seen.append(s)
94 return seen
96 @model_validator(mode="after")
97 def _shape(self) -> "FieldSpec":
98 if self.type == FieldType.ENUM and not self.values:
99 raise ValueError(f"enum field {self.name!r} requires non-empty 'values'")
100 if self.type == FieldType.ARRAY and self.items in (
101 FieldType.ARRAY,
102 FieldType.OBJECT,
103 FieldType.ENUM,
104 ):
105 raise ValueError(f"array field {self.name!r} items must be a scalar type")
106 return self
108 def python_type(self) -> Any:
109 """The annotation used when building a Pydantic model for this field."""
110 match self.type:
111 case FieldType.STRING:
112 return str
113 case FieldType.NUMBER:
114 return float
115 case FieldType.INTEGER:
116 return int
117 case FieldType.BOOLEAN:
118 return bool
119 case FieldType.ENUM:
120 if self.values:
121 return Literal[tuple(self.values)] # type: ignore[return-value]
122 return str
123 case FieldType.ARRAY:
124 inner = FieldSpec(name="item", type=self.items).python_type()
125 return list[inner] # type: ignore[valid-type]
126 case FieldType.OBJECT:
127 return dict[str, Any]
128 return Any
131class InterfaceValidationError(ValueError):
132 """Raised when bound values do not satisfy a worker's input_schema."""
135# ---------------------------------------------------------------------------
136# Schema helpers
137# ---------------------------------------------------------------------------
140def normalise_schema(raw: Any) -> list[FieldSpec]:
141 """Coerce a stored schema (list of dicts / FieldSpecs / None) to FieldSpecs.
143 Invalid entries raise ``ValueError`` so callers surface a clear message
144 rather than silently dropping fields.
145 """
146 if not raw:
147 return []
148 if isinstance(raw, dict):
149 # {"name": {...}} mapping form → list form
150 raw = [{"name": k, **(v or {})} for k, v in raw.items()]
151 specs: list[FieldSpec] = []
152 seen: set[str] = set()
153 for entry in raw:
154 spec = entry if isinstance(entry, FieldSpec) else FieldSpec(**entry)
155 if spec.name in seen:
156 raise ValueError(f"duplicate interface field {spec.name!r}")
157 seen.add(spec.name)
158 specs.append(spec)
159 return specs
162def schema_to_dicts(specs: list[FieldSpec]) -> list[dict[str, Any]]:
163 return [s.model_dump(mode="json") for s in specs]
166def schema_to_json_schema(specs: list[FieldSpec]) -> dict[str, Any]:
167 """A JSON-Schema object describing the fields — used in prompts and the UI."""
168 props: dict[str, Any] = {}
169 required: list[str] = []
170 for s in specs:
171 prop: dict[str, Any]
172 match s.type:
173 case FieldType.ENUM:
174 prop = {"type": "string", "enum": list(s.values)}
175 case FieldType.ARRAY:
176 prop = {
177 "type": "array",
178 "items": {"type": _json_type(s.items)},
179 }
180 case _:
181 prop = {"type": _json_type(s.type)}
182 if s.description:
183 prop["description"] = s.description
184 if s.default is not None:
185 prop["default"] = s.default
186 props[s.name] = prop
187 if s.required:
188 required.append(s.name)
189 schema: dict[str, Any] = {"type": "object", "properties": props}
190 if required:
191 schema["required"] = required
192 schema["additionalProperties"] = False
193 return schema
196def _json_type(t: FieldType) -> str:
197 return {
198 FieldType.STRING: "string",
199 FieldType.NUMBER: "number",
200 FieldType.INTEGER: "integer",
201 FieldType.BOOLEAN: "boolean",
202 FieldType.ENUM: "string",
203 FieldType.ARRAY: "array",
204 FieldType.OBJECT: "object",
205 }[t]
208# ---------------------------------------------------------------------------
209# Value coercion / validation
210# ---------------------------------------------------------------------------
212_TRUE = {"true", "1", "yes", "y", "on"}
213_FALSE = {"false", "0", "no", "n", "off", ""}
216def coerce_value(spec: FieldSpec, value: Any) -> Any:
217 """Coerce ``value`` to the field's declared type.
219 Lenient where an unambiguous conversion exists (``"3"`` → 3 for a number,
220 ``"true"`` → True, a JSON string for an object/array); raises
221 ``InterfaceValidationError`` otherwise.
222 """
223 if value is None:
224 return None
225 try:
226 match spec.type:
227 case FieldType.STRING:
228 if isinstance(value, (dict, list)):
229 return safe_json.dumps(value, ensure_ascii=False)
230 return str(value)
231 case FieldType.NUMBER:
232 if isinstance(value, bool):
233 raise ValueError("boolean is not a number")
234 return float(value)
235 case FieldType.INTEGER:
236 if isinstance(value, bool):
237 raise ValueError("boolean is not an integer")
238 if isinstance(value, float) and not value.is_integer():
239 raise ValueError(f"{value} is not an integer")
240 return int(float(value)) if isinstance(value, str) else int(value)
241 case FieldType.BOOLEAN:
242 if isinstance(value, bool):
243 return value
244 if isinstance(value, (int, float)):
245 return bool(value)
246 s = str(value).strip().lower()
247 if s in _TRUE:
248 return True
249 if s in _FALSE:
250 return False
251 raise ValueError(f"{value!r} is not a boolean")
252 case FieldType.ENUM:
253 s = str(value)
254 if spec.values and s not in spec.values:
255 # case-insensitive rescue
256 lowered = {v.lower(): v for v in spec.values}
257 if s.lower() in lowered:
258 return lowered[s.lower()]
259 raise ValueError(f"{s!r} not in {spec.values}")
260 return s
261 case FieldType.ARRAY:
262 if isinstance(value, str):
263 text = value.strip()
264 if text.startswith("["):
265 value = safe_json.loads_exact(text)
266 else:
267 value = [v.strip() for v in text.split(",") if v.strip()]
268 if not isinstance(value, list):
269 value = [value]
270 item_spec = FieldSpec(name="item", type=spec.items)
271 return [coerce_value(item_spec, v) for v in value]
272 case FieldType.OBJECT:
273 if isinstance(value, str):
274 value = safe_json.loads_exact(value)
275 if hasattr(value, "model_dump"):
276 value = value.model_dump()
277 if not isinstance(value, dict):
278 raise ValueError("expected an object")
279 return value
280 except (ValueError, TypeError) as exc:
281 raise InterfaceValidationError(
282 f"field {spec.name!r}: cannot coerce {value!r} to {spec.type.value} ({exc})"
283 ) from exc
284 return value
287def validate_inputs(
288 specs: list[FieldSpec], values: dict[str, Any]
289) -> tuple[dict[str, Any], list[str]]:
290 """Validate and coerce bound input values against an input_schema.
292 Returns ``(coerced_values, errors)``. Missing optional fields receive
293 their default; missing required fields and coercion failures are reported
294 in ``errors`` (the value is left out) so the caller can decide whether to
295 abort or continue with a degraded context. Unknown keys pass through
296 untouched — a node may bind extra context beyond the declared interface.
297 """
298 coerced: dict[str, Any] = {}
299 errors: list[str] = []
300 declared = {s.name for s in specs}
301 for spec in specs:
302 present = spec.name in values and values[spec.name] is not None
303 if not present:
304 if spec.default is not None:
305 coerced[spec.name] = spec.default
306 elif spec.required:
307 errors.append(f"missing required input {spec.name!r}")
308 continue
309 try:
310 coerced[spec.name] = coerce_value(spec, values[spec.name])
311 except InterfaceValidationError as exc:
312 errors.append(str(exc))
313 for key, value in values.items():
314 if key not in declared:
315 coerced[key] = value
316 return coerced, errors
319# ---------------------------------------------------------------------------
320# Structured output
321# ---------------------------------------------------------------------------
324#: What a field named for a model's reasoning is called on the wire
325#: (``RESERVED_FIELD_NAMES``: Claude 5.x can refuse — and bill for — a field
326#: asking it to write out its reasoning). The worker's output keeps the name
327#: its schema declares.
328_WIRE_NAMES: dict[str, str] = {
329 "reasoning": "explanation",
330 "rationale": "justification",
331 "thinking": "considerations",
332 "trace": "steps",
333 "chain_of_thought": "steps_taken",
334}
335assert set(_WIRE_NAMES) == RESERVED_FIELD_NAMES, "a reserved name has no wire name"
338class WorkerOutput(ModelOutput):
339 """Base of a worker's output model. Validates by the name its schema
340 declares — what a reply written to the OUTPUT CONTRACT uses — and by the
341 wire name of a field named for a model's reasoning, which a decoded reply
342 uses."""
344 model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
347def _wire_name(name: str, taken: set[str]) -> str | None:
348 wire = _WIRE_NAMES.get(name)
349 if wire is None:
350 return None
351 while wire in taken:
352 wire = f"{wire}_text"
353 taken.add(wire)
354 return wire
357def _object_text(value: Any) -> Any:
358 """An ``object`` field travels as JSON text: strict decoding cannot type a
359 free-form object. An object written in place is taken as its text."""
360 if isinstance(value, dict):
361 return safe_json.dumps(value, ensure_ascii=False)
362 if isinstance(value, str):
363 try:
364 parsed = safe_json.loads_exact(value)
365 except ValueError:
366 parsed = None
367 if not isinstance(parsed, dict):
368 # pydantic reports a ValueError as a validation error; a
369 # TypeError would escape it.
370 raise ValueError("not a JSON object") # noqa: TRY004
371 return value
374def build_output_model(
375 specs: list[FieldSpec], name: str = "WorkerOutput"
376) -> type[BaseModel]:
377 """The ``ModelOutput`` a worker's output_schema is filled to.
379 Every one decodes natively (``strict_schema``): an ``object`` field is a
380 JSON object written as text, read back by :func:`output_values`, and a
381 field named for a model's reasoning travels under another name
382 (``_WIRE_NAMES``). Read a validated instance with :func:`output_values`.
383 """
384 fields: dict[str, Any] = {}
385 validators: dict[str, Any] = {}
386 taken = {s.name for s in specs}
387 for s in specs:
388 is_object = s.type == FieldType.OBJECT
389 annotation = str if is_object else s.python_type()
390 description = s.description
391 if is_object:
392 description = f"{description} (a JSON object, written as text)".strip()
393 options: dict[str, Any] = {"description": description}
394 alias = _wire_name(s.name, taken)
395 if alias:
396 options["alias"] = alias
397 if s.required and s.default is None:
398 fields[s.name] = (annotation, Field(**options))
399 else:
400 default = (
401 safe_json.dumps(s.default)
402 if is_object and isinstance(s.default, dict)
403 else s.default
404 )
405 fields[s.name] = (
406 annotation | None, # type: ignore[operator]
407 Field(default=default, **options),
408 )
409 if is_object:
410 validators[f"_object_{s.name}"] = field_validator(s.name, mode="before")(
411 classmethod(lambda cls, value: _object_text(value))
412 )
413 safe = re.sub(r"[^A-Za-z0-9_]", "_", name) or "WorkerOutput"
414 return create_model( # type: ignore[call-overload]
415 safe, __base__=WorkerOutput, __validators__=validators, **fields
416 )
419def output_values(value: BaseModel, specs: list[FieldSpec]) -> dict[str, Any]:
420 """A validated output model as the worker's output: by its schema's
421 names, each ``object`` field read back from its text."""
422 data = value.model_dump()
423 for s in specs:
424 if s.type == FieldType.OBJECT and isinstance(data.get(s.name), str):
425 data[s.name] = safe_json.loads_exact(data[s.name])
426 return data
429def output_schema_instruction(specs: list[FieldSpec]) -> str:
430 """System-prompt block instructing the model to answer with schema JSON
431 — for a worker with tools, whose final answer is read from its text. A
432 worker without tools is held to the schema instead (``structured_call``)."""
433 if not specs:
434 return ""
435 lines = [
436 "OUTPUT CONTRACT",
437 "Your final answer MUST be a single JSON object and nothing else — no "
438 "prose before or after it, no Markdown fence. It must match this schema "
439 "exactly (field names are case-sensitive):",
440 safe_json.dumps(schema_to_json_schema(specs), indent=2),
441 "Field guide:",
442 ]
443 for s in specs:
444 detail = s.type.value
445 if s.type == FieldType.ENUM and s.values:
446 detail += " — one of: " + ", ".join(s.values)
447 elif s.type == FieldType.ARRAY:
448 detail += f" of {s.items.value}"
449 req = "required" if s.required else "optional"
450 desc = f" — {s.description}" if s.description else ""
451 lines.append(f" - {s.name} ({detail}, {req}){desc}")
452 lines.append(
453 "If you used tools, incorporate their results into the fields; put any "
454 "narrative into the string fields rather than outside the object."
455 )
456 return "\n".join(lines)
459#: A reply that is one fenced block and nothing else.
460_FENCED = re.compile(r"```(?:json)?\s*(.*?)\s*```", re.DOTALL)
463def _exact_candidates(text: str) -> list[Any]:
464 """What a worker's answer is read as: the whole text, or the one fenced
465 block it is. Never an object found inside prose — a reply cut off, or
466 an example in its working, is not the answer."""
467 stripped = text.strip()
468 texts = [stripped]
469 fenced = _FENCED.fullmatch(stripped)
470 if fenced:
471 texts.append(fenced.group(1))
472 candidates: list[Any] = []
473 for candidate in texts:
474 try:
475 candidates.append(safe_json.loads_exact(candidate))
476 except ValueError:
477 continue
478 return candidates
481def parse_structured_output(
482 text: Any, specs: list[FieldSpec]
483) -> tuple[dict[str, Any] | None, str]:
484 """Read a worker's answer — or an operation's result — as its
485 output_schema.
487 Returns ``(values, error)``: ``values`` is the validated dict (with
488 defaults applied) or ``None`` when the answer is not one; ``error``
489 carries the last validation message for diagnostics. Text is read
490 exactly (``_exact_candidates``); a model's answer that is not one is
491 repaired by the worker natively (``BaseAgent._structure_output``).
492 """
493 if not specs:
494 return None, "no output schema"
495 if isinstance(text, dict):
496 candidates: list[Any] = [text]
497 elif hasattr(text, "model_dump"):
498 candidates = [text.model_dump()]
499 else:
500 candidates = _exact_candidates(str(text))
501 model = build_output_model(specs)
502 last_error = "no JSON object found in output"
503 for data in candidates:
504 if not isinstance(data, dict):
505 last_error = "JSON is not an object"
506 continue
507 # Coerce leniently first (e.g. "0.8" → 0.8, "High" → "high") so a
508 # near-miss from the model still validates.
509 coerced: dict[str, Any] = {}
510 for s in specs:
511 if s.name in data and data[s.name] is not None:
512 try:
513 coerced[s.name] = coerce_value(s, data[s.name])
514 except InterfaceValidationError:
515 coerced[s.name] = data[s.name]
516 try:
517 parsed = model.model_validate(coerced)
518 except ValidationError as exc:
519 last_error = "; ".join(
520 f"{'.'.join(str(p) for p in e['loc'])}: {e['msg']}"
521 for e in exc.errors()
522 )
523 continue
524 return output_values(parsed, specs), ""
525 return None, last_error
528def default_output(specs: list[FieldSpec]) -> dict[str, Any]:
529 """Schema-shaped dict of defaults (None for fields without one)."""
530 return {s.name: s.default for s in specs}