Smarter Broker Model

Smarter API Manifest Abstract Broker class.

class smarter.lib.manifest.broker.abstract_broker_class.AbstractBroker(request, *args, name=None, kind=None, loader=None, api_version='smarter.sh/v1', manifest=None, file_path=None, url=None, **kwargs)[source]

Bases: ABC, SmarterRequestMixin, Generic[ModelT, MetaModelT]

Abstract base class for the Smarter Broker Model.

This class defines the core broker service pattern for the Smarter API, and is the foundation for all concrete Broker implementations. Brokers are responsible for processing Smarter YAML manifests, initializing Pydantic models, and brokering the correct implementation class for CLI and API operations.

Responsibilities:

  • Load, partially validate, and parse a Smarter API YAML manifest, sufficient to initialize a Pydantic model.

  • Implement the broker service pattern for the underlying object.

  • Initialize the corresponding Pydantic models.

  • Instantiate the underlying Python object for the resource.

The broker pattern provides generic services for manifest operations, including: get, post, put, delete, and patch.

Subclasses must implement the abstract methods to provide resource-specific logic for CLI and API commands such as apply, describe, delete, deploy, example_manifest, get, logs, and undeploy.

A broker names its Django ORM models as type arguments, the model of its resource and the model that holds the resource’s name and owner, e.g. AbstractBroker[Secret, Secret], or AbstractBroker[PluginDataBase, PluginMeta] for a plugin.

abstract property ORMMetaModelClass: Type[MetaModelT]

Return the Django ORM meta model class for the broker.

Returns:

The Django ORM meta model class definition for the broker.

abstract property ORMModelClass: Type[ModelT]

Return the Django ORM model class for the broker.

Returns:

The Django ORM model class definition for the broker.

property SAMModelClass: Type[AbstractSAMBase]

Return the SAM (Smarter Api Manifest) model class for the broker.

Returns:

The Pydantic model class definition for the broker.

abstract property SerializerClass: Type[ModelSerializer]

Return the serializer class for the broker.

Returns:

The serializer class definition for the broker.

__init__(request, *args, name=None, kind=None, loader=None, api_version='smarter.sh/v1', manifest=None, file_path=None, url=None, **kwargs)[source]

Initialize the broker from a manifest, a loader, a manifest file, or the Django ORM.

A manifest takes precedence over a loader, and a loader over a file path. With none of them, the broker is initialized from the ORM instance named name and owned by the user profile, if there is one.

Parameters:
  • request (HttpRequest | None) – The request, or None. It may also be passed positionally in args.

  • args – Positional arguments, among which the request, user, account, user profile, manifest and loader are found by their types.

  • name (str | None) – The resource’s name.

  • kind (str | None) – The resource’s SAM kind, e.g. Guardrail.

  • loader (SAMLoader | None) – A loader that has read the manifest.

  • api_version (str) – The manifest’s api version.

  • manifest (dict[str, Any] | AbstractSAMBase | None) – The manifest, as a Pydantic model or a dict.

  • file_path (str | None) – The path of a manifest file, read when no loader is passed.

  • url (str | None) – Accepted, for the same parameters as SAMLoader, but not used.

  • kwargs – user, account and user_profile, and the rest, which are passed on to SmarterRequestMixin.

Raises:
  • SmarterValueError – If the kind, name or manifest is invalid.

  • SAMBrokerError – If the loader’s kind is not the broker’s kind.

property abstract_broker_logger_cache_invalidation_prefix: str[source]

Return the logger prefix for the AbstractBroker cache invalidation.

It is built once per broker: every log message starts with it.

Returns:

The logger prefix for the AbstractBroker.

property abstract_broker_logger_prefix: str[source]

Return the logger prefix for the AbstractBroker.

It is built once per broker: every log message starts with it.

Returns:

The logger prefix for the AbstractBroker.

property abstract_broker_ready_state: str

Return a string representation of the AbstractBroker’s ready state.

Returns:

“READY” if the AbstractBroker is ready, otherwise “NOT_READY”.

property api_version: str

The API version of the manifest.

Returns:

The API version of the manifest.

abstractmethod apply(request, *args, **kwargs)[source]

Apply a manifest, which works like an upsert operation.

This abstract method should be implemented by subclasses to provide the logic for applying a manifest to create or update a resource.

Designed around the Kubernetes kubectl apply command.

This method processes a Smarter YAML manifest and either creates or updates the corresponding resource, depending on whether it already exists.

Example manifest metadata:

metadata:
    description: new description
    name: test71d12b8212b628df
    version: 1.0.0
Parameters:
  • request (HttpRequest) – The HTTP request object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse | None

Returns:

A SmarterJournaledJsonResponse if implemented, otherwise None.

static assign_changed_fields(instance, data)[source]

Set the fields of an ORM instance whose values differ from the manifest’s.

A broker’s apply() saves the instance only when this returns a field. See smarter.lib.django.models.utils.assign_changed_fields().

Parameters:
  • instance (Model) – The ORM instance.

  • data (dict[str, Any]) – The fields from the manifest, from manifest_to_django_orm().

Return type:

list[str]

Returns:

The names of the fields that were set, because their values changed.

cache_invalidations()[source]

Handle broker specific cache invalidation logic.

Return type:

None

clean_cli_param(param, param_name='unknown', url=None)[source]

Clean a cli parameter: strip a string’s whitespace, and turn an empty string into None.

A parameter that is not a string is logged as a warning. A list becomes its first element, and any other value is returned unchanged.

Parameters:
  • param (Any) – The param to clean.

  • param_name (str) – The name of the param, for logging purposes.

  • url (str | None) – The url from which the param was extracted, for logging purposes.

Return type:

str | None

Returns:

The cleaned param.

command_result()[source]

The data of the response to a command that changed the resource, e.g. apply.

It identifies the resource, and nothing else. Use to_json() for logging only: it includes the broker’s request, authentication and cache key, which a client must not see.

Return type:

dict[str, Any]

Returns:

The resource’s api version, kind and name.

Raises:

SAMBrokerInternalError – If the broker has no kind.

property created: bool

Return True if the broker was created successfully.

Returns:

True if the broker was created successfully.

abstractmethod delete(request, *args, **kwargs)[source]

Delete a resource.

Parameters:
  • request (HttpRequest) – The HTTP request object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the result of the delete operation.

abstractmethod dependencies()[source]

Return brokers for the resources that depend on this resource.

A resource depends on this resource when it refers to it, so that deleting this resource would break it, or would delete it too. For example, an LLMClient that lists a Guardrail in its spec.guardrails depends on that Guardrail. The dependents are queried from the Django ORM, and may belong to other users. verify_no_dependencies() uses them to refuse to delete a resource that is still in use.

A broker usually implements it as return self.dependency_brokers_for(<its ORM instance>), so that it agrees with dependents(), which says which resources those are.

Example:

broker = SAMGuardrailBroker(request=request, name="stupid_input", kind="Guardrail")
for dependency in broker.dependencies():
    print(dependency.kind, dependency.name)
# LLMClient smarter_example
Return type:

List[AbstractBroker | SAMDependencyReference]

Returns:

A broker for each resource that depends on this resource, or an empty list. See dependency_broker() for the SAMDependencyReference it returns in place of a broker that fails to initialize.

dependencies_status()[source]

Return the status.dependencies of a manifest: the kind and name of each visible dependency.

Example:

broker.dependencies_status()
# [{"kind": "LLMClient", "name": "smarter_example"}]
Return type:

List[dict[str, Any]]

Returns:

A dict with the kind and name of each dependency that the authenticated user may read.

dependency_broker(kind, instance, name=None, user_profile=None)[source]

Return a broker for a resource that depends on this resource.

The broker is initialized from the ORM, for the resource’s own owner, which may be another user than this broker’s. A broker can fail to initialize when the resource’s stored data no longer validates, e.g. a plugin whose model was removed from the list of valid models. One broken dependent must not break the resource it depends on, so this returns a SAMDependencyReference with the resource’s kind, name and owner instead.

Parameters:
  • kind (str) – The SAM kind of the resource, e.g. SAMKinds.LLM_CLIENT.value.

  • instance (Model) – The resource’s Django ORM instance. It has a user_profile.

  • name (str | None) – The resource’s manifest name. Defaults to instance.name.

  • user_profile (UserProfile | None) – The resource’s owner. Defaults to instance.user_profile.

Return type:

AbstractBroker | SAMDependencyReference

Returns:

A broker for the resource, or a reference to it if its broker fails to initialize.

Raises:

SAMBrokerInternalError – If no broker is registered for kind.

dependency_brokers(kind, instances)[source]

Return a broker for each resource that depends on this resource.

Parameters:
  • kind (str | None) – The SAM kind of the resources, e.g. SAMKinds.LLM_CLIENT.value, or None if each resource has its own kind in its kind field, as a plugin’s PluginMeta does.

  • instances (Iterable[Model]) – The resources’ Django ORM instances.

Return type:

List[AbstractBroker | SAMDependencyReference]

Returns:

A broker, or a reference, for each resource, without duplicates. See dependency_broker().

dependency_brokers_for(instance)[source]

Return a broker for each resource that depends on a resource, as dependents() lists them.

Parameters:

instance (TypeVar(MetaModelT, bound= Model) | None) – The resource’s Django ORM instance, or None if it does not exist.

Return type:

List[AbstractBroker | SAMDependencyReference]

Returns:

A broker, or a reference, for each resource that depends on it, or an empty list if it does not exist. See dependency_brokers().

dependency_references()[source]

Return the kind, name and owner of each resource that depends on this resource, without building brokers.

It is dependencies(), with a SAMDependencyReference in place of each broker, for the callers that need only those, such as describe’s status.dependencies and the check before a delete. Building a broker per dependent costs its own lookups and logging, and a built-in resource can have many dependents. The dependencies are queried afresh, and the brokers that dependencies() memoized, if any, are kept for it.

Return type:

List[AbstractBroker | SAMDependencyReference]

Returns:

A reference for each resource that depends on this resource. A broker that builds its dependencies without dependency_brokers() returns brokers here too.

dependency_tree()[source]

Return the tree of every resource that this resource uses, recursively, by record locator.

The root is this resource. Its children are the resources that it uses, as references() lists them, and theirs are the resources that they use, down to the resources that use no others, such as Secrets. A resource that two others use is in the tree twice, once under each. A resource that is already one of its own ancestors is a leaf, so that a cycle ends.

Each node has the kind’s icon, from smarter.apps.api.v1.manifests.enum.sam_kind_icon(), the resource’s owner, its record locator, and the path of its manifest page in the web console, derived from the record locator by smarter.lib.manifest.record_locator.console_url(), and the url of its detail, by smarter.apps.dashboard.resource_detail.resource_detail_url(), so that a web console page can draw the tree with a card for each resource. A resource that the authenticated user may not read has only its kind and record locator, and no children.

Example:

broker = SAMLLMClientBroker(request=request, name="stackademy_sql", kind="LLMClient")
tree = broker.dependency_tree()
tree.model_dump(mode="json")
# {"kind": "LLMClient", "icon": "artificial-intelligence", "name": "stackademy_sql",
#  "owner": "Ada Lovelace (ada)",
#  "recordLocator": "llmclient-rMTAwMDAxMwx",
#  "url": "/workbench/llm-clients/rMTAwMDAxMwx/manifest/", "readable": True,
#  "children": [{"kind": "SqlPlugin", "name": "stackademy_sql", ...,
#                "children": [{"kind": "SqlConnection", ..., "children": [{"kind": "Secret", ...}]}]}]}
Return type:

SAMDependencyTreeNode | None

Returns:

The tree, or None if the resource does not exist.

Raises:

SAMBrokerErrorNotImplemented – If a broker in the tree does not implement references().

property dependency_tree_instance: Model | None

The Django ORM instance that is the root of dependency_tree(), and that references() takes.

It is orm_instance, unless a broker’s ORM instance is not the row that the other kinds refer to, e.g. a plugin’s, whose rows are referred to by their PluginMeta.

Returns:

The instance, or None if the resource does not exist.

static dependency_tree_name(instance)[source]

Return a resource’s name in dependency_tree().

It is the resource’s name. An Extension, which has no name, has its slug, e.g. weather, which is how its manifest and the extension registry identify it.

Parameters:

instance (Model) – The resource’s Django ORM instance.

Return type:

str | None

Returns:

The name, or None if the resource has neither a name nor a slug.

dependency_tree_node(kind, instance, ancestors, recursive=True, readable=None)[source]

Return one resource’s node of dependency_tree(), with the nodes of the resources that it uses.

Parameters:
  • kind (str) – The SAM kind of the resource, e.g. SAMKinds.LLM_CLIENT.value.

  • instance (Model) – The resource’s Django ORM instance.

  • ancestors (frozenset[str | None]) – The record locators of the resource’s ancestors in the tree.

  • recursive (bool) – Whether the node has the nodes of the resources that it uses. A node without them describes the resource alone, e.g. one of the resources that depend on another, in a list.

  • readable (bool | None) – Whether the authenticated user may read the resource, when the caller already knows, e.g. for a whole group of siblings at once. None checks it with dependency_tree_readable().

Return type:

SAMDependencyTreeNode

Returns:

The node.

static dependency_tree_owner(instance)[source]

Return who owns a resource of dependency_tree(), as the web console names a person.

It is the full name and username of the user of the resource’s user_profile, e.g. Ada Lovelace (ada), or the username alone if the user has no name. An Extension, which no user owns, has its publisher.

Parameters:

instance (Model) – The resource’s Django ORM instance.

Return type:

str | None

Returns:

The owner, or None if the resource has none, e.g. a Budget.

dependency_tree_readable(instance)[source]

Return True if the authenticated user may read a resource of dependency_tree().

A resource whose manager has no read permissions, e.g. an Extension, which every account that has it enabled may use, is readable.

Parameters:

instance (Model) – The resource’s Django ORM instance.

Return type:

bool

Returns:

Whether the user may read it.

dependency_tree_readable_pks(rows)[source]

Return the primary keys of the rows that the authenticated user may read, with one query.

Parameters:

rows (List[Model]) – Sibling rows of dependency_tree().

Return type:

set | None

Returns:

The readable rows’ primary keys, or None when each row must be checked by dependency_tree_readable(): without a user, for rows of several models, or for a model whose manager has no read permissions.

classmethod dependents(instance)[source]

Return the resources that depend on a resource, as Django ORM rows, without building brokers.

This is the one place where a broker says which resources refer to its kind of resource. dependencies() builds a broker for each of these rows, and has_dependents() only asks whether there are any, which is much cheaper: a resource list page asks it for every row that it shows, as that row’s canDelete.

Return lazy QuerySets where possible, so that has_dependents() can ask each with one EXISTS query. Rows that can only be filtered in Python may be a generator.

Example:

@classmethod
def dependents(cls, instance: Guardrail) -> SAMDependents:
    llmclients = LLMClient.objects.filter(
        id__in=LLMClientGuardrails.objects.filter(guardrail=instance).values("llmclient_id")
    )
    return [(SAMKinds.LLM_CLIENT.value, llmclients)]
Parameters:

instance (TypeVar(MetaModelT, bound= Model)) – The resource’s Django ORM instance, e.g. a Guardrail.

Return type:

List[Tuple[str | None, Iterable[Model]]]

Returns:

The kinds and rows of the resources that depend on it, or an empty list.

Raises:

SAMBrokerErrorNotImplemented – If the broker does not implement it.

abstractmethod deploy(request, *args, **kwargs)[source]

Deploy a resource.

Parameters:
  • request (HttpRequest) – The HTTP request object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the result of the deploy operation.

deployable: ClassVar[bool] = False

True when the broker implements deploy().

The cli api’s resources command reports it as each kind’s Deployable, and the smarter cli offers deploy and undeploy commands for those kinds. A broker that sets it must override deploy(); undeploy() may still raise SAMBrokerErrorNotImplemented, as CustomDomain’s and LLMHostCompute’s do.

abstractmethod describe(request, *args, **kwargs)[source]

Describe a resource.

Parameters:
  • request (HttpRequest) – The HTTP request object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the description of the resource.

abstractmethod example_manifest(request, *args, **kwargs)[source]

Returns an example yaml manifest document for the kind of resource.

Parameters:
  • request (HttpRequest) – The HTTP request object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the example manifest.

filter_by_annotation_selector(queryset, kwargs)[source]

Filter a get command’s resources by the annotation selector in its query parameters.

The selector is the annotation query parameter, which may be repeated, e.g. ?annotation=acme.com/crm-account-id=A-10042&annotation=!acme.com/archived. Every requirement must match. See smarter.lib.annotation.selectors.

Parameters:
  • queryset (TypeVar(QuerySetType, bound= QuerySet)) – The resources that the requester may read.

  • kwargs (dict[str, Any]) – The get command’s keyword arguments, which hold the query parameters.

Raises:

smarter.lib.annotation.validation.SmarterAnnotationError – If the selector is invalid, which is a 400.

Return type:

TypeVar(QuerySetType, bound= QuerySet)

Returns:

The resources that match the selector.

property formatted_class_name: str

Return the logger prefix for the AbstractBroker.

Returns:

The logger prefix for the AbstractBroker.

property formatted_class_name_cache_invalidations: str

Return the logger prefix for the AbstractBroker cache invalidations.

Returns:

The logger prefix for the AbstractBroker cache invalidations.

abstractmethod get(request, *args, **kwargs)[source]

Get information about specified resources.

Parameters:
  • request (HttpRequest) – The HTTP request object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the result of the get operation.

get_model_titles(serializer)[source]

For tabular output from get() implementations.

Returns a list of field names and types from the Django model serializer.

Parameters:

serializer (ModelSerializer) – The Django model serializer instance.

Return type:

list[dict[str, str]] | None

Returns:

A list of field names and types.

get_or_create_secret(user_profile, name, value=None, description=None, expiration=None)[source]

Get or create a Smarter Secret in the database.

This is used to store secrets that are passed in the manifest.

Parameters:
  • user_profile (UserProfile) – The UserProfile to associate the secret with.

  • name (str) – The name of the secret.

  • value (str | None) – The value of the secret.

  • description (str | None) – A description of the secret.

  • expiration (datetime | None) – The expiration date of the secret.

Return type:

Secret

Returns:

The created or retrieved Secret object.

get_owned_object(model_class, caller)[source]

Return the row of model_class that has the broker’s name, owned by the first owner that has one.

The owners are tried in the order of owner_user_profiles(). A row that isn’t found is expected, e.g. for a manifest applied for the first time. Several rows for one owner, or an unexpected error, are logged, and end the search.

Parameters:
  • model_class (Type[TypeVar(OwnedModelT, bound= MetaDataModel)]) – The model to look the row up in.

  • caller (str) – The calling method’s name, for log messages.

Return type:

TypeVar(OwnedModelT, bound= MetaDataModel) | None

Returns:

The row, or None.

classmethod has_dependents(instance)[source]

Return True if any resource depends on a resource.

It asks dependents() whether there is at least one row, one kind at a time, and stops at the first. It builds no brokers, so it costs a few EXISTS queries.

Example:

if SAMGuardrailBroker.has_dependents(guardrail):
    print("an LLMClient uses this guardrail")
Parameters:

instance (TypeVar(MetaModelT, bound= Model)) – The resource’s Django ORM instance, e.g. a Guardrail.

Return type:

bool

Returns:

Whether any resource depends on it.

Raises:

SAMBrokerErrorNotImplemented – If the broker does not implement dependents().

property is_ready_abstract_broker: bool

Return True if the AbstractBroker is ready for operations.

An AbstractBroker is considered ready, and stays ready, if any of these is true:

  • The request is for an example manifest.

  • The request is for a JSON schema.

  • A manifest is loaded.

  • A ready SAMLoader is present.

  • An ORM meta instance was found.

Every reason why a broker is not ready is logged at DEBUG. A broker that is not ready is normal for a command that needs no single resource, e.g. get (a list). A command that does need one fails with SAMBrokerErrorNotReady, which the cli view logs.

Returns:

True if the AbstractBroker is ready for operations.

property is_valid: bool

True if the broker has a manifest, a ready loader, or an ORM instance.

Returns:

Whether the broker was initialized from any of them.

json_response_err(command, e)[source]

Return a structured error response that can be unpacked and rendered by the cli in a variety of formats.

Parameters:
Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the error response.

Raises:

SAMBrokerError – If the broker has no request.

json_response_err_notfound(command, message=None)[source]

Return a common not found response.

Parameters:
Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the not found response.

Raises:

SAMBrokerError – If the broker has no request.

json_response_err_notimplemented(command)[source]

Return a common not implemented response.

Parameters:

command (SmarterJournalCliCommands) – The command that was executed.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the not implemented response.

Raises:

SAMBrokerError – If the broker has no request.

json_response_err_notready(command)[source]

Return a common not ready response.

Parameters:

command (SmarterJournalCliCommands) – The command that was executed.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the not ready response.

Raises:

SAMBrokerError – If the broker has no request.

json_response_err_readonly(command)[source]

Return a common read-only response.

Parameters:

command (SmarterJournalCliCommands) – The command that was executed.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the read-only response.

Raises:

SAMBrokerError – If the broker has no request.

json_response_ok(command, data=None, message=None)[source]

Return a common success response.

Parameters:
Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the success response.

Raises:

SAMBrokerError – If the broker has no request.

property kind: str | None

The kind of manifest.

Returns:

The kind of manifest.

kind_setter(value)[source]

Set the kind of manifest.

Validates that the kind is a valid SmarterJournalThings value. None is ignored, with a warning, because a kind cannot be unset.

Parameters:

value (str | None) – The kind of manifest to set.

Raises:

SmarterValueError – If the kind is not valid.

Return type:

None

property known_name: str | None

The broker’s name, as far as it is known without building its manifest.

Readiness messages are logged while a broker initializes, after its loader has read the manifest’s name but before name is set. This keeps them from reporting no name.

Returns:

The name, from the broker, its manifest or its loader, or None.

property loader: SAMLoader | None

The SAMLoader instance for this broker.

Returns:

The SAMLoader instance for this broker.

log_abstract_broker_state()[source]

Log the current state of the AbstractBroker instance for debugging purposes.

A ready broker’s state is logged at DEBUG, which is usually switched off, so it is built only when it will be logged: it reads the broker’s ready state and ORM instance, which would otherwise cost every broker queries that its caller may never need. A broker that is not ready is logged at DEBUG too: a command that needs no single resource, e.g. get, never makes it ready, and one that does fails with SAMBrokerErrorNotReady, which the cli view logs.

Return type:

None

abstractmethod logs(request, *args, **kwargs)[source]

Get logs for a resource.

Parameters:
  • request (HttpRequest) – The HTTP request object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the logs for the resource.

abstract property manifest: dict[str, Any] | AbstractSAMBase | None

The Pydantic model representing the manifest.

If the manifest has not been initialized yet, this property will attempt to initialize it using the SAMLoader.

Returns:

The Pydantic model representing the manifest.

manifest_setter(value)[source]

Set the manifest for the broker and override all AbstractBroker model properties based on the manifest data.

Parameters:

value (dict[str, Any] | AbstractSAMBase | None) – The manifest to set, either as a Pydantic model or a dictionary.

Return type:

None

manifest_to_django_orm()[source]

Convert the Smarter API manifest metadata into a dictionary for creating or updating the resource’s Django ORM model.

This method extracts all relevant metadata from the loaded manifest and transforms it into a dictionary format compatible with Django ORM operations. The manifest’s configuration is first dumped and converted from camelCase to snake_case to match Django’s field naming conventions.

The resulting dictionary includes the account, name, description, and version fields from the manifest metadata. This dictionary is intended to be used to supplement the model spec when instantiating or updating the ORM model instance in the database.

If the manifest is not loaded or is invalid, an exception is raised to indicate that the broker is not ready to perform the transformation.

Return type:

dict[str, Any]

Returns:

A dictionary containing the user profile and all metadata fields, to create or update the Django ORM model.

Raises:
  • SAMBrokerErrorNotReady – If the manifest is not loaded, or the broker has no user profile.

  • SAMBrokerError – If the manifest metadata cannot be converted to a dictionary.

property name: str | None

The name of the resource that this broker manages, its manifest’s metadata.name.

The name is looked up once, and kept: from the manifest, if it is a Pydantic model, else from the loader’s manifest metadata, else from the request’s name query parameter. A name that cannot be found is logged at debug level, since some commands, e.g. json-schema, need no name, and those that do fail with their own error.

The name is essential for database queries and model lookups, together with the user profile.

Returns:

The name of the resource, or None if the name is not set or cannot be determined.

Note

The name property is a critical identifier used throughout the broker to ensure correct mapping between manifest data and persistent application state.

name_cached_property_setter(value)[source]

Set the broker’s name, which name then returns.

name was once a cached_property, so this also deletes a cached value of it from the instance’s __dict__, if one is there.

Parameters:

value (str | None) – The name to set for the manifest, or None.

Raises:

SmarterValueError – If the value is neither a string nor None.

Return type:

None

property orm_instance: ModelT | None

Return the Django ORM model instance for the broker.

There are multiple strategies to retrieve the ORM instance:

  1. If the instance is already cached in self._orm_instance, return it.

  2. If the broker is not ready or the name is not set, log a warning and return None.

  3. Attempt to retrieve the ORM instance using the user_profile and name. If not found, attempt to retrieve using the admin user_profile for the account. If still not found, attempt to retrieve using the Smarter platform admin user_profile.

  4. Cache the retrieved instance for future access.

Returns:

The Django ORM model instance for the broker.

property orm_meta_instance: MetaModelT | None

Return the Django ORM meta model instance for the broker.

It is the instance that orm_meta_instance_setter() found, by the broker’s name and user profile, or None. For simple relational models, the ORM meta class is the same as the ORM class, and the meta instance is the same as the ORM instance.

This property is used for resolving more complex ORM relationships where the name and user_profile fields are stored in a parent Django model.

orm_meta_instance_setter()[source]

Initialize the ORM metadata for the broker instance.

This method attempts to initialize the ORM metadata by querying the ORMMetaModelClass using the broker’s name and user_profile, then the account admin’s user profile, then the Smarter admin’s. If the ORM metadata is successfully retrieved, it is stored in the _orm_meta_instance attribute. If none is found, or an error occurs, _orm_meta_instance stays None. Multiple matches and unexpected errors are logged.

Nothing is done without a name and a user profile. If the meta model class is the ORM model class, and the ORM instance is already known, it is used instead of a query.

Return type:

None

owner_user_profiles()[source]

Yield the user profiles that may own the broker’s resource, in the order they are tried.

They are the broker’s user profile, the account admin’s, and the Smarter admin’s. Each one is looked up only when the one before it didn’t own the resource.

Return type:

Iterator[UserProfile | None]

Returns:

An iterator of the user profiles.

property params: QueryDict | None

Return the query parameters from the url of the request.

There are two scenarios to consider:

  1. the request is a Django HttpRequest object (the expected case)

  2. the request is a Python PreparedRequest object (the edge case)

Returns:

The query parameters from the url of the request.

abstractmethod prompt(request, *args, **kwargs)[source]

Invoke a prompt operation.

This abstract method should be implemented by subclasses to provide prompt-based interactions with the broker resource.

Parameters:
  • request (HttpRequest) – The HTTP request object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the prompt response.

raise_for_unknown_keys(manifest)[source]

Raise a validation error if the manifest has keys that its Pydantic model does not define.

The models ignore such keys, so that a misspelled key, e.g. defaultTemperatura, would otherwise be silently ignored, rather than be reported to the client as an error.

Parameters:

manifest (object) – The manifest, as a dict. Anything else is not checked, nor is a manifest of a broker whose Pydantic model is AbstractSAMBase itself.

Raises:

SAMValidationError – If the manifest has keys that its Pydantic model does not define.

Return type:

None

readable_by_name(model_class, owned, name=None)[source]

Return the resource to describe: the user’s own, or else one with this name that the user may read.

get lists every resource that the user may read, including the ones that are shared with the account, e.g. built-in Guardrails. describe must find each of them by the name that get returned. apply and delete must not: they act on the user’s own resource only.

Parameters:
Return type:

MetaDataWithOwnershipModel | None

Returns:

The resource, or None if the user may read none of this name.

property ready: bool

Return True if the broker is ready for operations.

A broker is considered ready if it has a valid manifest loaded.

Returns:

True if the broker is ready for operations.

property ready_state: str

Return a string representation of the broker’s ready state.

Returns:

“READY” if the broker is ready, otherwise “NOT_READY”.

classmethod references(instance)[source]

Return the resources that a resource uses, as Django ORM rows: the opposite of dependents().

A resource uses another when it refers to it, by name in its manifest or by a foreign key, e.g. an LLMClient uses the Guardrails in its spec.guardrails, and an SqlConnection uses the Secret of its password. Each edge here is the same edge that the other kind’s dependents() lists, seen from this end. dependency_tree() follows them, recursively.

A kind of resource that uses no others returns an empty list.

Example:

@classmethod
def references(cls, instance: MCPClient) -> SAMDependents:
    secrets = Secret.objects.filter(pk=instance.credentials_id)
    return [(SAMKinds.SECRET.value, secrets)]
Parameters:

instance (TypeVar(MetaModelT, bound= Model)) – The resource’s Django ORM instance, e.g. an LLMClient.

Return type:

List[Tuple[str | None, Iterable[Model]]]

Returns:

The kinds and rows of the resources that it uses, or an empty list. A kind of None means that each row has its own kind, in its kind field, as a plugin’s PluginMeta does.

Raises:

SAMBrokerErrorNotImplemented – If the broker does not implement it.

property request: HttpRequest | None

Return the request object.

Returns:

The request object.

schema(request, *args, **kwargs)[source]

Return the published JSON schema for the Pydantic model.

Parameters:
  • request (HttpRequest) – The HTTP request object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the JSON schema.

send_broker_ready(signal)[source]

Send a broker_ready signal, once per broker.

Brokers send it from their ready property, which is read many times while a manifest is applied. Each send was logged, so one apply logged that its broker was ready four to six times.

Parameters:

signal (Signal) – The app’s broker_ready signal.

Return type:

None

Returns:

None

set_and_verify_name_param(*args, command=None, **kwargs)[source]

Set the broker’s name from the name keyword argument, if it has one.

Nothing is verified, and nothing is raised: without a name, the broker keeps its name.

Parameters:
  • args – Not used.

  • command (SmarterJournalCliCommands | None) – The command being executed. Not used.

  • kwargs – The command’s keyword arguments, which may have a name.

Return type:

None

static tags_changed(instance, tags)[source]

Whether the tags of an ORM instance differ from the manifest’s.

See smarter.lib.django.models.utils.tags_changed().

Parameters:
  • instance (Model) – The ORM instance, which has a tags TaggableManager.

  • tags (list[str]) – The manifest’s tags.

Return type:

bool

Returns:

True if the instance is new, or its tags differ.

property thing: SmarterJournalThings

The Smarter Journal Thing for this broker.

Returns:

The Smarter Journal Thing for this broker.

to_json()[source]

Serialize the broker instance to a dict, with its keys sorted, for logging.

It includes the broker’s internal state, e.g. its request, authentication and cache key, so it is never returned to a client. See command_result().

Return type:

dict[str, Any]

Returns:

A JSON-serializable dict representation of the broker instance.

abstractmethod undeploy(request, *args, **kwargs)[source]

Undeploy a resource.

Parameters:
  • request (HttpRequest) – The HTTP request object.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse containing the result of the undeploy operation.

property uri: str | None

Return the full uri of the request.

Returns:

The full uri of the request.

classmethod validation_errors(manifest, external_checks=True)[source]

Validate a manifest against the broker’s Pydantic model, without saving it.

Pydantic’s errors keep their loc, the path of the invalid value in the manifest. Errors that the model’s validators raise as other exceptions, e.g. SAMValidationError, have an empty loc.

By default the manifest is validated as one that a client sent, inside client_manifest_validation(), so validators that check something outside of the manifest also run, e.g. that an image url responds. A caller that must not make requests on a client’s behalf, such as an anonymous endpoint, passes external_checks=False.

Example:

SAMGuardrailBroker.validation_errors({"apiVersion": "smarter.sh/v1", "kind": "Guardrail"})
# [{"loc": ["metadata"], "message": "Field required", "type": "missing"}, ...]
Parameters:
  • manifest (dict[str, Any]) – The manifest, as a dict.

  • external_checks (bool) – Whether to run the validators that check something outside of the manifest.

Return type:

list[dict[str, Any]]

Returns:

The manifest’s errors, as dicts with a loc, a message and a type, or an empty list.

verify_no_dependencies(command=None)[source]

Raise an error if other resources depend on this resource.

Call this in delete(), before deleting anything.

Parameters:

command (SmarterJournalCliCommands | None) – The command that is being processed.

Raises:

SAMBrokerErrorDependencies – If dependency_references() returns any.

Return type:

None

visible_dependencies(dependencies=None)[source]

Return the dependencies that the authenticated user may read.

A dependency may belong to another account, e.g. an LLMClient that uses a built-in Guardrail. Superusers may read every dependency. Other users may read those of their own account.

Parameters:

dependencies (List[AbstractBroker | SAMDependencyReference] | None) – The dependencies to filter. Defaults to dependencies().

Return type:

List[AbstractBroker | SAMDependencyReference]

Returns:

The dependencies that the authenticated user may read.

static with_owners(rows)[source]

Return the rows with their owners’ user profiles and users, read in the same query.

dependency_tree_owner() reads each row’s user_profile.user, which would otherwise be two more queries per node.

Parameters:

rows (Iterable[Model]) – The rows, usually a QuerySet.

Return type:

Iterable[Model]

Returns:

The QuerySet with select_related("user_profile__user") when its model has a user_profile foreign key, else the rows as they are.

class smarter.lib.manifest.broker.abstract_broker_class.BrokerNotImplemented(request=None, api_version=None, account=None, name=None, kind=None, loader=None, manifest=None, file_path=None, url=None)[source]

Bases: AbstractBroker

An error class to proxy for a broker class that has not been implemented.

property ORMModelClass: Type[MetaDataWithOwnershipModel]

Not implemented.

Raises:

SAMBrokerErrorNotImplemented – Always.

property SerializerClass: Type[ModelSerializer]

Not implemented.

Raises:

SAMBrokerErrorNotImplemented – Always.

__init__(request=None, api_version=None, account=None, name=None, kind=None, loader=None, manifest=None, file_path=None, url=None)[source]

Initialize the broker from a manifest, a loader, a manifest file, or the Django ORM.

A manifest takes precedence over a loader, and a loader over a file path. With none of them, the broker is initialized from the ORM instance named name and owned by the user profile, if there is one.

Parameters:
  • request – The request, or None. It may also be passed positionally in args.

  • args – Positional arguments, among which the request, user, account, user profile, manifest and loader are found by their types.

  • name – The resource’s name.

  • kind – The resource’s SAM kind, e.g. Guardrail.

  • loader – A loader that has read the manifest.

  • api_version – The manifest’s api version.

  • manifest – The manifest, as a Pydantic model or a dict.

  • file_path – The path of a manifest file, read when no loader is passed.

  • url – Accepted, for the same parameters as SAMLoader, but not used.

  • kwargs – user, account and user_profile, and the rest, which are passed on to SmarterRequestMixin.

Raises:
  • SmarterValueError – If the kind, name or manifest is invalid.

  • SAMBrokerError – If the loader’s kind is not the broker’s kind.

delete(request, *args, **kwargs)[source]

Delegate to AbstractBroker.delete().

Parameters:
  • request (HttpRequest | Request | ASGIRequest) – The request.

  • args – Passed through.

  • kwargs – Passed through.

Return type:

SmarterJournaledJsonResponse

dependencies()[source]

Delegate to AbstractBroker.dependencies().

Return type:

List[AbstractBroker | SAMDependencyReference]

deploy(request, *args, **kwargs)[source]

Delegate to AbstractBroker.deploy().

Parameters:
  • request (HttpRequest | Request | ASGIRequest) – The request.

  • args – Passed through.

  • kwargs – Passed through.

Return type:

SmarterJournaledJsonResponse

describe(request, *args, **kwargs)[source]

Delegate to AbstractBroker.describe().

Parameters:
  • request (HttpRequest | Request | ASGIRequest) – The request.

  • args – Passed through.

  • kwargs – Passed through.

Return type:

SmarterJournaledJsonResponse

example_manifest(request, *args, **kwargs)[source]

Delegate to AbstractBroker.example_manifest().

Parameters:
  • request (HttpRequest | Request | ASGIRequest) – The request.

  • args – Passed through.

  • kwargs – Passed through.

Return type:

SmarterJournaledJsonResponse

get(request, *args, **kwargs)[source]

Delegate to AbstractBroker.get().

Parameters:
  • request (HttpRequest | Request | ASGIRequest) – The request.

  • args – Passed through.

  • kwargs – Passed through.

Return type:

SmarterJournaledJsonResponse

logs(request, *args, **kwargs)[source]

Delegate to AbstractBroker.logs().

Parameters:
  • request (HttpRequest | Request | ASGIRequest) – The request.

  • args – Passed through.

  • kwargs – Passed through.

Return type:

SmarterJournaledJsonResponse

property manifest: dict[str, Any] | AbstractSAMBase | None

Not implemented.

Raises:

SAMBrokerErrorNotImplemented – Always.

prompt(request, *args, **kwargs)[source]

Delegate to AbstractBroker.prompt().

Parameters:
  • request (HttpRequest | Request | ASGIRequest) – The request.

  • args – Passed through.

  • kwargs – Passed through.

Return type:

SmarterJournaledJsonResponse

undeploy(request, *args, **kwargs)[source]

Delegate to AbstractBroker.undeploy().

Parameters:
  • request (HttpRequest | Request | ASGIRequest) – The request.

  • args – Passed through.

  • kwargs – Passed through.

Return type:

SmarterJournaledJsonResponse

smarter.lib.manifest.broker.abstract_broker_class.KNOWN_KINDS: frozenset[str] = frozenset({'Account', 'ApiConnection', 'ApiPlugin', 'Budget', 'ChatConfig', 'CustomDomain', 'Guardrail', 'ImageSearchPlugin', 'LLMClient', 'LLMHost', 'LLMHostCompute', 'MCPClient', 'Orchestrator', 'Plugin', 'Prompt', 'Provider', 'Proxy', 'Secret', 'SkillPlugin', 'SmarterAuthToken', 'SqlConnection', 'SqlPlugin', 'User', 'Vectorsearch', 'Vectorstore', 'WebsearchPlugin'})

Every valid broker kind.

An enum’s members are fixed, so the set is built once.

class smarter.lib.manifest.broker.abstract_broker_class.MetaModelT

The Django ORM model that holds a broker’s resource’s name and owner, its AbstractBroker.ORMMetaModelClass.

For most kinds it is the same model as ModelT. A plugin’s is its PluginMeta.

alias of TypeVar(‘MetaModelT’, bound=Model)

class smarter.lib.manifest.broker.abstract_broker_class.ModelT

The Django ORM model of a broker’s resource, its AbstractBroker.ORMModelClass.

alias of TypeVar(‘ModelT’, bound=Model)

class smarter.lib.manifest.broker.abstract_broker_class.OwnedModelT

A Django ORM model that has a name and an owner, as AbstractBroker.get_owned_object() looks up.

E.g. a MetaDataWithOwnershipModel, or a Budget.

alias of TypeVar(‘OwnedModelT’, bound=MetaDataModel)

class smarter.lib.manifest.broker.abstract_broker_class.RowT

A Django ORM model, as rows_with_pk() returns rows of.

alias of TypeVar(‘RowT’, bound=Model)

smarter.lib.manifest.broker.abstract_broker_class.SAMDependency = ForwardRef('AbstractBroker') | smarter.lib.manifest.broker.abstract_broker_class.SAMDependencyReference

its broker, or a reference to it when its broker fails to initialize.

Type:

A resource that depends on another

class smarter.lib.manifest.broker.abstract_broker_class.SAMDependencyReference(kind, name, user_profile)[source]

Bases: object

The kind, name and owner of a dependent resource whose broker could not be initialized.

AbstractBroker.dependency_broker() returns one when a dependent resource’s broker raises during initialization, for example a plugin whose stored model was later removed from the list of valid models. It keeps the dependency visible, so that AbstractBroker.verify_no_dependencies() still refuses to delete the resource it depends on, and describe still lists it in status.dependencies.

Example:

dependency = SAMDependencyReference(kind="Plugin", name="everlasting_gobstopper", user_profile=user_profile)
print(dependency.kind, dependency.name, dependency.account)
Parameters:
  • kind (str) – The SAM kind of the resource, e.g. SAMKinds.STATIC_PLUGIN.value.

  • name (str) – The resource’s manifest name.

  • user_profile (UserProfile | None) – The resource’s owner.

__init__(kind, name, user_profile)[source]
property account: Account | None

The account of the resource’s owner, if it has one.

smarter.lib.manifest.broker.abstract_broker_class.SAMDependents

The resources that depend on another, as their Django ORM rows, grouped by SAM kind.

Each pair is a kind, e.g. SAMKinds.LLM_CLIENT.value, and the rows of that kind, usually a lazy QuerySet. A kind of None means that each row has its own kind, in its kind field, as a plugin’s PluginMeta does. See AbstractBroker.dependents().

alias of List[Tuple[str | None, Iterable[Model]]]

smarter.lib.manifest.broker.abstract_broker_class.dependents_exist(rows)[source]

Return True if there is at least one row, reading no more of them than that.

A QuerySet is asked with one EXISTS query, and any other iterable is read up to its first item, so a generator that filters rows in Python stops at the first match.

Parameters:

rows (Iterable[Model]) – The rows of one kind, from AbstractBroker.dependents().

Return type:

bool

Returns:

Whether there is at least one row.

smarter.lib.manifest.broker.abstract_broker_class.first_arg_of_type(args, types)[source]

Return the first positional argument that is an instance of a type, or None.

A broker can be passed its request, user, account, user profile, manifest and loader positionally, in any order, so AbstractBroker finds each by its type.

Parameters:
Return type:

Any

Returns:

The first argument of that type, or None if there is none.

smarter.lib.manifest.broker.abstract_broker_class.memoized_dependencies(func)[source]

Memoize a broker’s AbstractBroker.dependencies() for the life of the broker instance.

The dependencies are queried, and their brokers built, once per broker instance. AbstractBroker.verify_no_dependencies() clears the memo before it checks, so that a delete always sees the current dependencies.

Example:

class SAMGuardrailBroker(AbstractBroker):

    @memoized_dependencies
    def dependencies(self) -> List[AbstractBroker]:
        ...
Parameters:

func (Callable[..., List[AbstractBroker | SAMDependencyReference]]) – The broker’s dependencies() method.

Return type:

Callable[..., List[AbstractBroker | SAMDependencyReference]]

Returns:

The memoized method.

smarter.lib.manifest.broker.abstract_broker_class.rows_with_pk(manager, pk)[source]

Return the row with a primary key, as a QuerySet, or an empty QuerySet if the key is None.

A broker’s AbstractBroker.references() uses it for a nullable foreign key, e.g. rows_with_pk(Secret.objects, llmhost.api_key_secret_id). Unlike a filter on the reverse relation, it also works for an unsaved instance.

Parameters:
  • manager (Manager) – The model’s manager, e.g. Secret.objects.

  • pk (int | None) – The primary key, e.g. a foreign key’s id, or None.

Return type:

QuerySet

Returns:

A QuerySet of the row, or an empty QuerySet.

smarter.lib.manifest.broker.abstract_broker_class.should_log(level)[source]

Return True if the MANIFEST_LOGGING waffle switch is on, for the module’s waffle-switched logger.

Parameters:

level (int) – The log level. Not used: the switch turns every level on or off.

Return type:

bool

Returns:

Whether the switch is on.