Metadata Model

The abstract base model of Smarter models that hold SAM metadata: name, description, version, tags, annotations.

class smarter.lib.django.models.metadata_model.MetaDataModel(*args, **kwargs)[source]

Abstract base model that adds the SAM metadata fields to TimestampedModel.

These are the common fields that make up the Pydantic SAM metadata model, along with the timestamp fields for create/modify tracking.

Example Usage:

from smarter.lib.django.models import MetaDataModel

class MyModel(MetaDataModel):
    name = models.CharField(max_length=100)
Parameters:
  • created_at (Unknown) – Created at

  • updated_at (Unknown) – Updated at

  • name (Unknown) – Name. Name in camelCase, e.g., ‘apiKey’, no special characters.

  • description (Unknown) – Description. A brief description of this resource. Be verbose, but not too verbose.

  • version (Unknown) – Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.

Relationship fields:

Parameters:

tags (Unknown) – Tags. Tags for categorizing and organizing this resource.

property annotations: dict[str, str]

a map of string keys to string values, as in Kubernetes.

Assigning to it validates the new annotations, and the next save() makes the stored annotations exactly these, adding, changing and removing rows of smarter.lib.annotation.models.Annotation. Assignment accepts a map, or the list of one-key maps of older manifests, and converts scalar values to strings.

Example:

llmclient.annotations = {**llmclient.annotations, "acme.com/crm-account-id": "A-10042"}
llmclient.save()
Returns:

A copy of the annotations. Changing it doesn’t change the resource.

Type:

The resource’s annotations

Setter accepts:

None | str | dict[str, Any] | list[dict[str, Any]]

clone(new_name, new_version=None)[source]

Clone the model instance with a new name and optional new version.

Only the name, version, description and annotations are copied. The clone is validated and saved.

Parameters:
  • new_name (str) – The name for the cloned instance.

  • new_version (str | None) – The version for the cloned instance. If not provided, it will be the same as the original.

Return type:

MetaDataModel

Returns:

The new, saved instance.

created_at

DateTimeField

Created at

Timestamp indicating when the model instance was created.

This field is automatically set to the current date and time when the instance is first created. It is indexed in the database for efficient querying.

Type:

Type

description

TextField

Description. A brief description of this resource. Be verbose, but not too verbose.

Type:

Type

classmethod from_db(db, field_names, values, **kwargs)[source]

Load a row, and remember its name, so that save() can tell a rename.

Parameters:
  • db (str | None) – The database alias.

  • field_names (Collection[str]) – The loaded fields’ names.

  • values (Collection[Any]) – The loaded fields’ values.

  • kwargs (Any) – Passed on to Django’s, e.g. the fetch_mode that Django’s type stubs already declare.

Return type:

Self

Returns:

The instance.

classmethod get_cached_object(*args, invalidate=False, pk=None, name=None, **kwargs)[source]

Retrieve a model instance by primary key or name, using caching to optimize performance.

This method is selectively overridden in models that inherit from MetaDataModel to provide class-specific function parameters.

Example

# Retrieve by primary key
instance = MyModel.get_cached_object(pk=1)
# Retrieve by name
instance = MyModel.get_cached_object(name="exampleName")
Parameters:
  • args – Accepted for the subclasses’ signature, and ignored.

  • invalidate (bool | None) – Whether to drop the cached row, and read it again from the database.

  • pk (int | None) – The primary key of the model instance to retrieve.

  • name (str | None) – The name of the model instance to retrieve, which takes precedence over pk.

  • kwargs – Passed on to TimestampedModel.get_cached_object() for a lookup by pk.

Return type:

MetaDataModel

Returns:

The model instance.

Raises:
classmethod get_cached_objects(invalidate=False, **kwargs)[source]

Retrieve model instances using caching to optimize performance.

This method is selectively overridden in models that inherit from MetaDataModel to provide class-specific function parameters.

Example

# Retrieve all instances
instances = MyModel.get_cached_objects()
Parameters:
  • invalidate (bool | None) – Whether to invalidate the cache for this retrieval.

  • kwargs – Passed on to TimestampedModel.get_cached_objects().

Return type:

QuerySet[MetaDataModel]

Returns:

A queryset of all model instances.

Raises:

NotImplementedError – if called on an abstract model class.

classmethod invalidate_cached_name(name)[source]

Drop the cached copy of the row that had name.

get_cached_object() with invalidate=True drops it, then looks the name up again. That lookup fails when no row has the name any more, e.g. after a rename, or when several rows share it, e.g. the profiles of one user in several accounts. Either way the cached copy is already gone, so the failure is ignored.

Parameters:

name (str) – The name the row was cached by.

Return type:

None

name

CharField

Name. Name in camelCase, e.g., ‘apiKey’, no special characters.

Type:

Type

property ready: bool[source]

Check if the model instance is ready for use.

Returns:

True if the instance is ready, False otherwise.

remove_annotation(key)[source]

Remove one annotation of a saved resource, immediately.

Does nothing if it doesn’t exist.

Parameters:

key (str) – The annotation key.

Return type:

None

rename(new_name)[source]

Rename the model instance with a new name.

The instance is validated and saved.

Parameters:

new_name (str) – The new name for the instance.

Return type:

MetaDataModel

Returns:

The updated instance of MetaDataModel with the new name.

property rfc1034_compliant_name: str | None[source]

Returns a URL-friendly name for the llmclient.

This property returns an RFC 1034-compliant name for the llmclient, suitable for use in URLs and DNS labels.

Example:

self.name = 'Example LLMClient 1'
self.rfc1034_compliant_name  # 'example-llmclient-1'
Returns:

The RFC 1034-compliant name, or None if self.name is not set.

save(*args, **kwargs)[source]

Validate and save the model instance, write its pending annotations, and invalidate its caches.

TimestampedModel.save() validates the instance first. Then the annotations assigned since the last save are written. When an existing row of a direct subclass of MetaDataModel is saved, its cached copies, by pk and by name, and the cached list of all rows, are invalidated.

Example

obj = MyModel(name="Example")
obj.save()  # Will call validate() before saving

Important

  • If you override this method in a subclass, always call super().save(*args, **kwargs) to retain validation and timestamp functionality.

  • If validation fails, no data will be saved to the database.

Parameters:
  • args – Positional arguments, forwarded to Django’s save().

  • kwargs – Keyword arguments, forwarded to Django’s save().

Raises:

SmarterValueError – if validation fails.

save_annotations()[source]

Write annotations assigned since the last save() to the database, without saving the resource’s other fields.

Return type:

None

set_annotation(key, value)[source]

Add or change one annotation of a saved resource, immediately.

Parameters:
  • key (str) – The annotation key, e.g. acme.com/crm-account-id.

  • value (object) – The value. Scalars are converted to strings.

Raises:

SmarterAnnotationError – If the key or value is invalid.

Return type:

None

tags = <taggit.managers._TaggableManager object>
property tags_list: list[str][source]

Return the tags as a list of strings.

It is cached twice: cached_property keeps it on the instance, which is the fastest lookup, and cache_results keeps it in the Django cache, which outlives the instance.

Returns:

List of tag names.

updated_at

DateTimeField

Updated at

Timestamp indicating when the model instance was last updated.

This field is automatically updated to the current date and time whenever the instance is saved. It is indexed in the database for efficient querying.

Type:

Type

validate()[source]

Validate the model: its version, when set, must be a semantic version.

Raises:

SmarterValueError – if the version is not MAJOR.MINOR.PATCH.

version

CharField

Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.

Type:

Type

classmethod with_annotation(key, value=None)[source]

Return the resources of this model that have the annotation key, with value if given.

Example:

LLMClient.with_annotation("acme.com/crm-account-id", "A-10042")
Parameters:
  • key (str) – The annotation key.

  • value (str | None) – The value to match, or None for any value.

Return type:

QuerySet

Returns:

The resources, not filtered by any user’s permissions.