The platform for continuously improving AI agents.
import json
from functools import cache
from jsonschema import Draft202012Validator, FormatChecker
from jsonschema.exceptions import SchemaError
from pydantic import ValidationError
from overbae.core.errors import InputValidationError
from overbae.services import experiment_artifacts, experiment_interfaces
from overbae.services.experiment_asset_contract import ComponentPorts, component_authoring_contract
from overbae.services.experiment_catalog import catalogue, resolved
from overbae.services.experiment_contract import Document
from overbae.services.experiment_settings import (
CONTROL_SETTINGS,
Comparison,
Condition,
Investigation,
Publication,
)
from overbae.services.research_contract import TOOLS
def allow_connected_inputs(schema, paths):
schema["required"] = [key for key in schema.get("required", []) if key not in paths]
for key, value in schema.get("properties", {}).items():
nested = [path.removeprefix(key + ".") for path in paths if path.startswith(key + ".")]
if nested:
allow_connected_inputs(value, nested)
for key in ("allOf", "anyOf", "oneOf"):
for branch in schema.get(key, []):
allow_connected_inputs(branch, paths)
for key in ("then", "else"):
if key in schema:
allow_connected_inputs(schema[key], paths)
@cache
def operation_schema(tool, name):
schema = TOOLS[tool].schema(operation=name)
selector = "name" if tool == "platform" else "operation"
schema["properties"][selector] = {"const": name}
if "describe" in schema["properties"]:
schema["properties"]["describe"] = {"const": False}
allow_connected_inputs(schema, experiment_interfaces.bound_arguments(tool, name))
return schema
@cache
def authoring_contract():
schemas = {
kind: contract.model_json_schema()
for kind, contract in {
**CONTROL_SETTINGS,
"condition": Condition,
"research": Investigation,
"compare": Comparison,
"publish": Publication,
}.items()
}
schemas["component"] = {
"type": "object",
"properties": {
"ports": ComponentPorts.model_json_schema(),
"asset": {"type": "string", "format": "uuid"},
"fingerprint": {"type": "string"},
},
"description": "Draft with named config.ports and no operation. Before execution publish a component asset, pin asset and fingerprint, and configure component.run; retained asset ports replace draft declarations.",
}
schemas["train"] = {
"type": "object",
"properties": {},
"description": "training.create starts a campaign: operation arguments.run holds the "
"start_finetune settings every run shares and arguments.trials the most runs. "
"base_model comes from config.model or a connected model output; the train and "
"development cells come from the connected inputs.",
}
return [
{
**component,
**(
{"authoring": component_authoring_contract()}
if component["kind"] == "component"
else {}
),
"operations": [
{
**operation,
"arguments_schema": operation_schema(operation["tool"], operation["operation"]),
"bound_arguments": experiment_interfaces.bound_arguments(
operation["tool"], operation["operation"]
),
"interface": experiment_interfaces.interface(
{
"kind": component["kind"],
"config": {
"outputs": {port["name"]: {} for port in component["outputs"]}
},
"operation": {
"tool": operation["tool"],
"arguments": {
"name"
if operation["tool"] == "platform"
else "operation": operation["operation"]
},
},
}
),
}
for operation in component["operations"]
],
"config_schema": {
**schemas.get(component["kind"], {"type": "object"}),
"properties": {
**schemas.get(component["kind"], {}).get("properties", {}),
**(
{
"model": {
"type": "object",
"description": "Select a catalogue model with model, or a retained candidate with asset and fingerprint. Connect the model port only for outputs produced by training or selection.",
"properties": {
name: {"type": "string"}
for name in (
"model",
"asset",
"fingerprint",
"name",
"instructions",
)
},
"oneOf": [
{"required": ["model"]},
{"required": ["asset", "fingerprint"]},
],
}
}
if any(port["name"] == "model" for port in component["inputs"])
else {}
),
},
},
}
for component in catalogue()
]
def references(value):
if isinstance(value, dict):
if set(value) == {"$parameter"}:
yield value["$parameter"]
else:
for key, item in value.items():
if key != "_definition" and not (key == "recipe" and "bindings" in value):
yield from references(item)
elif isinstance(value, list):
for item in value:
yield from references(item)
def substitute(value, parameters):
if isinstance(value, dict):
if set(value) == {"$parameter"}:
name = value["$parameter"]
if name not in parameters:
raise InputValidationError("Supply every referenced flow parameter")
return parameters[name]
return {
key: item
if key == "_definition" or key == "recipe" and "bindings" in value
else substitute(item, parameters)
for key, item in value.items()
}
if isinstance(value, list):
return [substitute(item, parameters) for item in value]
return value
def bind_parameters(definitions, values, *, deferred=()):
if values.keys() - definitions.keys():
raise InputValidationError("Only declared flow parameters can be supplied")
parameters = {}
for name, parameter in definitions.items():
if name in deferred and name not in values:
continue
value = values.get(name, parameter.default)
if value is None:
if parameter.required:
raise InputValidationError(f"Supply flow parameter {name}")
continue
schema = {"type": parameter.type}
if parameter.enum is not None:
schema["enum"] = parameter.enum
if not Draft202012Validator(schema).is_valid(value):
raise InputValidationError(f"Flow parameter {name} does not match its declared type")
parameters[name] = value
return parameters
def compile_document(document, values, *, deferred=()):
try:
parsed = Document.model_validate(document)
except ValidationError as exc:
raise InputValidationError("Save a valid flow before running it") from exc
parameters = bind_parameters(parsed.parameters, values, deferred=deferred)
definition = parsed.model_dump(mode="json")
definition["nodes"] = substitute(
definition["nodes"],
{**{name: {"$parameter": name} for name in deferred}, **parameters},
)
nodes = {node["id"]: node for node in definition["nodes"]}
problems = []
for node in definition["nodes"]:
try:
validate_node(node, definition["edges"], nodes)
except InputValidationError as exc:
problems.append(f"{node['id']}: {exc.detail}")
except ValidationError as exc:
details = "; ".join(
f"{'.'.join(map(str, item['loc']))}: {item['msg']}"
for item in exc.errors(include_input=False, include_url=False)[:6]
)
problems.append(f"{node['id']}: {details}")
if problems:
raise InputValidationError("Complete the flow configuration:\n" + "\n".join(problems))
experiment_interfaces.validate(definition, executable=True)
return json.loads(json.dumps(definition)), parameters
def validate_known(schema, value):
errors = [
error
for error in Draft202012Validator(schema, format_checker=FormatChecker()).iter_errors(value)
if not list(references(error.instance))
or error.validator == "required"
and not (isinstance(error.instance, dict) and set(error.instance) == {"$parameter"})
]
if errors:
raise InputValidationError(
"; ".join(f"{'.'.join(map(str, error.path))}: {error.message}" for error in errors[:6])
)
def validate_config(contract, value):
validate_known(contract.model_json_schema(), value)
return contract.model_validate(value) if not list(references(value)) else None
def validate_node(node, edges, nodes):
if node["kind"] in {"component", "suite"} and not node["config"].get("asset"):
raise InputValidationError("Pin a published asset before executing this draft")
component = resolved(node)
incoming = {edge["input"] for edge in edges if edge["target"] == node["id"]}
if isinstance(node["config"].get("model"), dict):
if "model" not in component.inputs:
raise InputValidationError("This node does not consume a model")
selection = node["config"]["model"]
if bool(selection.get("model")) == bool(selection.get("asset")):
raise InputValidationError("Select one catalogue model or one retained candidate")
if selection.get("asset") and not selection.get("fingerprint"):
raise InputValidationError("Pin the retained candidate fingerprint")
incoming.add("model")
missing = set(component.required) - incoming
if missing:
raise InputValidationError(f"Connect {node['title']}: {', '.join(sorted(missing))}")
if operation := node.get("operation"):
args = operation["arguments"]
name = args.get("name") if operation["tool"] == "platform" else args.get("operation")
if (
operation["tool"] == "training"
and name == "create"
and not {"data", "model"} <= incoming
):
raise InputValidationError("Connect training data and a model before training")
validate_known(operation_schema(operation["tool"], name), args)
if node["kind"] == "condition":
validate_config(Condition, node["config"])
if node["kind"] == "research":
validate_config(Investigation, node["config"])
if node["kind"] == "publish":
publication = validate_config(Publication, node["config"])
for check in publication.checks if publication else []:
if bool(check.messages) == bool(check.decisions):
raise InputValidationError(
"Each deployment check needs either messages or decisions"
)
try:
Draft202012Validator.check_schema(check.response_schema)
except SchemaError as exc:
raise InputValidationError("Supply a valid deployment response schema") from exc
if node["kind"] in CONTROL_SETTINGS:
validate_config(CONTROL_SETTINGS[node["kind"]], node["config"])
if node["kind"] == "compare" and not node.get("operation"):
validate_config(Comparison, node["config"])
elif component.operations and not node.get("operation"):
raise InputValidationError(f"Configure {node['title']} before running this flow")
if node["kind"] == "model" and not (node["config"].get("model") or node["config"].get("asset")):
raise InputValidationError("Select a model for every model input")
if (
node.get("operation", {})
and node["operation"]["tool"] == "workspace"
and not list(references(node["config"].get("outputs", {})))
):
exports = experiment_artifacts.validate_exports(node)
if exports.keys() - component.outputs.keys():
raise InputValidationError(
"Declare output files only for this component’s output ports"
)