"""Pydantic models for Smarter API Manifests."""
import abc
import datetime
import re
from contextlib import contextmanager
from contextvars import ContextVar
from typing import Iterator, List, Optional
from django.utils.text import slugify
from pydantic import (
BaseModel,
ConfigDict,
Field,
PrivateAttr,
field_validator,
model_validator,
)
from smarter.apps.account.models import (
User,
UserProfile,
get_resolved_user,
is_authenticated_user,
)
from smarter.common.api import SmarterApiVersions
from smarter.common.mixins import SmarterHelperMixin
from smarter.common.utils import to_snake_case
from smarter.lib import logging
from smarter.lib.annotation.validation import (
SmarterAnnotationError,
normalize_annotations,
)
from smarter.lib.django.validators import SmarterValidator
from smarter.lib.manifest.exceptions import SAMValidationError
logger = logging.getSmarterLogger(__name__)
_CLIENT_MANIFEST: ContextVar[bool] = ContextVar("smarter_client_manifest", default=False)
[docs]
@contextmanager
def client_manifest_validation() -> Iterator[None]:
"""
Validate, inside this context, a manifest that a client sent, e.g. to apply or validate it.
Brokers validate a client's manifest inside it. Models that they build from the database are
validated outside of it. Validators that check something outside of the manifest, such as that a
url is available, run only inside it (see :func:`is_client_manifest`), so that describing a
resource never depends on the network.
A context variable is used rather than Pydantic's validation context, because
:class:`SmarterBasePydanticModel` overrides ``__init__``, through which Pydantic validates nested
models without the validation context.
Example:
.. code-block:: python
with client_manifest_validation():
spec = SAMLLMClientSpec(**manifest["spec"])
"""
token = _CLIENT_MANIFEST.set(True)
try:
yield
finally:
_CLIENT_MANIFEST.reset(token)
[docs]
def is_client_manifest() -> bool:
"""
Whether the manifest that is being validated is one that a client sent.
:returns: True inside :func:`client_manifest_validation`.
"""
return _CLIENT_MANIFEST.get()
[docs]
class SmarterBasePydanticModel(BaseModel, SmarterHelperMixin):
"""Smarter API Base Pydantic Model."""
_user: Optional[User] = PrivateAttr(default=None)
_user_profile: Optional[UserProfile] = PrivateAttr(default=None)
model_config = ConfigDict(
from_attributes=True, # allow model to be initialized from class attributes
arbitrary_types_allowed=True, # allow Field attributed to be created from custom class types
frozen=True, # models are read-only
)
[docs]
def __init__(self, **data):
"""
Initialize the model, with an optional owner that is kept in private attributes.
:param data: The model's fields, and optionally ``user_profile`` or ``user``, which are not fields.
A user profile sets both :attr:`user_profile` and :attr:`user`. A user without a user profile
sets them only if the user is authenticated, from the user's cached user profile.
"""
user_profile = data.pop("user_profile", None)
user = data.pop("user", None)
super().__init__(**data)
if isinstance(user_profile, UserProfile):
self._user_profile = user_profile
self._user = user_profile.user
elif user is not None:
user = get_resolved_user(user)
if is_authenticated_user(user): # type: ignore
self._user_profile = UserProfile.get_cached_object(user=user) # type: ignore
if isinstance(self._user_profile, UserProfile):
self._user = self._user_profile.user
[docs]
@model_validator(mode="before")
def coerce_none_strings(cls, data):
"""
Replace the strings ``"None"`` and ``""`` with None in the raw input, before validation.
:param data: The raw input; only a dict is changed, in place.
:returns: The input.
"""
if isinstance(data, dict):
for k, v in data.items():
if v in ("None", ""):
data[k] = None
return data
@property
def user(self) -> Optional[User]:
"""
Get the user associated with this manifest, if any.
:returns: The user of the model's user profile, or None.
"""
return self._user
@property
def user_profile(self) -> Optional[UserProfile]:
"""
Get the user profile associated with this manifest, if any.
:returns: The user profile that the model was initialized with, or the authenticated user's, or None.
"""
return self._user_profile
[docs]
class AbstractSAMSpecBase(SmarterBasePydanticModel, abc.ABC):
"""Pydantic Spec base class.
Expected to be subclassed by specific manifest classes.
"""
[docs]
class SAMDependency(SmarterBasePydanticModel):
"""A resource that depends on the resource that a manifest describes."""
kind: str = Field(
...,
description="kind[String]: The SAM kind of the resource that depends on this resource, e.g. LLMClient. Read only.",
)
name: str = Field(
...,
description="name[String]: The name of the resource that depends on this resource. Read only.",
)
[docs]
class SAMDependencyTreeNode(SmarterBasePydanticModel):
"""
A resource in a dependency tree: the resource, and, recursively, every resource that it uses.
It is the opposite direction of :class:`SAMDependency`, which lists the resources that depend
on a resource. An LLMClient's tree has its Provider, its plugins, their Connections, and those
Connections' Secrets. See :meth:`smarter.lib.manifest.broker.AbstractBroker.dependency_tree`.
A resource that the user may not read keeps its kind and record locator, so that the tree still
shows that something is there, but not its name, owner or urls, or what it uses in turn.
Each readable resource has two urls: ``url``, its manifest page in the web console, where its
manifest can be edited, and ``detailUrl``, the api of its detail (its manifest, what it uses and
what uses it), which a resource's detail dialog in the web console shows when its card is chosen.
Example:
.. code-block:: json
{
"kind": "LLMClient",
"icon": "artificial-intelligence",
"name": "stackademy_sql",
"owner": "Ada Lovelace (ada)",
"recordLocator": "llmclient-rMTAwMDAxMwx",
"url": "/workbench/llm-clients/rMTAwMDAxMwx/manifest/",
"detailUrl": "/api/web/dashboard/resource/LLMClient/llmclient-rMTAwMDAxMwx/",
"readable": true,
"children": [
{
"kind": "SqlPlugin",
"icon": "file-sheet",
"name": "stackademy_sql",
"owner": "Ada Lovelace (ada)",
"recordLocator": "pluginmeta-rMTEx",
"url": "/llm-tools/plugins/rMTEx/",
"detailUrl": "/api/web/dashboard/resource/SqlPlugin/pluginmeta-rMTEx/",
"readable": true,
"children": []
}
]
}
"""
# a node always has every field, so its JSON Schema, from which the workbench's Architecture tab
# generates its TypeScript types, marks the fields that have defaults as required too.
model_config = ConfigDict(json_schema_serialization_defaults_required=True)
kind: str = Field(
...,
description="kind[String]: The SAM kind of the resource, e.g. LLMClient. Read only.",
)
icon: str = Field(
...,
description=(
"icon[String]: The kind's icon in the web console, a Keen Icons name without its ki- prefix, e.g. "
"lock-2 for a Secret. See sam_kind_icon(). Read only."
),
)
name: Optional[str] = Field(
default=None,
description=(
"name[String]: The name of the resource, or an Extension's slug, e.g. weather. None if the user may not "
"read it. Read only."
),
)
owner: Optional[str] = Field(
default=None,
description=(
"owner[String]: Who owns the resource: its owner's full name and username, e.g. Ada Lovelace (ada), "
"or an Extension's publisher. None if the user may not read it, or if it has no owner. Read only."
),
)
recordLocator: Optional[str] = Field(
default=None,
description=(
"recordLocator[String]: The resource's record locator, e.g. llmclient-rMTAwMDAxMwx, from which its "
"web console url is derived. None for a resource that has none, e.g. a User. Read only."
),
)
url: Optional[str] = Field(
default=None,
description=(
"url[String]: The path of the resource's manifest page in the web console, where its manifest can be "
"edited, derived from its record locator. None if it has no page, or if the user may not read it. "
"Read only."
),
)
detailUrl: Optional[str] = Field(
default=None,
description=(
"detailUrl[String]: The path of the api of the resource's detail in the web console: its manifest, "
"the resources that it uses and those that use it. See "
"smarter.apps.dashboard.resource_detail.resource_detail_url(). None if the user may not read it, "
"or on a public page. Read only."
),
)
readable: bool = Field(
default=True,
description="readable[Boolean]: Whether the user may read the resource. Read only.",
)
children: List["SAMDependencyTreeNode"] = Field(
default_factory=list,
description="children[List]: The resources that this resource uses, each with its own tree. Read only.",
)
[docs]
class AbstractSAMStatusBase(SmarterBasePydanticModel, abc.ABC):
"""Pydantic Status base class.
Expected to be subclassed by specific manifest classes.
"""
recordLocator: str = Field(
...,
description="recordLocator[String]: An optional identifier used to locate the resource record associated with this manifest. Read only.",
)
created: datetime.datetime = Field(
...,
description="The date in which this resource was created. Read only.",
)
modified: datetime.datetime = Field(
...,
description="The date in which this resource was most recently changed. Read only.",
)
dependencies: Optional[List[SAMDependency]] = Field(
default=None,
description=(
"dependencies[List]: The resources that depend on this resource, and that must be deleted, or stop "
"referring to it, before it can be deleted. Lists only the resources that you can read. Read only."
),
)
[docs]
class AbstractSAMBase(SmarterBasePydanticModel, abc.ABC):
"""
Abstract base class for all Smarter API Manifest (SAM) models.
This class serves as the foundational Pydantic model for representing Smarter API manifests.
It is intended to be subclassed by concrete manifest classes that define specific resource types
within the Smarter API ecosystem.
The ``AbstractSAMBase`` class provides a strongly-typed structure for manifest data, ensuring
that all manifests adhere to a consistent schema and validation logic. It includes built-in
validation for core manifest fields and supports structured access to manifest data.
Subclasses should implement or extend this class to define the specific data and behaviors
required for their respective manifest types. This design promotes code reuse, type safety,
and robust validation across all Smarter API manifests.
The class also provides methods for validating manifest data and for representing the manifest
as a string for debugging or logging purposes.
.. note::
Do not instantiate this class directly. Instead, create subclasses that define the
required fields and any additional validation or methods specific to your manifest type.
"""
apiVersion: str = Field(
...,
description="apiVersion[String]: Required. The API version of the AbstractSAMBase.",
)
kind: str = Field(
...,
description="kind[String]: Required. The kind of resource described by the manifest.",
)
metadata: AbstractSAMMetadataBase = Field(..., description="metadata[obj]: Required. The manifest metadata.")
spec: AbstractSAMSpecBase = Field(..., description="spec[obj]: Required. The manifest specification.")
status: Optional[AbstractSAMStatusBase] = Field(
default=None,
description="status[obj]: Optional. Read-only. The run-time state of the resource described by the manifest.",
)
[docs]
@field_validator("apiVersion")
def validate_apiVersion(cls, v) -> str:
"""
Validates the ``apiVersion`` field for a manifest.
This method ensures that the ``apiVersion`` attribute is present and matches one of the
supported API versions defined in ``SmarterApiVersions``. If the value is missing or invalid,
a ``SAMValidationError`` is raised.
:param v: The value of the ``apiVersion`` field to validate.
:type v: str
:raises smarter.lib.manifest.exceptions.SAMValidationError: If the value is missing or not a supported version.
:return: The validated ``apiVersion`` string.
"""
if v in [None, ""]:
raise SAMValidationError("Missing required manifest key: apiVersion")
if v not in SmarterApiVersions.all():
raise SAMValidationError(f"Invalid version. Must be one of {SmarterApiVersions.all()} but got {v}")
return v
def __str__(self) -> str:
return f"{self.formatted_class_name}(apiVersion={self.apiVersion}, kind={self.kind})"