SQL Plugin Broker

class smarter.apps.llmtool.manifest.brokers.sql_plugin.SAMSqlPluginBroker(*args, **kwargs)[source]

Broker for Smarter SQL Plugin Manifests.

This class is responsible for loading, validating, and parsing Smarter SQL YAML plugin manifests, and for initializing the corresponding Pydantic model. It provides generic services for SQL plugins, such as instantiation, creation, update, and deletion.

Responsibilities:

  • Load and validate SQL plugin manifests.

  • Parse manifest data into a structured Pydantic model (SAMSqlPlugin).

  • Provide access to plugin metadata, status, and specification.

  • Manage plugin lifecycle operations (create, update, delete, etc.).

Example Usage:

broker = SAMSqlPluginBroker(manifest=my_manifest)
plugin = broker.plugin
if plugin.ready:
    plugin.create()
    plugin.save()

Parameters:

Parameters:

manifest (Optional[SAMSqlPlugin]) – Optional; a SAMSqlPlugin Pydantic model instance representing the plugin manifest.

Note

If the manifest kind does not match the expected plugin kind, or if required fields are missing, the broker may raise a SAMPluginBrokerError or related exception.

property ORMMetaModelClass: Type[PluginMeta]

Return the Django ORM meta model class for the broker.

Returns:

The Django ORM meta model class definition for the broker.

Return type:

Type[PluginMeta]

property ORMModelClass: Type[PluginDataSql]

Return the Django ORM model class for the broker.

Returns:

The Django ORM model class definition for the broker.

Return type:

Type[PluginDataSql]

property SAMModelClass: Type[SAMSqlPlugin]

Return the Pydantic model class for the broker.

Returns:

The Pydantic model class definition for the broker.

Return type:

Type[SAMSqlPlugin]

property SerializerClass: Type[PluginSerializer]

Returns the serializer class for the broker.

This property provides the serializer class definition used by the broker for serializing and deserializing plugin data. It returns the PluginSerializer class, which is specifically designed to handle static plugin data serialization.

Returns:

The serializer class definition for the broker.

Return type:

Type[PluginSerializer]

Example:

broker = SAMStaticPluginBroker()
serializer_class = broker.SerializerClass
print(serializer_class.__name__)
# Output: "PluginSerializer"

See also

  • PluginSerializer for static plugin data serialization.

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

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

A manifest takes precedence over a file path. With neither, 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 and manifest are found by their types.

  • name – The resource’s name.

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

  • api_version – The manifest’s api version.

  • manifest – The manifest, as a Pydantic model or as a dict, e.g. from parse_manifest().

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

  • url – Accepted, for compatibility, 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 manifest’s kind is not the broker’s kind.

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”.

accepted_session_key(session_key, source)

Return a session key that the request carries, if it is well formed.

The key comes from the client: the url, the request body, a cookie or a get() parameter. A malformed key, e.g. a cookie of the same name that another application set on a parent domain, is ignored rather than raised, so that the request starts a new session instead of failing.

Parameters:
  • session_key (str | None) – The raw value that the request carries, or None.

  • source (str) – Where the value came from, for the log, e.g. "cookie".

Return type:

str | None

Returns:

The session key, stripped of whitespace and of a trailing slash, or None if the value is missing or malformed.

property account: Account | None

Returns the account for the current user.

Handle lazy instantiation from user or user_profile.

Returns:

The account for the current user.

Return type:

Account or None

property account_number: str | None

A helper function to get the account number from the account.

Returns:

The account number for the current account.

Return type:

str or None

property administers_account: bool

manages every resource in it.

See user_administers_account().

Returns:

True if the current user may manage every resource of the current account.

Type:

Whether the current user administers the current account

property am_ready: bool

Returns True if the AccountMixin is am_ready to be used.

This is a convenience property that checks if the account and user are initialized. AccountMixin is considered am_ready if: - self.user is an instance of User - self.user_profile is an instance of UserProfile - self.account is an instance of Account

Returns:

True if the AccountMixin is am_ready to be used.

Return type:

bool

property amnesty_urls: list[str]

Returns a list of URLs that are exempt from certain checks.

Returns:

List of URL path strings that are exempt.

Return type:

list[str]

property api_subdomain: str | None

Extract the API subdomain, the first label of the host, from an llmclient URL.

For example, this url returns 'hr':

https://hr.3141-5926-5359.alpha.api.example.com/llm-client/
Returns:

The API subdomain, or None if the url is not an llmclient url.

property api_token: bytes | None

Get the API token from the request’s Authorization header.

The header’s value is Token <key> or Bearer <key>.

Example:

request_mixin = SmarterRequestMixin(request)
token = request_mixin.api_token
Returns:

The API token as bytes, or None if the header is missing or has neither prefix.

property api_version: str

The API version of the manifest.

Returns:

The API version of the manifest.

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

Apply the manifest: copy manifest data to the Django ORM model and save it to the database.

This method loads and validates the manifest, then applies its data to the corresponding Django ORM model. The plugin is created and, if ready, saved to the database. The response includes the serialized plugin data or an error message if the operation fails.

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

  • args – Additional positional arguments (unused).

  • kwargs – Additional keyword arguments for customization.

Returns:

A SmarterJournaledJsonResponse indicating success or failure.

Return type:

SmarterJournaledJsonResponse

Example:

response = broker.apply(request)
print(response.data)
Raises:
  • SAMPluginBrokerError – If the manifest is not set or is not a valid SAMSqlPlugin

  • SAMBrokerErrorNotReady – If the plugin is not ready

See also

SAMSqlPluginBroker.manifest() SAMSqlPlugin SqlPlugin SmarterJournaledJsonResponse SAMPluginBrokerError SAMBrokerErrorNotReady

static assign_changed_fields(instance, data)

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.

property auth_header: str | None

Get the Authorization header from the request.

Example:

request_mixin = SmarterRequestMixin(request)
print(request_mixin.auth_header)

This property checks for the “Authorization” header in the request headers.

Returns:

The value of the “Authorization” header as a string, or None if not present.

authenticate(api_token=None, request=None)

Authenticate the request using the API token in its Authorization header.

The request is passed along, so that a token that was already authenticated for it, e.g. by the token middleware or by AccountMixin’s own initialization, is not authenticated again.

Parameters:
  • api_token (bytes | None) – The API token to authenticate with. Defaults to the request’s.

  • request (HttpRequest | None) – The request that carries the token. Defaults to this mixin’s request.

Return type:

bool

Returns:

True if there is an API token and the parent’s authenticate() accepts it, otherwise False.

bool_environment_variable(var_name, default=False)

Retrieves a boolean value from an environment variable.

This method checks the specified environment variable and returns its value as a boolean. It recognizes common truthy values such as “true”, “1”, “yes”, and “on”. If the variable is not set or cannot be interpreted as a boolean, it returns the provided default value.

Parameters:
  • var_name (str) – The name of the environment variable to check.

  • default (bool) – The default boolean value to return if the environment variable is not set or invalid.

Returns:

The boolean value of the environment variable or the default.

Return type:

bool

cache_invalidations()[source]

Invalidate any relevant caches when the manifest or plugin data changes.

Return type:

None

property cache_key: str | None

Returns a cache key for the request.

This is used to cache the prompt request thread. The key is the sha256 hash of:

  • the class name,

  • the request’s user, or "Anonymous",

  • and the client UID (uid), or "unknown_uid".

Currently used by the ApiV1CliPromptConfigApiView and ApiV1CliPromptApiView as a means of sharing the session_key.

Example:

request_mixin = SmarterRequestMixin(request)
key = request_mixin.cache_key
print(key)  # e.g., 'a1b2c3d4e5f6...'
Returns:

A unique cache key string, or None if there is no request.

clean_cli_param(param, param_name='unknown', url=None)

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.

clear_cached_properties()

Clear the request, its parsed values, and all cached properties in this mixin.

Return type:

None

Returns:

None.

command_result()

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.

property data: dict[str, Any] | list[Any] | str | None

Get the request body data as a dictionary, list or str.

Used for setting the session_key.

Example:

request_mixin = SmarterRequestMixin(request)
data = request_mixin.data
print(data)  # e.g., {'session_key': 'abc123', ...}
Returns:

The request body parsed as json or yaml, an empty dict if the body is empty or can’t be parsed, or None if there is no request or the request is not qualified.

data_to_dict(data)

Converts data to a dictionary, handling different types of input.

This method accepts either a dictionary or a string. If a string is provided, it will attempt to parse it as JSON first, and if that fails, as YAML. If parsing fails or the data type is unsupported, a SmarterValueError is raised.

Parameters:

data (dict[str, Any] | str) – The data to convert, either a dict or a JSON/YAML string.

Returns:

The data as a dictionary.

Return type:

dict[str, Any]

Raises:

SmarterValueError – If the data cannot be converted to a dictionary.

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

Delete the SQL plugin.

This method deletes the SQL plugin associated with this broker. It verifies that the plugin is of the correct type and is ready before attempting deletion. If successful, it returns a JSON response indicating success; otherwise, it raises appropriate errors.

Raises:

SAMPluginBrokerError: If the plugin or plugin metadata is not properly initialized.

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

  • args – Additional positional arguments (unused).

  • kwargs – Additional keyword arguments (unused).

Returns:

A SmarterJournaledJsonResponse indicating success or failure of the deletion.

Return type:

SmarterJournaledJsonResponse

See also

SqlPlugin SmarterJournaledJsonResponse SAMPluginBrokerError SmarterJournalCliCommands

delete_plugin(command)

Delete this broker’s plugin, ready or not, once nothing depends on it.

A plugin that isn’t ready, e.g. one that is missing its selector or prompt, is deleted too: otherwise it could never be deleted, nor applied again under its name. See smarter.apps.llmtool.plugin.base.PluginBase.delete().

Parameters:

command (SmarterJournalCliCommands) – The journal command, delete.

Return type:

SmarterJournaledJsonResponse

Returns:

An ok response.

Raises:

SAMBrokerError – If the plugin has dependencies, or its deletion fails.

dependencies()

Return brokers for the LLMClients that use this plugin.

Returns:

A broker for each LLMClient that lists this plugin in its spec.plugins.

Return type:

List[AbstractBroker | SAMDependencyReference]

dependencies_status()

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)

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)

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)

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

Parameters:

instance (PluginMeta | 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()

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()

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: PluginMeta | None

The plugin’s PluginMeta, which the resources that use the plugin refer to.

Returns:

The PluginMeta, or None if the plugin does not exist.

Return type:

Optional[PluginMeta]

static dependency_tree_name(instance)

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)

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)

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)

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)

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)

Return the LLMClients that use a plugin.

Parameters:

instance (PluginMeta) – The PluginMeta.

Returns:

The LLMClients that list the plugin in their spec.plugins.

Return type:

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

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

Deploy the SQL plugin (not implemented).

This is not implemented for SQL plugins.

Raises:

SAMBrokerErrorNotImplemented: Always raised to indicate that this method is not implemented.

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

  • args – Additional positional arguments (unused).

  • kwargs – Additional keyword arguments (unused).

Returns:

A SmarterJournaledJsonResponse indicating that the method is not implemented.

Return type:

SmarterJournaledJsonResponse

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.

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

Return a JSON response with the manifest data for this SQL plugin.

This method serializes the current SQL plugin’s manifest, metadata, specification, and status into a structured JSON response, suitable for API clients or UI inspection. It validates the manifest by round-tripping the data through the Pydantic model to ensure schema compliance.

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

  • args – Additional positional arguments (unused).

  • kwargs – Additional keyword arguments for customization.

Returns:

A SmarterJournaledJsonResponse containing the manifest data.

Return type:

SmarterJournaledJsonResponse

Example:

response = broker.describe(request)
print(response.data)
Raises:
  • SAMPluginBrokerError – If required plugin components are not initialized.

  • SAMBrokerErrorNotReady – If the broker is not ready to describe the plugin.

See also

SAMSqlPluginBroker.manifest() SmarterJournaledJsonResponse SAMPluginBrokerError SAMBrokerErrorNotReady SqlPlugin SmarterJournalCliCommands SAMSqlPlugin SAMKeys SqlData SAMPluginSpecKeys SAMPluginMeta

deserves_amnesty(slug)

Determines if a given URL deserves amnesty based on the amnesty URLs list.

This excuses certain endpoints (like health checks) from select middleware checks.

Parameters:

slug (str) – The URL path to check.

Returns:

True if the URL deserves amnesty, False otherwise.

Return type:

bool

dict_is_contained_in(dict1, dict2)

Checks if one dictionary is contained within another.

This method determines if all key-value pairs in dict1 are present in dict2.

Parameters:
  • dict1 (dict[str, Any]) – The dictionary to check for containment.

  • dict2 (dict[str, Any]) – The dictionary to check against for containment.

Returns:

True if dict1 is contained in dict2, False otherwise.

Return type:

bool

dict_is_subset(small, big)

Checks if one dictionary is a subset of another.

This method determines if all key-value pairs in the small dictionary are present in the big dictionary. It returns True if the small dictionary is a subset of the big dictionary, and False otherwise.

Parameters:
  • small (dict[str, Any]) – The dictionary to check as a subset.

  • big (dict[str, Any]) – The dictionary to check against as a superset.

Returns:

True if the small dictionary is a subset of the big dictionary, False otherwise.

Return type:

bool

documents(request, *args, **kwargs)

List, add or remove a resource’s documents.

Only a kind that holds documents, a Vectorstore, implements it.

Parameters:
  • request (HttpRequest) – The HTTP request object, with any documents to add.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Return type:

SmarterJournaledJsonResponse

Returns:

A SmarterJournaledJsonResponse with the resource’s documents.

Raises:

SAMBrokerErrorNotImplemented – For every other kind.

property domain: str | None

Extract the domain, the host and port, from the URL.

For example, this url returns 'hr.3141-5926-5359.alpha.api.example.com':

https://hr.3141-5926-5359.alpha.api.example.com/llm-client/
Returns:

The domain, or None if there is no request or url.

eval_llmclient_url()

Resolve the account and user of a request to a deployed LLMClient’s own host.

For a named url, e.g. http://example.3141-5926-5359.api.localhost:9357/, the account is loaded from the url’s account number when account is not already set, and then, when user is not set, the user becomes that account’s admin user.

Other llmclient urls, the smarter api and cli api urls, need no follow up here. A request that is not an llmclient request is left as it is.

Return type:

None

Returns:

None. Sets account and user as a side effect.

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

Returns an example SQL plugin manifest as a JSON response.

This method generates a sample manifest for the SQL plugin using the static example_manifest method of the SqlPlugin class. The response is wrapped in a SmarterJournaledJsonResponse for consistency with the Smarter API’s journaling and response conventions.

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

  • args – Additional positional arguments (unused).

  • kwargs – Additional keyword arguments passed to the example manifest generator.

Returns:

A JSON response containing the example SQL plugin manifest.

Return type:

SmarterJournaledJsonResponse

Example:

response = broker.example_manifest(request)
print(response.data)

See also

SqlPlugin.example_manifest() SmarterJournaledJsonResponse

filter_by_annotation_selector(queryset, kwargs)

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 (QuerySetType) – 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:

QuerySetType

Returns:

The resources that match the selector.

find_session_key()

Return the unique prompt session key value for this request.

The session_key is managed by the /config/ endpoint for the llmclient. The React app calls this endpoint at app initialization to get a JSON dict that includes, among other info, this session_key, which uniquely identifies the device and the individual llmclient session for the device.

For subsequent prompt requests, the session_key is intended to be sent in the body of the request as a key-value pair, e.g. {"session_key": "1234567890"}.

The session key is looked for in these places, in this order, and the first well formed one (see accepted_session_key()) is returned:

  • The URL, e.g. http://localhost:9357/workbench/example/config/?session_key=1aeee4c1f183354247f43f80261573da921b0167c7c843b28afd3cb5ebba0d9a

  • The request body: {'session_key': '1aeee4c1f183354247f43f80261573da921b0167c7c843b28afd3cb5ebba0d9a'}

  • A cookie

  • The request’s GET parameters

Return type:

str | None

Returns:

The session key as a string, or None if not found.

property formatted_class_name: str

Returns a formatted class name for logging.

This property provides a human-readable, fully qualified class name, which is especially useful for log messages and debugging output. The format includes the parent class’s formatted name, followed by the current class name.

Returns:

A string representing the formatted class name, e.g., ParentClass.SAMSqlPluginBroker().

Return type:

str

Example:

broker = SAMSqlPluginBroker(manifest=my_manifest)
print(broker.formatted_class_name)
# Output: ParentClass.SAMSqlPluginBroker()
formatted_json(json_obj)

Formats a JSON object as a pretty-printed string with ANSI color codes for logging.

Parameters:

json_obj (dict[str, Any] | list) – The JSON object (dict or list) to format.

Returns:

A string representation of the JSON object with ANSI color codes.

Return type:

str

property formatted_state_not_ready: str

Returns the not-ready state formatted for logging.

Returns:

The formatted not-ready state as a string.

Return type:

str

property formatted_state_ready: str

Returns the readiness state formatted for logging.

Returns:

The formatted readiness state as a string.

Return type:

str

formatted_text(text, color_code='\x1b[1;31m')

Formats text with ANSI color codes for logging.

Parameters:
  • text (str) – The text to format.

  • color_code (str) – The ANSI color code to apply.

Returns:

The formatted text with ANSI color codes.

Return type:

str

formatted_text_blue(text)

Formats text in bold dark blue for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in bold dark blue.

Return type:

str

formatted_text_green(text)

Formats text in bright green for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in bright green.

Return type:

str

formatted_text_red(text)

Formats text in dark red for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in dark red.

Return type:

str

generate_fernet_encryption_key()

Generates a Fernet encryption key.

This method creates a new Fernet encryption key, which can be used for secure encryption and decryption of data. The generated key is returned as a URL-safe base64-encoded string.

Returns:

A new Fernet encryption key.

Return type:

str

generate_session_key()

Generate a new, random session_key.

Return type:

str

Returns:

A random 64 character session key.

generate_smarter_request_id()

Generate a unique identifier for the request.

Return type:

str

Returns:

A random uuid4, as 32 hexadecimal characters.

get(request, *args, **kwargs)

Return a JSON response with a list of SQL plugins for this account.

This method queries the database for all SQL plugins associated with the current account, optionally filtered by name, and returns a structured JSON response containing their serialized representations. Each plugin is validated by round-tripping through the Pydantic model.

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

  • args – Additional positional arguments (unused).

  • kwargs – Additional keyword arguments, such as filter criteria (e.g., name).

Returns:

A SmarterJournaledJsonResponse containing a list of SQL plugin manifests and metadata.

Return type:

SmarterJournaledJsonResponse

Example:

response = broker.get(request, name="my_plugin")
print(response.data)
Raises:

SAMPluginBrokerError – If a plugin cannot be serialized or validated during the retrieval process.

See also

PluginMeta PluginSerializer SAMSqlPlugin SmarterJournaledJsonResponse SmarterJournalCliCommands SAMKeys SAMMetadataKeys SCLIResponseGet SCLIResponseGetData

Retrieve the value of a cookie from the request object.

Parameters:

cookie_name (str) – Name of the cookie to retrieve.

Return type:

str | None

Returns:

Value of the cookie, or None if there is no request or the cookie does not exist.

get_model_titles(serializer)

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)

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)

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[OwnedModelT]) – The model to look the row up in.

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

Return type:

OwnedModelT | None

Returns:

The row, or None.

get_readonly_csv_file(file_path)

Reads a CSV file and returns its contents as a list of dictionaries, one per row.

The file is opened read-only, so reading it never modifies it.

Parameters:

file_path (str) – The path to the CSV file to read.

Returns:

The rows of the CSV file, one dictionary per row, keyed by the column headers.

Return type:

list[dict]

get_readonly_yaml_file(file_path)

Reads a YAML file and returns its contents as a dictionary.

The file is opened read-only, so reading it never modifies it.

Parameters:

file_path (str) – The path to the YAML file to read.

Returns:

The contents of the YAML file, parsed into a dictionary.

Return type:

dict

classmethod has_dependents(instance)

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 (PluginMeta) – 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 health_check_urls: list[str]

Returns a list of URL paths that are considered health check endpoints.

Returns:

List of health check URL path strings.

Return type:

list[str]

init(*args, **kwargs)

An optional method that can be called after initialization to perform any additional setup.

This is separate from __init__ to allow for more flexible initialization patterns.

Parameters:
  • args – Positional arguments passed to the init method.

  • kwargs – Keyword arguments passed to the init method.

Return type:

None

Returns:

None

init_manifest_from_data(manifest_class)

Build the broker’s manifest from the client’s manifest data, when the broker isn’t ready yet.

A broker with no manifest data, manifest or plugin is normal for a command that needs no resource, e.g. example-manifest, json-schema or get of a list, so that case is logged at DEBUG. A command that does need a ready broker still fails later with SAMBrokerErrorNotReady. The manifest data’s kind was checked when it was set.

Parameters:

manifest_class (Type[AbstractSAMBase]) – The Pydantic manifest model of this broker’s kind, e.g. SAMStaticPlugin.

Return type:

None

invalidate_cached_properties()

Invalidates all cached properties on the instance to force re-evaluation.

This method removes all attributes cached by @cached_property decorators from the instance’s __dict__. It is useful for testing or when the request object changes and you need to ensure that all dependent properties are recalculated.

Example:

from smarter.lib.django.request import SmarterRequestMixin

class Foo(SmarterRequestMixin):
    pass

foo = Foo(request)
foo.invalidate_cached_properties()
property ip_address: str | None

Get the client’s IP address from the request object.

This property attempts to extract the IP address from the request’s META dictionary, using the REMOTE_ADDR key.

Example:

request_mixin = SmarterRequestMixin(request)
ip = request_mixin.ip_address
print(ip)  # e.g., '192.168.1.100'
Returns:

The client’s IP address, the placeholder "ip_address" if REMOTE_ADDR is missing or empty, or None if the request has no META dictionary.

property is_authenticated: bool

Return True if the request’s user is authenticated.

Returns:

The request user’s is_authenticated, or False if there is no request or user, or checking it raises.

property is_config: bool

Return True if the URL resolves to a config endpoint.

Examples:

http://testserver/api/v1/cli/prompt/config/testc7098865f39202d5/
http://localhost:9357/workbench/example/config/?session_key=1aeee4c1f183354247f43f80261573da921b0167c7c843b28afd3cb5ebba0d9a
http://localhost:9357/api/v1/workbench/<int:llmclient_id>/prompt/config/
http://example.api.localhost:9357/config
Returns:

True if the URL is an llmclient url whose path includes config, otherwise False.

property is_dashboard: bool

Return True if the URL resolves to a dashboard endpoint.

Returns:

True if the URL’s path ends with /dashboard/, otherwise False.

property is_default_domain: bool

Return True if the URL is on the default api domain for the environment, e.g. api.alpha.platform.smarter.sh.

Returns:

True if the URL contains the environment’s api domain, otherwise False.

property is_environment_root_domain: bool

Return True if the URL resolves to the environment root domain.

Returns:

True if the URL’s host is the environment’s platform domain and its path is /, otherwise False.

is_internal_api_request(request)

Check if the request is an internal API request.

This method checks for a custom attribute on the request object that indicates whether the request is an internal API request. This can be used to bypass certain authentication or permission checks for internal requests.

Parameters:

request (HttpRequest) – The Django request object.

Return type:

bool

Returns:

True if it’s an internal API request, False otherwise.

property is_llmclient: bool

Return True if the URL resolves to an llmclient endpoint.

Conditions are checked in a lazy sequence to avoid unnecessary processing. The order matters: is_llmclient_named_url loads the url’s account as a side effect.

Examples:

http://localhost:9357/api/v1/prompt/1/prompt/
http://localhost:9357/api/v1/cli/prompt/example/
http://example.3141-5926-5359.api.localhost:9357/
http://localhost:9357/api/v1/llm-clients/1556/prompt/
http://localhost:9357/workbench/llm-clients/<str:hashed_id>/prompt/
http://localhost:9357/workbench/llm-clients/<str:hashed_id>/config/
http://localhost:9357/workbench/llm-clients/<str:hashed_id>/manifest/
Returns:

True if the request is qualified and its URL is a named, sandbox, smarter api or cli api llmclient url, otherwise False.

property is_llmclient_cli_api_url: bool

Return True if the URL is of the form http://localhost:9357/api/v1/cli/prompt/example/.

The expected path parts are:

['api', 'v1', 'cli', 'prompt', 'example']
Returns:

True if the URL matches the CLI llmclient API pattern, otherwise False.

property is_llmclient_named_url: bool

Return True if the url is a deployed LLMClient’s own host.

These are the forms of the url:

https://example-username.3141-5926-5359.api.example.com/
http://example-username.3141-5926-5359.api.localhost:9357/
http://example-username.3141-5926-5359.api.localhost:9357/config/
http://example-username.3141-5926-5359.api.localhost:9357/prompt/
http://example-username.3141-5926-5359.api.localhost:9357/jsi18n/

As a side effect, when the url has an account number and account is not set, the account is loaded from the account number.

Returns:

True if the URL matches the named llmclient pattern, otherwise False.

property is_llmclient_sandbox_url: bool

Return True if the URL is an llmclient sandbox endpoint.

Web console urls:

http://localhost:9357/workbench/llm-clients/<str:hashed_id>/prompt/
http://localhost:9357/workbench/llm-clients/<str:hashed_id>/config/
http://localhost:9357/workbench/llm-clients/<str:hashed_id>/manifest/

Api urls:

http://localhost:9357/api/v1/prompt/1/prompt/
Returns:

True if the URL matches an llmclient sandbox endpoint, otherwise False.

property is_llmclient_smarter_api_url: bool

Return True if the URL is a smarter api llmclient endpoint.

These are the forms of the url:

http://localhost:9357/api/v1/llm-clients/32/config/

http://localhost:9357/api/v1/workbench/1/prompt/
path_parts: ['api', 'v1', 'workbench', '<int:pk>', 'prompt']

http://localhost:9357/api/v1/llm-clients/1556/prompt/
path_parts: ['api', 'v1', 'llm-clients', '<int:pk>', 'prompt']

http://localhost:9357/api/v1/llm-clients/rMTAwMDAwNwx/prompt/
path_parts: ['api', 'v1', 'llm-clients', '<str:hashed_id>', 'prompt']
Returns:

True if the URL matches a smarter API llmclient endpoint, otherwise False.

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.

  • The client’s manifest data has an apiVersion, kind, metadata and spec.

  • 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_smarter_api: bool

Return True if the URL is of the form http://localhost:9357/api/v1/.

Examples:

path_parts: ['api', 'v1', 'llm-clients', '1', 'prompt']
http://api.localhost:9357/
Returns:

True if api is a segment of the URL’s path or a label of its host, otherwise False.

property is_valid: bool

True if the broker has a manifest, complete manifest data, or an ORM instance.

Returns:

Whether the broker was initialized from any of them.

property is_workbench: bool

Return True if the URL resolves to a workbench endpoint.

Returns:

True if the URL’s path ends with /workbench/, otherwise False.

json_response_err(command, e)

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)

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)

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)

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)

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)

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

Returns the manifest kind for this plugin broker.

This property provides the canonical string identifier for the SQL plugin manifest type, as defined by the constant MANIFEST_KIND. It is used to distinguish this broker’s manifest type from others in the Smarter API system.

Returns:

The manifest kind string for SQL plugins.

Return type:

str

Example:

broker = SAMSqlPluginBroker(manifest=my_manifest)
print(broker.kind)
# Output: "SqlPlugin"  # (or the value of MANIFEST_KIND)

See also

MANIFEST_KIND SAMSqlPluginBroker.manifest

kind_setter(value)

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 it has the manifest data’s name but before name is set. This keeps them from reporting no name.

Returns:

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

log_abstract_broker_state()

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

log_ready_status()

Log the ready status of the instance, at INFO.

Return type:

None

Returns:

None.

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

Retrieve logs for the SQL plugin (not implemented).

This is not implemented for SQL plugins.

Raises:

SAMBrokerErrorNotImplemented: Always raised to indicate that this method is not implemented.

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

  • args – Additional positional arguments (unused).

  • kwargs – Additional keyword arguments (unused).

Returns:

A SmarterJournaledJsonResponse indicating that the method is not implemented.

Return type:

SmarterJournaledJsonResponse

property manifest: SAMSqlPlugin | None

Returns the SQL plugin manifest as a validated Pydantic model instance.

This property constructs and caches a SAMSqlPlugin object using data from the client’s manifest data, including API version, kind, metadata, specification, and status. Child models (such as metadata, spec, and status) are automatically initialized by Pydantic.

If there is manifest data, the manifest is created from it and cached for future access. If the manifest has already been initialized, the cached instance is returned.

Returns:

The initialized SQL plugin manifest as a Pydantic model, or None if not available.

Return type:

Optional[SAMSqlPlugin]

Example:

broker = SAMSqlPluginBroker(manifest=None)
manifest = broker.manifest
if manifest:
    print(manifest.apiVersion)

See also

SAMSqlPlugin SAMSqlPluginBroker.kind SAMPluginCommonMetadata SAMSqlPluginSpec SAMPluginCommonStatus

property manifest_data: dict[str, Any] | None

The client’s manifest, as a dict, if it has every section that a manifest requires.

A broker’s manifest validates this dict with the kind’s Pydantic model. Manifest data that lacks an apiVersion, a kind, metadata or a spec, or has an empty one, is not a manifest yet, so it is None here, and the broker is not ready.

Returns:

The manifest data, or None if there is none, or it is incomplete.

manifest_data_setter(value)

Set the client’s manifest, as a dict.

Parameters:

value (dict[str, Any] | None) – The manifest, as a dict, e.g. from parse_manifest(), or None to unset it.

Raises:
  • SmarterValueError – If the value is not a dict.

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

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

Return type:

None

property manifest_metadata: dict[str, Any] | None

The metadata of the client’s manifest data.

Returns:

The metadata, or None if there is no manifest data, or it has no metadata.

property manifest_sections: dict[str, Any]

The apiVersion, kind, metadata and spec of the client’s manifest data, to validate a SAM model with.

A broker builds its manifest with, e.g., SAMGuardrail.model_validate(self.manifest_sections). The client’s status is left out, because it is read-only. A section that the manifest data doesn’t have is None, which the model’s validation rejects. Each call returns a new dict, which a broker may add the status to.

Returns:

A dict with the keys apiVersion, kind, metadata and spec.

manifest_setter(value)

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

property manifest_status: dict[str, Any] | None

The status of the client’s manifest data.

Returns:

The status, or None if there is no manifest data, or it has no status.

manifest_to_django_orm()

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.

mask_string(string='', mask_char='*', mask_length=4, string_length=8)

Masks a string for secure logging.

This utility function masks all but the last unmasked_chars characters of the input string, replacing them with asterisks. It is useful for logging sensitive information like API keys or passwords.

Parameters:
  • string (str | None) – The string to be masked.

  • mask_char (str) – The character used for masking.

  • mask_length (int) – The number of characters to mask.

  • string_length (int) – The length of the string to consider for masking.

Returns:

The masked string.

Return type:

str

property missing_manifest_sections: list[str]

The sections that the client’s manifest data lacks, or has empty, of apiVersion, kind, metadata and spec.

Returns:

The missing sections’ keys, e.g. ["spec"], or an empty list if there is no manifest data, or it has every section.

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 manifest data’s 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)

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: PluginDataBase | None

Return the Django ORM model instance for the broker.

Returns:

The Django ORM model instance for the broker.

Return type:

Optional[TimestampedModel]

property orm_meta_instance: PluginMeta | None

Return the PluginMeta of this broker, if it is of this broker’s plugin class.

Returns:

The PluginMeta instance, or None.

orm_meta_instance_setter()

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()

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.

property parsed_url: ParseResult | None

Expose the private ParseResult URL object as a public property.

Example:

request_mixin = SmarterRequestMixin(request)
parsed = request_mixin.parsed_url
print(parsed.netloc)  # e.g., 'example.com'
Returns:

The parsed URL, or None if there is no url.

property path: str | None

Extract the path from the URL.

For example, this url returns '/llm-client/':

https://hr.3141-5926-5359.alpha.api.example.com/llm-client/
Returns:

The path, / for an empty path, or None if there is no request or url.

property plugin: SqlPlugin | None

Returns the initialized SqlPlugin instance for this broker.

This property creates and caches a SqlPlugin object using the current broker’s metadata, user profile, manifest, and name. If the plugin has already been initialized, the cached instance is returned.

Returns:

The initialized SqlPlugin instance, or None if not available.

Return type:

Optional[SqlPlugin]

Example:

broker = SAMSqlPluginBroker(manifest=my_manifest)
plugin = broker.plugin
if plugin and plugin.ready:
    plugin.create()
    plugin.save()
plugin_class: str | None = 'sql'

The PluginMeta.plugin_class of this broker’s kind, e.g. api for ApiPlugin.

Plugin names are unique per user profile, not per plugin class, so every PluginMeta lookup is filtered by it. Otherwise get of one plugin kind returns the plugins of every kind, and describe of a plugin with another kind’s broker fails.

property plugin_data: PluginDataSql | None

Returns the PluginDataSql ORM object associated with this broker.

This property retrieves and caches the PluginDataSql instance for the current plugin, which is used to store and manage plugin-specific data in the database. If the object does not exist, a warning is logged and None is returned.

Returns:

The PluginDataSql object for this broker, or None if not available.

Return type:

Optional[PluginDataSql]

Raises:

PluginDataSql.DoesNotExist if the object is not found in the database.

Example:

broker = SAMSqlPluginBroker(manifest=my_manifest)
data = broker.plugin_data
if data:
    print(data.connection)

See also

PluginDataSql SAMSqlPluginBroker.plugin_meta

plugin_data_orm2pydantic()[source]

Overrides the parent method to map SQL plugin data from ORM to Pydantic.

Converts the plugin data from the Django ORM model format to the Pydantic manifest format.

This method constructs a SqlData Pydantic model using the data associated with the current plugin_meta. It retrieves the data using the ORM-to-Pydantic conversion method.

Parameters:

parameters (dict) –

An OpenAI API-compliant dictionary of parameters to pass to the API call, e.g.:

{
    'type': 'object',
    'required': ['username'],
    'properties': {
        'unit': {
            'enum': ['Celsius', 'Fahrenheit'],
            'type': 'string',
            'default': 'Celsius',
            'description': 'The temperature unit to use.'
        },
        'username': {
            'type': 'string',
            'default': 'admin',
            'description': 'The username to query.'
        }
    },
    'additionalProperties': False
}

Returns:

The plugin data as a Pydantic model.

Return type:

SqlData | None

Example

broker = SAMSqlPluginBroker()
sql_data = broker.plugin_data_orm2pydantic()
print(sql_data.model_dump_json())
Raises:

SAMPluginBrokerError – If there is an error retrieving or converting the plugin data.

See also

  • SqlData

plugin_init()[source]

Initialize the SQL plugin for this broker.

This method creates an instance of the SqlPlugin class using the current broker’s metadata, user profile, manifest, and name. It assigns the created plugin to the broker’s internal _plugin attribute for future access.

Return type:

None

Returns:

None

Example:

broker = SAMSqlPluginBroker(manifest=my_manifest)
broker.plugin_init()
plugin = broker.plugin
if plugin.ready:
    plugin.create()
    plugin.save()
property plugin_meta: PluginMeta | None

Retrieve the PluginMeta ORM instance associated with this broker.

This property returns the plugin metadata object for the current plugin, resolving it by name and account if not already cached. If the metadata cannot be found, None is returned.

Returns:

The PluginMeta instance for this broker, or None if unavailable.

Return type:

Optional[PluginMeta]

Note

The metadata is cached after the first successful lookup for efficient repeated access.

Warning

If the plugin metadata does not exist in the database, no exception is raised; None is returned.

See also

PluginMeta SAMPluginBaseBroker.plugin() SAMPluginBaseBroker.plugin_data()

Example usage:

meta = broker.plugin_meta
if meta:
    print(meta.name, meta.account)
else:
    print("No plugin metadata found.")
Setter accepts:

PluginMeta

plugin_meta_queryset()

Return the PluginMeta rows of this broker’s plugin class.

Return type:

QuerySet[PluginMeta]

Returns:

The PluginMeta rows whose plugin_class is plugin_class.

plugin_metadata_orm2pydantic()

Convert plugin metadata from the Django ORM model format to the Pydantic manifest format.

This method transforms the plugin metadata, typically retrieved as a dictionary from the Django ORM (PluginMeta), into a Pydantic model (SAMPluginCommonMetadata). It ensures the metadata is properly camel-cased and validated for use in manifest serialization and API responses.

Returns:

The plugin metadata as a Pydantic model.

Return type:

SAMPluginCommonMetadata

Raises:

SAMPluginBrokerError – If the plugin metadata or plugin instance is not found, or if conversion fails.

Error

Any error during conversion, such as missing metadata or invalid format, is wrapped and raised as SAMPluginBrokerError.

See also

PluginMeta SAMPluginCommonMetadata SAMPluginBaseBroker.plugin_meta() SAMPluginBaseBroker.plugin()

Example usage:

metadata = broker.plugin_metadata_orm2pydantic()
print(metadata.name, metadata.description)
property plugin_prompt_orm: PluginPrompt | None

Retrieve the PluginPrompt ORM instance associated with this broker.

This property returns the plugin prompt object for the current plugin metadata. If the prompt cannot be found, None is returned.

Returns:

The PluginPrompt instance for this broker, or None if unavailable.

Return type:

Optional[PluginPrompt]

Note

The prompt is retrieved based on the associated PluginMeta.

plugin_prompt_orm2pydantic()

Convert plugin prompt data from the Django ORM model format to the Pydantic manifest format.

This method transforms the plugin prompt data, typically retrieved as a dictionary from the Django ORM (PluginPrompt), into a Pydantic model (SAMPluginCommonSpecPrompt). It ensures the prompt data is properly camel-cased and validated for use in manifest serialization and API responses.

Returns:

The plugin prompt data as a Pydantic model.

Return type:

SAMPluginCommonSpecPrompt

Raises:

SAMPluginBrokerError – If the plugin prompt or plugin instance is not found, or if conversion fails.

Error

Any error during conversion, such as missing prompt data or invalid format, is wrapped and raised as SAMPluginBrokerError.

See also

PluginPrompt SAMPluginCommonSpecPrompt SAMPluginBaseBroker.plugin_prompt() SAMPluginBaseBroker.plugin()

Example usage:

prompt = broker.plugin_prompt_orm2pydantic()
print(prompt.template, prompt.variables)
plugin_selector_orm2pydantic()

Convert plugin selector data from the Django ORM model format to the Pydantic manifest format.

This method transforms the plugin selector data, typically retrieved as a dictionary from the Django ORM (PluginSelector), into a Pydantic model (SAMPluginCommonSpecSelector). It ensures the selector data is properly camel-cased and validated for use in manifest serialization and API responses.

Returns:

The plugin selector data as a Pydantic model.

Return type:

SAMPluginCommonSpecSelector

Raises:

SAMPluginBrokerError – If the plugin selector, plugin metadata, or plugin instance is not found, or if conversion fails.

Error

Any error during conversion, such as missing selector data or invalid format, is wrapped and raised as SAMPluginBrokerError.

See also

PluginSelector SAMPluginCommonSpecSelector SAMPluginBaseBroker.plugin() SAMPluginBaseBroker.plugin_meta()

Example usage:

selector = broker.plugin_selector_orm2pydantic()
print(selector.type, selector.options)
plugin_sql_spec_orm2pydantic()[source]

Convert the static plugin specification from the Django ORM model format to the Pydantic manifest format.

This method constructs a SAMPluginStaticSpec Pydantic model using the prompt, selector, and static data associated with the current plugin_meta. It retrieves each component using their respective ORM-to-Pydantic conversion methods.

Returns:

The static plugin specification as a Pydantic model.

Return type:

SAMSqlPluginSpec | None

Example:

broker = SAMStaticPluginBroker()
static_spec = broker.plugin_static_spec_orm2pydantic()
print(static_spec.model_dump_json())
Raises:

SAMPluginBrokerError – If there is an error retrieving or converting any component of the plugin specification.

See also

  • SAMPluginStaticSpec

  • SAMPluginCommonSpecPrompt

  • SAMPluginCommonSpecSelector

  • SAMPluginStaticSpecData

plugin_status_pydantic()

Get the plugin status as a Pydantic model.

This method retrieves the plugin status from the Django ORM model and converts it into a Pydantic model (SAMPluginCommonStatus). It ensures that the status information is properly formatted for use in manifest serialization and API responses.

Returns:

The plugin status as a Pydantic model.

Return type:

SAMPluginCommonStatus | None

See also

SAMPluginCommonStatus SAMPluginBaseBroker.plugin_meta() SAMPluginBaseBroker.plugin()

Example usage:

status = broker.plugin_status_pydantic()
print(status.active, status.last_updated)
prompt(request, *args, **kwargs)[source]

Prompt with the SQL plugin (not implemented).

This is not implemented for SQL plugins.

Raises:

SAMBrokerErrorNotImplemented: Always raised to indicate that this method is not implemented.

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

  • args – Additional positional arguments (unused).

  • kwargs – Additional keyword arguments (unused).

Returns:

A SmarterJournaledJsonResponse indicating that the method is not implemented.

Return type:

SmarterJournaledJsonResponse

property qualified_request: bool

A cursory screening of the WSGI request object to look for any disqualifying conditions that confirm this is not a request that we are interested in.

The request is considered “qualified” if all of the following are true:

  • The request object (self._smarter_request) is present.

  • The URL path is present and non-empty.

  • The request does not originate from an internal AWS Kubernetes subnet (netloc starts with 192.168).

  • The path is not in the list of amnesty_urls.

  • The path does not start with /admin/.

  • The path does not start with /docs/.

  • The path does not end with a static file extension (see STATIC_FILE_EXTENSIONS).

Example:

# True case: a valid llmclient request
request_mixin = SmarterRequestMixin(request)
if request_mixin.qualified_request:
    print("This is a qualified llmclient request.")

# False case: a static asset or admin/docs request
static_request = SmarterRequestMixin(static_asset_request)
if not static_request.qualified_request:
    print("This request is not of interest.")
Returns:

True if the request passes all checks and is of interest, otherwise False.

raise_for_unknown_keys(manifest)

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)

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

Check if the broker is ready for operations.

This property determines whether the broker has been properly initialized and is ready to perform its functions. A broker is considered ready if it has a valid manifest loaded, either from raw data, a manifest dict, or existing Django ORM models.

Returns:

True if the broker is ready, False otherwise.

Return type:

bool

property ready_state: str

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

Returns:

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

recursive_sort_dict(data)

Recursively sorts a dictionary by its keys.

This method takes a dictionary and returns a new dictionary with all keys sorted in ascending order. If any values are also dictionaries, they will be sorted recursively as well.

Parameters:

data (dict[str, Any]) – The dictionary to sort.

Returns:

A new dictionary with all keys sorted.

Return type:

dict[str, Any]

classmethod references(instance)

Return the resources that a plugin uses.

Every plugin uses the Provider that its spec.prompt.provider names. An SqlPlugin and an ApiPlugin also use their Connection, and a WebsearchPlugin the Secret of its search api key.

Parameters:

instance (PluginMeta) – The plugin’s PluginMeta.

Returns:

Its Provider, Connection and Secret, of those that it has.

Return type:

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

property request: HttpRequest | None

Return the request object.

Returns:

The request object.

property required_cache_key: str

Return cache_key, for code that reads or writes the cache with it.

cache_key is None only without a request, which a view always has. Rather than read or write the cache under the key None, which every such caller would share, this raises.

Returns:

The cache key.

Raises:

SmarterValueError – If there is no request, so no cache key.

rfc1034_compliant_str(name)

Converts a string to an RFC 1034 compliant format.

This method takes a string and converts it to a format that complies with RFC 1034, which is commonly used for domain names. It replaces invalid characters with hyphens and ensures the resulting string is lowercase.

Parameters:

name (str) – The string to convert to RFC 1034 compliant format.

Returns:

The converted string in RFC 1034 compliant format.

Return type:

str

rfc1034_compliant_to_snake(name)

Converts an RFC 1034 compliant string to snake_case.

This method takes a string in RFC 1034 compliant format and converts it to snake_case. It replaces hyphens with underscores and ensures the resulting string is lowercase.

Parameters:

name (str) – The RFC 1034 compliant string to convert.

Returns:

The converted string in snake_case.

Return type:

str

property root_domain: str | None

Extract the root domain from the URL.

Example:

request_mixin = SmarterRequestMixin(request)
print(request_mixin.root_domain)
# For 'https://hr.3141-5926-5359.alpha.api.example.com/llm-client/' → 'example.com'
# For 'http://localhost:9357/' → 'localhost'
Returns:

The root domain, or None if not found.

schema(request, *args, **kwargs)

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)

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

property session_key: str

Getter for the session_key property.

The session_key is a unique identifier for a prompt session. It is used to identify the prompt session across multiple requests. If the session_key is not already set, it attempts to find it in the request (see find_session_key()). Barring that, it generates a new one.

Example:

request_mixin = SmarterRequestMixin(request)
session_key = request_mixin.session_key
print(session_key)  # e.g., '38486326c21ef4bcb7e7bc305bdb062f16ee97ed8d2462dedb4565c860cd8ecc'
Returns:

The session key as a string.

set_and_verify_name_param(*args, command=None, **kwargs)

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

set_is_internal_api_request(request, value=True)

Set the internal API request attribute on the request object.

This method allows you to mark a request as an internal API request by setting a custom attribute on the request object. This can be used in middleware or views to indicate that the request should be treated as internal.

Parameters:
  • request (HttpRequest) – The Django request object, or a DRF request, whose wrapped Django request is flagged too.

  • value (bool) – The value to set for the internal API request attribute (default is True).

Return type:

HttpRequest

Returns:

The modified request object.

Raises:

SmarterValueError – If request is not a Django HttpRequest or a DRF Request.

setup(*args, **kwargs)

This method is called by Django views during initialization.

It attempts to resolve the account and user information from the request object if it hasn’t already been set.

Parameters:
  • args – Positional arguments passed to the view.

  • kwargs – Keyword arguments passed to the view, may include ‘request’.

Returns:

The result of the superclass setup method.

Return type:

None

smarter_build_absolute_uri(request)

Attempts to get the absolute URI from a request object.

This utility function tries to retrieve the request URL from any valid child class of django.http.HttpRequest. It is especially useful in unit tests or scenarios where the request object may not implement build_absolute_uri().

Parameters:

request (HttpRequest) – The request object.

Returns:

The absolute request URL.

Return type:

str | None

Raises:

SmarterValueError – If the URI cannot be built from the request.

property smarter_capabilities: str | None

Get the smarter capabilities from the request.

This property checks for the “X-Smarter-Capabilities” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
capabilities = request_mixin.smarter_capabilities
Returns:

The value of the “X-Smarter-Capabilities” header as a string, or None if not present.

property smarter_client: str | None

Get the smarter client name from the request.

This property checks for the “X-Smarter-Client” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
client_name = request_mixin.smarter_client
Returns:

The value of the “X-Smarter-Client” header as a string, or None if not present.

property smarter_client_type: str | None

Get the smarter client type from the request.

This property checks for the “X-Smarter-ClientType” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
client_type = request_mixin.smarter_client_type
Returns:

The value of the “X-Smarter-ClientType” header as a string, or None if not present.

property smarter_client_version: str | None

Get the smarter client version from the request.

This property checks for the “X-Smarter-ClientVersion” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
client_version = request_mixin.smarter_client_version
Returns:

The value of the “X-Smarter-ClientVersion” header as a string, or None if not present.

property smarter_request: Request | HttpRequest | ASGIRequest | MagicMock | None

Returns the current request object.

This property is named to avoid potential name collisions in child classes. This property is preferred over standard Django request types in that it more elegantly resolves idiosyncratic usage like Unit tests, Sphinx docs, and other non-standard request objects.

Example:

request_mixin = SmarterRequestMixin(request)
req = request_mixin.smarter_request
Returns:

The current request object.

property smarter_request_id: str | None

Get the smarter request ID from the request.

This property checks for the “X-Smarter-RequestId” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
request_id = request_mixin.smarter_request_id
Returns:

The value of the “X-Smarter-RequestId” header as a string, or None if not present.

property smarter_request_llmclient_id: int | None

Extract the llmclient id from the URL.

For example, for this url the property decodes the hashed id rMTAwMDAyNwx into the llmclient’s id:

http://localhost:9357/workbench/llm-clients/rMTAwMDAyNwx/prompt/
Returns:

The llmclient id as an integer, or None if not found. A named url and a sandbox url without a hashed id return None.

property smarter_request_llmclient_name: str | None

Extract the llmclient name from the URL.

For example, this url returns "example":

http://example.3141-5926-5359.api.localhost:9357/config
Returns:

The llmclient name as a string, or None if not found.

smarter_request_setup(*args, request=None, user=None, **kwargs)

Initialize the SmarterRequestMixin with the request and user.

A view calls it from its own setup(), after Django’s View.setup(). It isn’t named setup(), because Django’s takes the request positionally, and a view inherits both. It initializes the request and user attributes of the mixin. The request is set using the smarter_request property setter, which also handles URL parsing and user authentication.

Parameters:
  • args – Positional arguments passed to the setup method.

  • request (HttpRequest | None) – The HTTP request object to be associated with this mixin instance.

  • user (AnonymousUser | User | None) – The user associated with the request, if available.

  • kwargs – Keyword arguments passed to the setup method.

Return type:

None

property smarter_request_user: AnonymousUser | User | None

Returns the user associated with the request.

This property is named to avoid potential name collisions in child classes. It retrieves the user from the request object if available.

Example:

request_mixin = SmarterRequestMixin(request)
user = request_mixin.smarter_request_user
Returns:

The user associated with the request, or None if not available.

sorted_dict(data)

Returns a new dictionary with keys sorted.

Parameters:

data (dict[str, Any]) – The dictionary to sort.

Returns:

A new dictionary with sorted keys.

Return type:

dict[str, Any]

property srm_formatted_class_name: str

Returns the class name in a formatted string along with the name of this mixin.

Returns:

Formatted class name string.

property srm_ready: bool

Returns True if the request mixin is srm_ready for processing.

This is a convenience property to check if the request is srm_ready.

Returns:

True if the request mixin is srm_ready, False otherwise.

property subdomain: str | None

Extract the subdomain from the URL.

Example:

request_mixin = SmarterRequestMixin(request)
sub = request_mixin.subdomain
print(sub)  # e.g., 'hr.3141-5926-5359.alpha' for
            # 'https://hr.3141-5926-5359.alpha.api.example.com/llm-client/'
Returns:

The subdomain, or None if not found.

static tags_changed(instance, tags)

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.

property timestamp: datetime

Create a consistent timestamp based on the time that this object was instantiated.

Example:

request_mixin = SmarterRequestMixin(request)
ts = request_mixin.timestamp
print(ts)  # e.g., 2025-12-01 12:34:56.789012
Returns:

The time at which this object was instantiated.

to_camel_case(data, convert_values=False)

Converts a snake_case string to camelCase.

This method takes a string in snake_case format and converts it to camelCase. It is useful for standardizing naming conventions across different formats.

Parameters:
  • data (ConvertibleCaseT) – The snake_case string to convert.

  • convert_values (bool) – Whether to convert the values of dictionaries and lists recursively.

Returns:

The converted string in camelCase.

Return type:

ConvertibleCaseT

to_json()

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.

to_snake_case(data, convert_values=False)

Converts a camelCase or PascalCase string to snake_case.

This method takes a string in camelCase or PascalCase format and converts it to snake_case. It is useful for standardizing naming conventions across different formats.

Parameters:
  • data (ConvertibleCaseT) – The camelCase or PascalCase string to convert.

  • convert_values (bool) – Whether to convert the values of dictionaries and lists recursively.

Returns:

The converted string in snake_case.

Return type:

ConvertibleCaseT

property uid: str | None

Unique identifier for the client.

This is assumed to be a combination of the machine MAC address and the hostname.

Example:

request_mixin = SmarterRequestMixin(request)
uid = request_mixin.uid
print(uid)  # e.g., '00:1A:2B:3C:4D:5E-myhost'
Returns:

The client UID as a string, or None if not available.

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

Undeploy the SQL plugin (not implemented).

This is not implemented for SQL plugins.

Raises:

SAMBrokerErrorNotImplemented: Always raised to indicate that this method is not implemented.

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

  • args – Additional positional arguments (unused).

  • kwargs – Additional keyword arguments (unused).

Returns:

A SmarterJournaledJsonResponse indicating that the method is not implemented.

Return type:

SmarterJournaledJsonResponse

property unformatted_class_name: str

Returns the raw class name without formatting.

Returns:

The unformatted class name as a string.

Return type:

str

This is useful for logging or serialization where the plain class name is needed.

property unique_client_string: str

Generate a unique string based on several request attributes.

This string is used for generating session_key and client_key.

The unique string is composed of:

  • Account number, when there is an account

  • URL

  • User agent

  • IP address

Example:

request_mixin = SmarterRequestMixin(request)
unique_str = request_mixin.unique_client_string
print(unique_str)
Returns:

A unique string representing the client and request context.

property uri: str | None

Return the full uri of the request.

Returns:

The full uri of the request.

property url: str | None

The string representation of the ParseResult object stored in _parsed_url.

Example:

request_mixin = SmarterRequestMixin(request)
url_str = request_mixin.url
print(url_str)  # e.g., 'https://example.com/path/'
Returns:

The URL as a string.

property url_account_number: str | None

Extract the account number from the URL, using SmarterValidator.VALID_ACCOUNT_NUMBER_PATTERN.

For example, this url returns "3141-5926-5359":

http://example.3141-5926-5359.api.localhost:9357/config
Returns:

The account number as a string, or None if there is no request, the request is not qualified, or the url has no account number.

property url_path_parts: list[str]

Extract the path parts from the URL.

Example:

request_mixin = SmarterRequestMixin(request)
parts = request_mixin.url_path_parts
print(parts)  # e.g., ['api', 'v1', 'workbench', '1', 'prompt']
Returns:

A list of strings representing each part of the URL path.

property user: AnonymousUser | User | None

Returns the user.

Handle lazy instantiation from user_profile or account.

Returns:

The user.

Return type:

User or None

property user_agent: str | None

Get the client’s user agent string from the request object.

This property attempts to extract the user agent from the request’s META dictionary, using the HTTP_USER_AGENT key.

Example:

request_mixin = SmarterRequestMixin(request)
ua = request_mixin.user_agent
print(ua)  # e.g., 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)...'
Returns:

The client’s user agent string, the placeholder "user_agent" if the header is missing, or None if the request has no META dictionary.

property user_profile: UserProfile | None

Returns the user_profile for the current user.

Handle lazy instantiation from user or account.

Returns:

The user_profile for the current user.

Return type:

UserProfile or None

classmethod validation_errors(manifest, external_checks=True)

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)

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)

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)

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.