Brokers
Smarter API LLMClient Manifest handler.
- class smarter.apps.llmclient.manifest.brokers.llmclient.LLMClientSerializer(*args, **kwargs)[source]
Bases:
ModelSerializerDjango ORM model serializer for get().
- class smarter.apps.llmclient.manifest.brokers.llmclient.SAMLLMClientBroker(*args, **kwargs)[source]
Bases:
AbstractBroker[LLMClient,LLMClient]Broker for
SAMLLMClient manifests.This class provides a high-level abstraction for managing llmclient manifests within the Smarter platform. It acts as the central coordinator for the lifecycle of llmclient manifests, bridging the gap between declarative YAML files and persistent application state.
The broker is responsible for:
Managing the lifecycle of llmclient manifests, including loading, validation, and parsing of YAML files.
Initializing Pydantic models from manifest data to ensure robust schema validation and serialization.
Integrating with Django ORM models that represent llmclient manifests, supporting creation, update, deletion, and querying of database records.
Transforming data between Django ORM models and Pydantic models to enable seamless conversion between database and API representations.
Coordinating composite models, such as LLMClient, LLMClientAPIKey, LLMClientPlugin, and LLMClientExtensions, to ensure all components of an llmclient are synchronized according to the manifest specification.
Ensuring atomic and consistent application of changes using Django’s transaction management.
Providing detailed logging and error handling integrated with the Smarter platform’s diagnostics systems.
This broker is a key component in the deployment, configuration, and lifecycle management of llmclients in the Smarter Framework.
- property ORMMetaModelClass: Type[LLMClient]
Return the Django ORM meta model class for the broker.
- Returns:
The Django ORM meta model class definition for the broker.
- Return type:
Type[LLMClient]
- property ORMModelClass: Type[LLMClient]
The Django ORM model class for the LLMClient.
- Returns:
The LLMClient Django ORM model class.
- Return type:
Type[LLMClient]
- property SerializerClass: Type[LLMClientSerializer]
The Django ORM model serializer class for the LLMClient.
- Returns:
The LLMClient Django ORM model serializer class.
- Return type:
Type[ModelSerializer]
- __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
nameand 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,accountanduser_profile, and the rest, which are passed on toSmarterRequestMixin.
- Raises:
SmarterValueError – If the kind, name or manifest is invalid.
SAMBrokerError – If the manifest’s kind is not the broker’s kind.
- apply(request, *args, **kwargs)[source]
Apply the manifest.
copy the manifest data to the Django ORM model and save the model to the database. Note that there are fields included in the manifest that are not editable and are therefore removed from the Django ORM model dict prior to attempting the save() command. These fields are defined in the readonly_fields list.
LLMClient is a composite model that includes the LLMClient, LLMClientAPIKey, LLMClientPlugin and LLMClientExtensions models. All of these are represented in the manifest spec and are created or updated as needed.
Note
tags are handled separately because they are of type TaggableManager and require a different method to set them.
- Return type:
- apply_vectorsearches(command)[source]
Link the LLMClient to the Vectorsearches that its manifest’s
spec.vectorsearcheslists, and only those.- Parameters:
command (
SmarterJournalCliCommands) – The journal command, for errors.- Return type:
- Returns:
True if a Vectorsearch was linked or unlinked.
- Raises:
SAMBrokerErrorNotFound – If a listed Vectorsearch doesn’t exist, or isn’t shared with the user.
- cache_invalidations()[source]
Handle broker specific cache invalidation logic.
We should invalidate any cached objects that are related to the LLMClient when any mutation occurs. In this case, we need to invalidate the LLMClient cache itself, but also any related objects such as the plugins, extensions and api keys.
- Return type:
- delete(request, *args, **kwargs)[source]
Delete the LLMClient, after checking that no Orchestrator depends on it.
Invalidates the LLMClient’s caches before the delete, while it still has an id.
- Parameters:
request (
HttpRequest) – The HTTP request.args – Positional arguments (unused).
kwargs – Keyword arguments (unused).
- Return type:
- Returns:
A successful response with empty data.
- Raises:
SAMBrokerErrorNotReady – if the broker has no name.
SAMBrokerErrorNotFound – if the LLMClient does not exist.
SAMLLMClientBrokerError – if the delete fails.
- dependencies()[source]
Return brokers for the Orchestrators that use this LLMClient.
An LLMClient’s Prompts are its chat history, not dependencies, so they are deleted with it.
- Returns:
A broker for each Orchestrator that lists this LLMClient in its
spec.llmClients.- Return type:
- classmethod dependents(instance)[source]
Return the Orchestrators that use an LLMClient.
An LLMClient’s Prompts are its chat history, not dependencies, so they are deleted with it.
- deploy(request, *args, **kwargs)[source]
Set the LLMClient’s
deployedflag and save it.When the flag changes,
LLMClient.save()sendsllmclient_deploy, whose receiver queues thedeploy_default_apiCelery task.- Parameters:
request (
HttpRequest) – The HTTP request.args – Positional arguments (unused).
kwargs – Keyword arguments (unused).
- Return type:
- Returns:
A successful response with empty data.
- Raises:
SAMBrokerErrorNotReady – if the broker has no name.
SAMBrokerErrorNotFound – if the LLMClient does not exist.
SAMLLMClientBrokerError – if the save fails.
- deployable: ClassVar[bool] = True
True when the broker implements
deploy().The cli api’s
resourcescommand reports it as each kind’sDeployable, and the smarter cli offersdeployandundeploycommands for those kinds. A broker that sets it must overridedeploy();undeploy()may still raiseSAMBrokerErrorNotImplemented, as CustomDomain’s and LLMHostCompute’s do.
- describe(request, *args, **kwargs)[source]
Return the LLMClient as a manifest.
- Parameters:
request (
HttpRequest) – The HTTP request.args – Positional arguments (unused).
kwargs – Keyword arguments (unused).
- Return type:
- Returns:
A response whose data is the LLMClient’s manifest dict.
- Raises:
SAMBrokerErrorNotReady – if the broker has no name.
SAMBrokerErrorNotFound – if the LLMClient does not exist.
SAMLLMClientBrokerError – if the manifest cannot be built.
- django_orm_to_manifest_dict()[source]
Transform the Django ORM LLMClient model instance into a dictionary compatible with the Smarter API LLMClient manifest format.
This method converts the current LLMClient ORM model and its related resources (plugins, extensions, API key) into a dictionary structure that matches the expected schema for a Pydantic manifest. The conversion includes renaming fields from snake_case to camelCase, removing internal-only fields, and assembling metadata, spec, and status sections as required by the manifest.
The resulting dictionary contains all configuration, metadata, plugin, function, and status information necessary to reconstruct the manifest for the llmclient. This enables seamless round-trip conversion between database state and manifest representation.
If the LLMClient model is not available, the method logs a warning and returns
None. If the conversion fails, an exception is raised to indicate the error.- Returns:
A dictionary representing the Smarter API LLMClient manifest, or
Noneif the LLMClient model is not set.- Return type:
- Raises:
SAMLLMClientBrokerError – If the ORM model cannot be converted to a manifest dictionary.
See also:
smarter.apps.llmclient.manifest.brokers.llmclient.SAMLLMClientBroker.manifest_to_django_orm()smarter.apps.llmclient.manifest.models.llmclient.SAMLLMClientsmarter.apps.llmclient.manifest.models.llmclient.metadata.SAMLLMClientMetadatasmarter.apps.llmclient.manifest.models.llmclient.spec.SAMLLMClientSpecsmarter.apps.llmclient.manifest.models.llmclient.status.SAMLLMClientStatus
- example_manifest(request, *args, **kwargs)[source]
Return an example manifest for the Smarter API LLMClient.
- Returns:
A JSON response containing an example Smarter API LLMClient manifest.
- Return type:
See also:
smarter.apps.llmclient.manifest.models.llmclient.SAMLLMClientsmarter.lib.manifest.enumSAMKeyssmarter.apps.llmclient.manifest.enum.SAMMetadataKeyssmarter.apps.llmclient.manifest.enum.SCLIResponseGetsmarter.apps.llmclient.manifest.enum.SCLIResponseGetDatasmarter.common.conf.settings.Settings.llm_default_system_role
- property extensions: List[str] | None
The slugs of the Extensions linked to the LLMClient that this broker manages.
- Returns:
The slugs, or
Noneif there is no LLMClient.- Return type:
Optional[List[str]]
- forget_llmclient_on_failure()[source]
Drop the broker’s cached LLMClient when the block it wraps raises.
Used inside
apply()’s transaction. The rollback undoes the LLMClient’s row, or its changed fields, in the database, but not the instance that the broker cached, which would then describe an LLMClient that doesn’t exist, or values that weren’t saved. Without it, the next read ofllmclientreads the database again.
- property formatted_class_name: str
Returns a formatted string representing the class name for logging purposes.
This property generates a human-readable class name that is used to improve the clarity and consistency of log messages throughout the broker. The formatted class name includes the parent class name and appends the specific broker class identifier, making it easier to trace log entries back to their source within the codebase.
The formatted class name is especially useful in environments where multiple brokers or components are active, as it helps distinguish log messages and aids in debugging and monitoring application behavior.
- Returns:
A string containing the formatted class name, suitable for use in log output.
- Return type:
- get(request, *args, **kwargs)[source]
List the account’s LLMClients that the user may see, optionally filtered by name and annotations.
Returns at most
MAX_RESULTSLLMClients, ordered by name, each serialized withLLMClientSerializerand camel-cased.- Parameters:
request (
HttpRequest) – The HTTP request.args – Positional arguments (unused).
kwargs – Query parameters:
nameand the annotation selector.
- Return type:
- Returns:
A response with the column titles and the serialized LLMClients.
- Raises:
SAMLLMClientBrokerError – if an LLMClient fails to serialize.
- property kind: str
Returns the manifest kind for the Smarter API LLMClient.
This property provides the specific kind identifier used to classify the Smarter API LLMClient manifest within the Smarter platform. The kind is a key component of the manifest schema, allowing the system to recognize and process llmclient manifests appropriately. The kind value is defined as a constant in the llmclient manifest model and is used throughout the broker to ensure consistency when handling llmclient manifests.
- Returns:
The manifest kind string for the Smarter API LLMClient.
- Return type:
Important
The kind property is essential for manifest validation, routing, and processing within the Smarter platform.
- property llmclient: LLMClient | None
Provides access to the Django ORM model instance representing the current Smarter LLMClient.
This property reads the LLMClient that the broker’s user profile owns under the broker’s name, and caches it for future access. It never creates one: a new LLMClient is created by
apply(), inside its transaction, so that an apply that fails leaves nothing behind.- Returns:
The Django ORM LLMClient instance, or
Noneif the user profile has no LLMClient of that name.- Return type:
Optional[LLMClient]
Note
The returned LLMClient object is essential for linking related resources such as API keys, plugins, and extensions, and for performing updates or queries on the llmclient’s state.
FIX NOTE
This should be refactored/removed in favor of orm_instance. There is no logic in this property that merits it overriding the parent orm_instance property.
- property llmclient_api_key: LLMClientAPIKey | None
Provides access to the API key associated with the current LLMClient instance.
This property retrieves the
LLMClientAPIKeyDjango ORM model object that is linked to the LLMClient managed by this broker. The API key is used for authenticating requests made by the LLMClient and is stored securely in the database.If the API key has already been retrieved and cached, it is returned immediately. Otherwise, the property attempts to fetch the API key from the database using the current LLMClient instance. If no API key is found,
Noneis returned.This property is essential for operations that require authentication or authorization on behalf of the LLMClient, such as invoking external APIs or managing secure resources.
- Returns:
The
LLMClientAPIKeyinstance associated with the LLMClient, orNoneif no API key exists.- Return type:
Optional[LLMClientAPIKey]
Important
If the LLMClientAPIKey is
None, it indicates that no API key has been set for the LLMClient, which in turn will enable anonymous unauthenticated access for the LLMClient.
- logs(request, *args, **kwargs)[source]
Return an empty logs response: LLMClient logs are not implemented.
- Parameters:
request (
HttpRequest) – The HTTP request.args – Positional arguments (unused).
kwargs – Keyword arguments (unused).
- Return type:
- Returns:
A successful response whose data is an empty dict.
- property manifest: SAMLLMClient | None
Returns the Smarter API LLMClient manifest as a Pydantic model.
This method constructs and returns an instance of the
SAMLLMClientPydantic model, which represents the full manifest for a Smarter API LLMClient. The manifest contains all configuration, metadata, and specification details required to describe and deploy an llmclient within the Smarter platform.The manifest is initialized from the client’s manifest data, which supplies the manifest’s API version, kind, metadata, and specification, which are passed to the respective fields of the
SAMLLMClientmodel. The metadata and spec fields are themselves Pydantic models (SAMLLMClientMetadataandSAMLLMClientSpec), and are recursively initialized with their corresponding data.Unlike child models, which are automatically cascade-initialized by Pydantic when constructing the parent model, the top-level manifest model must be explicitly instantiated in this method. This ensures that all manifest data is validated and structured according to the schema defined by the
SAMLLMClientmodel.If the manifest has already been initialized and cached, this method returns the cached instance. If there is manifest data, whose kind was checked when it was set, a new manifest instance is created and cached before returning.
- Returns:
An instance of
SAMLLMClientrepresenting the llmclient manifest, orNoneif the manifest cannot be initialized.- Return type:
Optional[SAMLLMClient]
- manifest_to_django_orm()[source]
Convert the Smarter API LLMClient manifest into a dictionary suitable for creating or updating a Django ORM LLMClient model.
This method extracts all relevant configuration, metadata, and versioning information from the loaded manifest and transforms it into a dictionary format compatible with Django ORM operations. The manifest’s
spec.config.promptis first dumped and converted from camelCase to snake_case to match Django’s field naming conventions. Itsspec.config.stylesis stored as is, with its camelCase keys and without the settings that it leaves out, in thestylesfield.The resulting dictionary includes the account, name, description, and version fields from the manifest metadata, as well as all configuration fields from the manifest specification. This dictionary can be used to instantiate or update a LLMClient 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.
- Returns:
A dictionary containing all fields required to create or update a Django ORM LLMClient model.
- Return type:
- Raises:
SAMBrokerErrorNotReady – If the manifest is not loaded or cannot be found.
SAMLLMClientBrokerError – If the manifest configuration cannot be converted to a dictionary.
- new_llmclient(data)[source]
Build, but don’t save, the LLMClient that applying the manifest creates.
apply()validates and saves it inside its transaction, so that a failed apply rolls the new LLMClient back with everything else it wrote.- Parameters:
data (
dict[str,Any]) – The manifest’s fields, frommanifest_to_django_orm(), without the read-only fields and the tags.- Return type:
- Returns:
The new, unsaved LLMClient, owned by the broker’s user profile.
- Raises:
SAMLLMClientBrokerError – If the broker has no user profile to own it.
- property plugins: List[str] | None
Provides access to the Django ORM model class representing LLMClient plugins.
This property retrieves a list of the names of the
LLMClientPluginDjango ORM model objects that are linked to the LLMClient managed by this broker. The plugins extend the functionality of the LLMClient, as specified in the manifest.If the plugins have already been retrieved and cached, they are returned immediately. Otherwise, the property attempts to fetch the plugins from the database using the current LLMClient instance. If no plugins are found,
Noneis returned.- Returns:
A list of names of
LLMClientPlugininstances associated with the LLMClient, orNoneif no plugins exist.- Return type:
Optional[List[str]]
- prompt(request, *args, **kwargs)[source]
Not supported: the CLI does not prompt an LLMClient.
- Parameters:
request (
HttpRequest) – The HTTP request.args – Positional arguments (unused).
kwargs – Keyword arguments (unused).
- Raises:
SAMBrokerErrorNotImplemented – always.
- Return type:
- raise_for_unknown_keys(manifest)[source]
Raise a validation error if the manifest has keys that it does not define.
spec.configis split intopromptandstyles. A manifest that was written before the split has its settings directly inspec.config, and the error says where each belongs now, e.g.spec.config.appNameinspec.config.prompt.appName.- Parameters:
manifest – The manifest, as the client sent it.
- Raises:
SAMValidationError – If the manifest has keys that it does not define.
- Return type:
- 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:
Trueif the broker is ready,Falseotherwise.- Return type:
- classmethod references(instance)[source]
Return the resources that an LLMClient uses.
Its Provider, which
spec.config.providernames, or the default Provider; the plugins, MCPClients, Guardrails, Vectorsearches and Extensions that it lists; its Custom Domain; and the api key that its url requires. An Extension is not a SAM kind, so it is a leaf ofdependency_tree().
- resolve_extension(slug)[source]
Return the installed Extension with the slug
slug, if this broker’s user’s account may use it.An extension that is disabled may still be listed: its tools are offered once an administrator enables it.
- resolve_guardrail(name)[source]
Return the Guardrail named
namethat this broker’s user may use, the nearest.Their own, else their account’s, else that of the nearest account that shares with theirs, e.g. an organization’s IT department, ending with the built-in guardrails of the Smarter admin user. See
smarter.apps.account.hierarchy.resolve_by_name(): only the profile’s account tree counts, so an LLMClient’s guardrails don’t depend on who wrote it.
- resolve_mcpclient(name)[source]
Return the MCPClient named
namethat this broker’s user may use.The user’s own MCPClient takes precedence over one that is shared with them.
- resolve_vectorsearch(name)[source]
Return the Vectorsearch named
namethat this broker’s user may use.The user’s own Vectorsearch takes precedence over one that is shared with them.
- Parameters:
name (
str) – The name of the Vectorsearch.- Returns:
The Vectorsearch, or
Noneif the user has none by that name.- Return type:
- touch_when_relations_changed(relations_changed, llmclient_saved)[source]
Move the llmclient’s
updated_atwhen apply changed what it uses, but not the llmclient itself.An llmclient’s cached answers to first messages are keyed by its
updated_at(seesmarter.apps.provider.services.text_completion.lib.prompt_cache), so attaching or detaching a plugin, guardrail, extension, MCP client or api key must move it too. Otherwise the llmclient answers as it did before, until the cached answers expire.
- undeploy(request, *args, **kwargs)[source]
Clear the LLMClient’s
deployedflag and save it.When the flag changes,
LLMClient.save()sendsllmclient_undeploy, whose receiver queues theundeploy_default_apiCelery task.- Parameters:
request (
HttpRequest) – The HTTP request.args – Positional arguments (unused).
kwargs – Keyword arguments (unused).
- Return type:
- Returns:
A successful response with empty data.
- Raises:
SAMBrokerErrorNotReady – if the broker has no name.
SAMBrokerErrorNotFound – if the LLMClient does not exist.
SAMLLMClientBrokerError – if the save fails.
- exception smarter.apps.llmclient.manifest.brokers.llmclient.SAMLLMClientBrokerError(message=None, thing=None, command=None, stack_trace=None)[source]
Bases:
SAMBrokerErrorBase exception for Smarter API LLMClient Broker handling.
- property get_formatted_err_message
Return the error message prefix for LLMClient broker errors.