Source code for smarter.apps.llmclient.manifest.brokers.llmclient

# pylint: disable=W0718,C0302
"""Smarter API LLMClient Manifest handler."""

import datetime
from contextlib import contextmanager
from typing import Iterator, List, Optional, Type

from django.db import transaction
from django.forms.models import model_to_dict
from django.http import HttpRequest
from rest_framework.serializers import ModelSerializer
from taggit.managers import TaggableManager, _TaggableManager

from smarter.apps.account.hierarchy import resolve_by_name
from smarter.apps.account.models import User
from smarter.apps.account.utils import (
    is_platform_staff,
    smarter_cached_objects,
    valid_resource_owners_for_user,
)
from smarter.apps.guardrail.models import Guardrail
from smarter.apps.llmclient.manifest.models.llmclient.const import MANIFEST_KIND
from smarter.apps.llmclient.manifest.models.llmclient.metadata import (
    SAMLLMClientMetadata,
)
from smarter.apps.llmclient.manifest.models.llmclient.model import SAMLLMClient
from smarter.apps.llmclient.manifest.models.llmclient.spec import (
    SAMLLMClientSpec,
    SAMLLMClientSpecConfig,
    SAMLLMClientSpecConfigPrompt,
)
from smarter.apps.llmclient.manifest.models.llmclient.status import SAMLLMClientStatus
from smarter.apps.llmclient.manifest.models.llmclient.styles import (
    SAMLLMClientSpecConfigStyles,
    SAMLLMClientStylesConversationHeader,
    SAMLLMClientStylesMessage,
)
from smarter.apps.llmclient.models import (
    LLMClient,
    LLMClientAPIKey,
    LLMClientExtensions,
    LLMClientGuardrails,
    LLMClientMCPClients,
    LLMClientPlugin,
    LLMClientVectorsearches,
)
from smarter.apps.llmtool.models import Extension, PluginMeta
from smarter.apps.llmtool.signals import broker_ready
from smarter.apps.mcpclient.models import MCPClient
from smarter.apps.vectorsearch.models import Vectorsearch
from smarter.common.conf import smarter_settings
from smarter.common.exceptions import SmarterValueError
from smarter.lib import logging
from smarter.lib.django.waffle import SmarterWaffleSwitches
from smarter.lib.drf.models import SmarterAuthToken
from smarter.lib.journal.enum import SmarterJournalCliCommands
from smarter.lib.journal.http import SmarterJournaledJsonResponse
from smarter.lib.manifest.broker import (
    AbstractBroker,
    SAMBrokerError,
    SAMBrokerErrorNotFound,
    SAMBrokerErrorNotImplemented,
    SAMBrokerErrorNotReady,
    SAMDependency,
    SAMDependents,
    memoized_dependencies,
    rows_with_pk,
)
from smarter.lib.manifest.enum import (
    SAMKeys,
    SAMMetadataKeys,
    SCLIResponseGet,
    SCLIResponseGetData,
)
from smarter.lib.manifest.exceptions import SAMValidationError
from smarter.lib.manifest.models import client_manifest_validation
from smarter.lib.typing import SmarterDictType, required

logger = logging.getSmarterLogger(
    __name__, any_switches=[SmarterWaffleSwitches.LLM_CLIENT_LOGGING, SmarterWaffleSwitches.MANIFEST_LOGGING]
)

MAX_RESULTS = 1000


[docs] class SAMLLMClientBrokerError(SAMBrokerError): """Base exception for Smarter API LLMClient Broker handling.""" @property def get_formatted_err_message(self): """Return the error message prefix for LLMClient broker errors.""" return "Smarter API LLMClient Manifest Broker Error"
[docs] class LLMClientSerializer(ModelSerializer): """Django ORM model serializer for get().""" # pylint: disable=C0115 class Meta: model = LLMClient fields = ["name", "url", "dns_verification_status", "deployed", "created_at", "updated_at"]
[docs] class SAMLLMClientBroker(AbstractBroker[LLMClient, LLMClient]): """ Broker for :py:class:`SAM <smarter.lib.manifest.models.AbstractSAMMetadataBase>` LLMClient 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. """ # override the base abstract manifest model with the LLMClient model _manifest: Optional[SAMLLMClient] = None _pydantic_model: Type[SAMLLMClient] = SAMLLMClient deployable = True _llmclient: Optional[LLMClient] = None _extensions: Optional[List[str]] = None _plugins: Optional[List[str]] = None _llmclient_api_key: Optional[LLMClientAPIKey] = None _name: Optional[str] = None _ready: bool = False
[docs] def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) logger.debug( "broker for %s %s is %s.", self.kind, self.name, self.ready_state, )
[docs] def raise_for_unknown_keys(self, manifest) -> None: """ Raise a validation error if the manifest has keys that it does not define. ``spec.config`` is split into ``prompt`` and ``styles``. A manifest that was written before the split has its settings directly in ``spec.config``, and the error says where each belongs now, e.g. ``spec.config.appName`` in ``spec.config.prompt.appName``. :param manifest: The manifest, as the client sent it. :raises SAMValidationError: If the manifest has keys that it does not define. """ spec = manifest.get(SAMKeys.SPEC.value) if isinstance(manifest, dict) else None config = spec.get("config") if isinstance(spec, dict) else None if isinstance(config, dict): moved = [] for key in config: if key in SAMLLMClientSpecConfig.model_fields: continue if key in SAMLLMClientSpecConfigPrompt.model_fields: moved.append(f"spec.config.{key} to spec.config.prompt.{key}") elif key in SAMLLMClientSpecConfigStyles.model_fields: moved.append(f"spec.config.{key} to spec.config.styles.{key}") if moved: raise SAMValidationError( f"The {self.kind} manifest's spec.config is split into prompt, which is required, and " f"styles, which is optional. Move {', '.join(moved)}." ) super().raise_for_unknown_keys(manifest)
@property def SerializerClass(self) -> Type[LLMClientSerializer]: """ The Django ORM model serializer class for the LLMClient. :returns: The LLMClient Django ORM model serializer class. :rtype: Type[ModelSerializer] """ return LLMClientSerializer @property def ready(self) -> 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. :rtype: bool """ if self._ready: return self._ready retval = super().ready if not retval: logger.debug("AbstractBroker is not ready for %s", self.kind) return False retval = self.manifest is not None or self.account is not None logger.debug( "manifest presence indicates ready=%s for %s", retval, self.kind, ) if retval: self._ready = True self.send_broker_ready(broker_ready) return self._ready @property def llmclient(self) -> Optional[LLMClient]: """ 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 :py:meth:`apply`, inside its transaction, so that an apply that fails leaves nothing behind. :returns: The Django ORM LLMClient instance, or ``None`` if the user profile has no LLMClient of that name. :rtype: 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. .. admonition:: 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. """ if self._llmclient: return self._llmclient try: # read the database, not the cache: a broker writes this llmclient, so it must be current. # get_cached_object(invalidate=True) was current too, but it also emptied the cache that # every other reader of this llmclient uses, each time a broker was built. self._llmclient = ( LLMClient.objects.prefetch_related("tags") .select_related("user_profile", "user_profile__account", "user_profile__user") .get(user_profile=self.user_profile, name=self.name) ) except LLMClient.DoesNotExist: logger.debug("%s %s not found for %s", self.kind, self.name, self.user_profile) return None logger.debug( "retrieved existing LLMClient instance %s owned by %s from database.", self._llmclient, self.user_profile, ) return self._llmclient
[docs] def new_llmclient(self, data: SmarterDictType) -> LLMClient: """ Build, but don't save, the LLMClient that applying the manifest creates. :py:meth:`apply` validates and saves it inside its transaction, so that a failed apply rolls the new LLMClient back with everything else it wrote. :param data: The manifest's fields, from :py:meth:`manifest_to_django_orm`, without the read-only fields and the tags. :returns: The new, unsaved LLMClient, owned by the broker's user profile. :raises SAMLLMClientBrokerError: If the broker has no user profile to own it. """ user_profile = self.user_profile if user_profile is None: raise SAMLLMClientBrokerError(f"{self.kind} {self.name} has no user profile to own it", thing=self.kind) llmclient = LLMClient(**data) llmclient.user_profile = user_profile logger.debug("building a new %s %s for %s", self.kind, self.name, self.user_profile) return llmclient
[docs] @contextmanager def forget_llmclient_on_failure(self) -> Iterator[None]: """ Drop the broker's cached LLMClient when the block it wraps raises. Used inside :py:meth:`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 of :py:attr:`llmclient` reads the database again. :raises Exception: Whatever the block raised, unchanged. """ try: yield except Exception: self._llmclient = None raise
@property def extensions(self) -> Optional[List[str]]: """ The slugs of the Extensions linked to the LLMClient that this broker manages. :returns: The slugs, or ``None`` if there is no LLMClient. :rtype: Optional[List[str]] """ if self._extensions: return self._extensions if not self.llmclient: return None self._extensions = list( LLMClientExtensions.objects.filter(llmclient=self.llmclient) .order_by("extension__slug") .values_list("extension__slug", flat=True) ) return self._extensions @property def plugins(self) -> Optional[List[str]]: """ Provides access to the Django ORM model class representing LLMClient plugins. This property retrieves a list of the names of the ``LLMClientPlugin`` Django 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, ``None`` is returned. :returns: A list of names of ``LLMClientPlugin`` instances associated with the LLMClient, or ``None`` if no plugins exist. :rtype: Optional[List[str]] """ if self._plugins: return self._plugins if not self.llmclient: return None queryset = LLMClientPlugin.objects.filter(llmclient=self.llmclient) self._plugins = list(queryset.values_list("plugin_meta__name", flat=True)) return self._plugins @property def llmclient_api_key(self) -> Optional[LLMClientAPIKey]: """ Provides access to the API key associated with the current LLMClient instance. This property retrieves the ``LLMClientAPIKey`` Django 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, ``None`` is 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 ``LLMClientAPIKey`` instance associated with the LLMClient, or ``None`` if no API key exists. :rtype: 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. """ if self._llmclient_api_key: return self._llmclient_api_key try: self._llmclient_api_key = LLMClientAPIKey.objects.get(llmclient=self.llmclient) except LLMClientAPIKey.DoesNotExist: return None return self._llmclient_api_key
[docs] def manifest_to_django_orm(self) -> SmarterDictType: """ 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.prompt`` is first dumped and converted from camelCase to snake_case to match Django's field naming conventions. Its ``spec.config.styles`` is stored as is, with its camelCase keys and without the settings that it leaves out, in the ``styles`` field. 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. :rtype: dict :raises SAMBrokerErrorNotReady: If the manifest is not loaded or cannot be found. :raises SAMLLMClientBrokerError: If the manifest configuration cannot be converted to a dictionary. """ if not self.manifest: raise SAMBrokerErrorNotReady( f"Manifest not loaded for {self.kind} broker. Cannot convert to Django ORM.", thing=self.kind ) metadata = super().manifest_to_django_orm() original_config = self.manifest.spec.config.prompt.model_dump() config_dump = self.to_snake_case(original_config) if not isinstance(config_dump, dict): raise SAMLLMClientBrokerError( f"Failed to convert {self.kind} {self.manifest.metadata.name} to dict. Got {type(config_dump)}", thing=self.kind, ) # to_snake_case() also converts the strings in lists, which are values, e.g. the # appExamplePrompts, so lists are restored as is. for key, value in original_config.items(): if isinstance(value, list): config_dump[str(self.to_snake_case(key))] = value # a manifest without deployed keeps the llmclient's deployed state, so that applying a deployed # llmclient's manifest again doesn't undeploy it. A new llmclient is then not deployed. if config_dump.get("deployed") is None: config_dump.pop("deployed", None) styles = self.manifest.spec.config.styles config_dump["styles"] = styles.model_dump(mode="json", exclude_none=True) if styles else {} retval = { **metadata, **config_dump, } logger.debug( "converted manifest to Django ORM dict: %s", retval, ) return retval
# the return value is a Pydantic model_dump(), whose keys are already camelCase. It is # not passed through @camel_case(), which would also convert the names in lists, e.g. # spec.plugins and spec.mcpClients.
[docs] def django_orm_to_manifest_dict(self) -> Optional[SmarterDictType]: """ 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 ``None`` if the LLMClient model is not set. :rtype: Optional[dict] :raises SAMLLMClientBrokerError: If the ORM model cannot be converted to a manifest dictionary. See also: - :py:meth:`smarter.apps.llmclient.manifest.brokers.llmclient.SAMLLMClientBroker.manifest_to_django_orm` - :py:class:`smarter.apps.llmclient.manifest.models.llmclient.SAMLLMClient` - :py:class:`smarter.apps.llmclient.manifest.models.llmclient.metadata.SAMLLMClientMetadata` - :py:class:`smarter.apps.llmclient.manifest.models.llmclient.spec.SAMLLMClientSpec` - :py:class:`smarter.apps.llmclient.manifest.models.llmclient.status.SAMLLMClientStatus` """ if not self.account: raise SAMBrokerErrorNotReady( f"Account not loaded for {self.kind} broker. Cannot convert Django ORM to manifest dict.", thing=self.kind, ) if not self.user_profile: raise SAMBrokerErrorNotReady( f"User profile not loaded for {self.kind} broker. Cannot convert Django ORM to manifest dict.", thing=self.kind, ) if not self.llmclient: logger.warning( "called without a LLMClient. This could affect broker operations.", ) return None llmclient_dict = model_to_dict(self.llmclient) llmclient_dict = self.to_camel_case(llmclient_dict) if not isinstance(llmclient_dict, dict): raise SAMLLMClientBrokerError( f"Failed to convert {self.kind} {self.llmclient.name} to dict", thing=self.kind ) llmclient_dict.pop("id") llmclient_dict.pop("name") llmclient_dict.pop("description") llmclient_dict.pop("version") plugins = LLMClientPlugin.objects.filter(llmclient=self.llmclient) plugin_names = [plugin.plugin_meta.name for plugin in plugins] extension_slugs = list( LLMClientExtensions.objects.filter(llmclient=self.llmclient) .order_by("extension__slug") .values_list("extension__slug", flat=True) ) mcpclient_names = [ link.mcpclient.name for link in LLMClientMCPClients.objects.filter(llmclient=self.llmclient).select_related("mcpclient") ] guardrail_names = [ link.guardrail.name for link in LLMClientGuardrails.objects.filter(llmclient=self.llmclient).select_related("guardrail") ] vectorsearch_names = [ link.vectorsearch.name for link in LLMClientVectorsearches.objects.filter(llmclient=self.llmclient) .select_related("vectorsearch") .order_by("vectorsearch__name") ] # spec.apiKey is the SmarterAuthToken's name, which is what apply() looks it up by. api_key = self.llmclient_api_key.api_key.name if self.llmclient_api_key else None meta = SAMLLMClientMetadata( name=self.llmclient.name, description=self.llmclient.description, version=self.llmclient.version, tags=self.llmclient.tags_list, annotations=self.llmclient.annotations, ) styles = llmclient_dict.pop("styles", None) spec_config = SAMLLMClientSpecConfig( prompt=SAMLLMClientSpecConfigPrompt(**llmclient_dict), styles=SAMLLMClientSpecConfigStyles(**styles) if styles else None, ) spec = SAMLLMClientSpec( config=spec_config, plugins=plugin_names, extensions=extension_slugs or None, guardrails=guardrail_names or None, mcpClients=mcpclient_names or None, vectorsearches=vectorsearch_names or None, apiKey=api_key, ) status = SAMLLMClientStatus( accountNumber=required(self.account.account_number, "account.account_number"), username=self.user_profile.user.username, recordLocator=self.llmclient.record_locator, created=required(self.llmclient.created_at, "llmclient.created_at"), modified=required(self.llmclient.updated_at, "llmclient.updated_at"), deployed=bool(self.llmclient.deployed), defaultHost=self.llmclient.default_host, sandboxHost=self.llmclient.sandbox_host, hostname=self.llmclient.hostname, dnsVerificationStatus=required(self.llmclient.dns_verification_status, "llmclient.dns_verification_status"), customUrl=self.llmclient.custom_url, defaultUrl=self.llmclient.default_url, sandboxUrl=self.llmclient.sandbox_url, url=self.llmclient.url, urlLLMClient=self.llmclient.url_llmclient, urlChatConfig=self.llmclient.url_chat_config, urlChatapp=self.llmclient.url_chatapp, ) model = SAMLLMClient( apiVersion=self.api_version, kind=self.kind, metadata=meta, spec=spec, status=status, ) logger.debug( "converted LLMClient %s to manifest dict: %s", self.llmclient.name, model.model_dump(), ) return model.model_dump()
########################################################################### # Smarter abstract property implementations ########################################################################### @property def formatted_class_name(self) -> 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. :rtype: str """ class_name = f"{SAMLLMClientBroker.__name__}[{id(self)}]" return self.formatted_text(class_name) @property def kind(self) -> 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. :rtype: str .. important:: The kind property is essential for manifest validation, routing, and processing within the Smarter platform. """ return MANIFEST_KIND @property def manifest(self) -> Optional[SAMLLMClient]: """ Returns the Smarter API LLMClient manifest as a Pydantic model. This method constructs and returns an instance of the ``SAMLLMClient`` Pydantic 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 ``SAMLLMClient`` model. The metadata and spec fields are themselves Pydantic models (``SAMLLMClientMetadata`` and ``SAMLLMClientSpec``), 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 ``SAMLLMClient`` model. 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 ``SAMLLMClient`` representing the llmclient manifest, or ``None`` if the manifest cannot be initialized. :rtype: Optional[SAMLLMClient] """ if self._manifest: if not isinstance(self._manifest, SAMLLMClient): raise SAMLLMClientBrokerError("Cached manifest is not a SAMLLMClient instance", thing=self.kind) return self._manifest if self.manifest_data is not None: logger.debug( "initializing %s from manifest data with name %s", self.kind, (self.manifest_metadata or {}).get(SAMMetadataKeys.NAME.value, "unknown"), ) # validated as a client's manifest, so that, e.g., the styles' image urls are checked to # be available. See smarter.lib.manifest.models.client_manifest_validation. with client_manifest_validation(): self._manifest = SAMLLMClient.model_validate(self.manifest_sections) return self._manifest if self._llmclient: self._manifest = self.django_orm_to_manifest_dict() # type: ignore if self._manifest: logger.debug( "initialized from manifest data for existing LLMClient %s with name %s", self._llmclient, self._llmclient.name, ) return self._manifest else: logger.debug( "could not initialize", ) return self._manifest ########################################################################### # Smarter manifest abstract method implementations ###########################################################################
[docs] def cache_invalidations(self) -> None: """ 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. .. returns: None .. rtype: None """ logger.debug("called.", prefix_format=logging.SmarterFormattedText.BOLD_DARK_BLUE) # 1.) invalidate the LLMClient cache itself. # ----------------------------- LLMClient.get_cached_object(pk=self.llmclient.id, invalidate=True) # type: ignore # 2.) invalidate anything else in which the llmclient is part of. this could # include listviews, the plugins, extensions and api keys. # ----------------------------- LLMClient.get_cached_objects(user_profile=self.user_profile, invalidate=True) # 3.) invalidate all children of LLMClient # ----------------------------- llmclient_plugins = LLMClientPlugin.objects.filter(llmclient=self.llmclient) for llmclient_plugin in llmclient_plugins: LLMClientPlugin.get_cached_object(pk=llmclient_plugin.id, invalidate=True) # type: ignore llmclient_api_keys = LLMClientAPIKey.objects.filter(llmclient=self.llmclient) for llmclient_api_key in llmclient_api_keys: LLMClientAPIKey.get_cached_object(pk=llmclient_api_key.id, invalidate=True) # type: ignore return super().cache_invalidations()
@property def ORMMetaModelClass(self) -> Type[LLMClient]: """ Return the Django ORM meta model class for the broker. :return: The Django ORM meta model class definition for the broker. :rtype: Type[LLMClient] """ return LLMClient @property def ORMModelClass(self) -> Type[LLMClient]: """ The Django ORM model class for the LLMClient. :returns: The LLMClient Django ORM model class. :rtype: Type[LLMClient] """ return LLMClient
[docs] def example_manifest(self, request: HttpRequest, *args, **kwargs) -> SmarterJournaledJsonResponse: """ Return an example manifest for the Smarter API LLMClient. :returns: A JSON response containing an example Smarter API LLMClient manifest. :rtype: SmarterJournaledJsonResponse See also: - :py:class:`smarter.apps.llmclient.manifest.models.llmclient.SAMLLMClient` - :py:class:`smarter.lib.manifest.enumSAMKeys` - :py:class:`smarter.apps.llmclient.manifest.enum.SAMMetadataKeys` - :py:class:`smarter.apps.llmclient.manifest.enum.SCLIResponseGet` - :py:class:`smarter.apps.llmclient.manifest.enum.SCLIResponseGetData` - :attr:`smarter.common.conf.settings.Settings.llm_default_system_role` """ command = SmarterJournalCliCommands(self.example_manifest.__name__) meta_data = SAMLLMClientMetadata( name="example_llmclient", description="This is an example llmclient manifest generated by the SAMLLMClientBroker. It serves as a template for creating your own llmclient manifests.", version="1.0.0", tags=["example", "template", "school-project"], annotations={ "color": "red", "size": "medium", "hash": "sha256:abc123def456", }, ) prompt = SAMLLMClientSpecConfigPrompt( subdomain=None, customDomain=None, deployed=False, provider=smarter_settings.llm_default_provider, defaultModel=smarter_settings.llm_default_model, defaultSystemRole=smarter_settings.llm_default_system_role, defaultTemperature=smarter_settings.llm_default_temperature, defaultMaxTokens=smarter_settings.llm_default_max_tokens, appName="Example LLMClient", appAssistant="Example Assistant", appWelcomeMessage="Welcome to the Example LLMClient! How can I assist you today?", appExamplePrompts=[ "What is the weather like today?", "Can you tell me a joke?", "How do I reset my password?", ], appPlaceholder="Type your message here...", appInfoUrl="https://example.com/info", appFileAttachment=False, ) # The style models declare their defaults positionally, as Field(None, ...), which type # checkers don't read as a default, so the unused settings are passed as None explicitly. conversation_header = SAMLLMClientStylesConversationHeader( backgroundColor="#1b1f3b", color="#ffffff", infoColor="#c0c4e0", borderColor=None, ) incoming_message = SAMLLMClientStylesMessage( backgroundColor="#eef1ff", color="#1b1f3b", borderColor=None, linkColor=None, ) outgoing_message = SAMLLMClientStylesMessage( backgroundColor="#ff5733", color="#ffffff", borderColor=None, linkColor=None, ) styles = SAMLLMClientSpecConfigStyles( appLogoUrl="https://cdn.smarter.sh/images/logo/smarter-crop.png", appBackgroundImageUrl="https://cdn.smarter.sh/prompt-ui/background.png", appBackgroundImageSize="cover", assistantAvatarUrl=None, userAvatarUrl=None, fontFamily=None, googleFont="Inter", fontSize=None, borderRadius="14px", mainContainer=None, conversationHeader=conversation_header, messageList=None, incomingMessage=incoming_message, outgoingMessage=outgoing_message, messageInput=None, buttons=None, typingIndicator=None, ) config = SAMLLMClientSpecConfig(prompt=prompt, styles=styles) spec = SAMLLMClientSpec( config=config, plugins=["everlasting_gobstopper", "research_assistant", "code_review", "image_search"], extensions=["calculator", "date-calculator", "weather"], guardrails=["pii_redaction_input", "prompt_injection_keyword_input", "moderation_output"], mcpClients=["deepwiki"], vectorsearches=["example_vectorsearch"], apiKey="snake_case_api_key_name", ) status = SAMLLMClientStatus( accountNumber=required( smarter_cached_objects.smarter_account.account_number, "smarter_account.account_number" ), username=smarter_cached_objects.smarter_admin.username, recordLocator="abc123def456", created=datetime.datetime.now(), modified=datetime.datetime.now(), deployed=False, defaultHost="example-llmclient.smarterapi.com", defaultUrl="https://example-llmclient.smarterapi.com", customUrl=None, sandboxHost="https://example.com", sandboxUrl="https://example.com/api/v1/llm-clients/1/", hostname="example-llmclient.smarterapi.com", url="https://example.com/api/v1/llm-clients/1/", urlLLMClient="https://example-llmclient.smarterapi.com/llmclient", urlChatapp="https://example-llmclient.smarterapi.com/chatapp", urlChatConfig="https://example-llmclient.smarterapi.com/chatconfig", dnsVerificationStatus="verified", ) model = SAMLLMClient(apiVersion=self.api_version, kind=self.kind, metadata=meta_data, spec=spec, status=status) return self.json_response_ok(command=command, data=model.model_dump())
[docs] def get(self, request: HttpRequest, *args, **kwargs) -> SmarterJournaledJsonResponse: """ List the account's LLMClients that the user may see, optionally filtered by name and annotations. Returns at most ``MAX_RESULTS`` LLMClients, ordered by name, each serialized with :class:`~smarter.apps.llmclient.serializers.LLMClientSerializer` and camel-cased. :param request: The HTTP request. :param args: Positional arguments (unused). :param kwargs: Query parameters: ``name`` and the annotation selector. :returns: A response with the column titles and the serialized LLMClients. :raises SAMLLMClientBrokerError: if an LLMClient fails to serialize. """ command = SmarterJournalCliCommands(self.get.__name__) items: list[SmarterDictType] = [] name = kwargs.get(SAMMetadataKeys.NAME.value, None) name = self.clean_cli_param(param=name, param_name="name", url=self.smarter_build_absolute_uri(request)) # generate a QuerySet of PluginMeta objects that match our search criteria if name: llmclients = LLMClient.objects.filter(user_profile__account=self.account, name=name) else: llmclients = LLMClient.objects.filter(user_profile__account=self.account) valid_owners = valid_resource_owners_for_user(user_profile=self.user_profile) llmclients = self.filter_by_annotation_selector(llmclients.filter(user_profile__in=valid_owners), kwargs) llmclients = llmclients.order_by("name")[:MAX_RESULTS] logger.debug( "found %s LLMClients for account %s", llmclients.count(), self.account, ) # iterate over the QuerySet and use a serializer to create a model dump for each LLMClient for llmclient in llmclients: try: model_dump = LLMClientSerializer(llmclient).data if not model_dump: raise SAMLLMClientBrokerError( f"Model dump failed for {self.kind} {llmclient.name}", thing=self.kind, command=command ) camel_cased_model_dump = self.to_camel_case(model_dump) items.append(camel_cased_model_dump) except Exception as e: logger.error( "failed to serialize %s %s", self.kind, llmclient.name, exc_info=True, ) raise SAMLLMClientBrokerError( f"Failed to serialize {self.kind} {llmclient.name}", thing=self.kind, command=command ) from e data = { SAMKeys.APIVERSION.value: self.api_version, SAMKeys.KIND.value: self.kind, SAMMetadataKeys.NAME.value: name, SAMKeys.METADATA.value: {"count": len(items)}, SCLIResponseGet.KWARGS.value: kwargs, SCLIResponseGet.DATA.value: { SCLIResponseGetData.TITLES.value: self.get_model_titles(serializer=LLMClientSerializer()), SCLIResponseGetData.ITEMS.value: items, }, } return self.json_response_ok(command=command, data=data)
# pylint: disable=too-many-branches
[docs] def apply(self, request: HttpRequest, *args, **kwargs) -> SmarterJournaledJsonResponse: """ 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. """ command = SmarterJournalCliCommands(self.apply.__name__) if not self.ready: raise SAMBrokerErrorNotReady( f"{self.kind} {self.name} broker is not ready", thing=self.kind, command=command ) if not self.manifest: raise SAMBrokerErrorNotReady(f"{self.kind} {self.name} not found", thing=self.kind, command=command) if not self.manifest.spec: raise SAMBrokerErrorNotReady( f"{self.kind} {self.name} manifest spec not found", thing=self.kind, command=command ) if self.manifest.spec.config.prompt.staffOnly and not is_platform_staff(self.user): # anyone else would hide the llmclient from themselves, and from their own account. raise SAMLLMClientBrokerError( f"Only the platform's staff may apply a staff-only {self.kind}: remove spec.config.prompt.staffOnly, " "or set it to false.", thing=self.kind, command=command, ) if self.manifest.metadata.name != self.name: # the manifest's metadata validator stores names in snake_case, e.g. 'My Client' as # 'my_client', so the llmclient is looked up by that name. Otherwise it is never # found, and every apply tries to create it again. logger.warning( "%s name '%s' is stored as '%s'", self.kind, self.name, self.manifest.metadata.name, ) self._name = self.manifest.metadata.name self._llmclient = None # a new llmclient is created inside the transaction, so that an apply that fails, e.g. on a # plugin that doesn't exist, rolls it back with everything else, rather than leaving it behind. with transaction.atomic(), self.forget_llmclient_on_failure(): readonly_fields = ["id", "created_at", "updated_at", "tags"] try: data = self.manifest_to_django_orm() tags = data.get("tags", []) for field in readonly_fields: data.pop(field, None) # the subdomain and the custom domain are relations that are created when the # llmclient is deployed, so apply neither sets them nor clears them. for field, manifest_key in (("subdomain", "subdomain"), ("custom_domain", "customDomain")): if data.pop(field, None) is not None: raise SmarterValueError( f"spec.config.prompt.{manifest_key} cannot be set by apply, because it is assigned when " f"the {self.kind} is deployed. Remove it from the manifest, or set it to null." ) llmclient = self.llmclient if llmclient is None: llmclient = self.new_llmclient(data) changed = True else: changed = bool(self.assign_changed_fields(llmclient, data)) if llmclient.user_profile != self.user_profile: raise SAMLLMClientBrokerError( f"User profile mismatch for {self.kind} {self.manifest.metadata.name}", thing=self.kind, command=command, ) # run the model's field validators, e.g. the provider, URLs and maximum lengths, # which save() does not, so that an invalid manifest is a 400 rather than an # invalid row, or a database error. llmclient.full_clean(validate_unique=False) # an unchanged llmclient is not saved again: see assign_changed_fields(). Its relations, # below, are applied either way. if changed: llmclient.save() self._llmclient = llmclient # Fix note: occasionally seeing AttributeError: \'list\' object has no attribute \'set\ in the logs, # which is why this is wrapped in a try/except block. try: if not isinstance(llmclient.tags, (TaggableManager, _TaggableManager)): logger.warning( "llmclient.tags is a list instead of a TaggableManager for %s %s owned by %s. This is unexpected and may indicate an issue with the LLMClient model definition or the database state. Tags=%s", self.kind, self.manifest.metadata.name, self.user_profile, tags, ) elif self.tags_changed(llmclient, tags): llmclient.tags.set(tags) # pylint: disable=broad-except except Exception as e: logger.error( "failed to set tags for %s %s owned by %s. Tags=%s. Error: %s", self.kind, self.manifest.metadata.name, self.user_profile, tags, e, exc_info=True, ) llmclient.refresh_from_db() except Exception as e: logger.error( "failed to save %s %s owned by %s. Error: %s", self.kind, self.manifest.metadata.name, self.user_profile, e, exc_info=True, ) raise SAMLLMClientBrokerError( f"Failed to apply {self.kind} {self.manifest.metadata.name}", thing=self.kind, command=command ) from e # whether apply attached or detached any of the resources that the llmclient uses. Its own # row may be unchanged then, but what it does is not: see the end of this block. relations_changed = False # LLMClientAPIKey: create or update the API Key # ------------- if self.manifest.spec.apiKey: if not isinstance(self.user, User): raise SAMLLMClientBrokerError( f"User not set for broker. Cannot attach API Key {self.manifest.spec.apiKey}", thing=self.kind, command=command, ) try: api_key = SmarterAuthToken.objects.get(name=self.manifest.spec.apiKey, user=self.user) except SmarterAuthToken.DoesNotExist as e: # the client's error, answered with a 404: not an error of the platform's. logger.warning("did not find an API Key named %s", self.manifest.spec.apiKey) raise SAMBrokerErrorNotFound( f"API Key {self.manifest.spec.apiKey} not found", thing=self.kind, command=command ) from e for key in LLMClientAPIKey.objects.filter(llmclient=llmclient): if key.api_key != api_key: key.delete() relations_changed = True logger.debug("Detached SmarterAuthToken %s from LLMClient %s", key.api_key.name, llmclient.name) # type: ignore[union-attr] _, created = LLMClientAPIKey.objects.get_or_create(llmclient=llmclient, api_key=api_key) if created: relations_changed = True logger.debug( "SmarterAuthToken %s attached to LLMClient %s", self.manifest.spec.apiKey, llmclient.name, ) # LLMClientPlugin: add what's missing, remove what is in the model but is not in the manifest # ------------- for plugin in LLMClientPlugin.objects.filter(llmclient=llmclient): if not self.manifest.spec.plugins or ( self.manifest.spec.plugins and plugin.plugin_meta.name not in self.manifest.spec.plugins ): plugin.delete() relations_changed = True logger.debug( "Detached Plugin %s from LLMClient %s", plugin.plugin_meta.name, llmclient.name, ) if self.manifest.spec.plugins: for plugin_name in self.manifest.spec.plugins: plugin_name = str(self.to_snake_case(plugin_name)) try: plugin_meta = PluginMeta.objects.get(name=plugin_name, user_profile=self.user_profile) except PluginMeta.DoesNotExist as e: # the client's error, answered with a 404: not an error of the platform's. logger.warning("did not find a Plugin named %s", plugin_name) raise SAMBrokerErrorNotFound( f"Plugin {plugin_name} not found for account {self.account.account_number if self.account else 'unknown'}", thing=self.kind, command=command, ) from e _, created = LLMClientPlugin.objects.get_or_create(llmclient=llmclient, plugin_meta=plugin_meta) if created: relations_changed = True logger.debug( "attached Plugin %s to LLMClient %s", plugin_meta.name, llmclient.name, ) # LLMClientExtensions: add what's missing, remove what's in the model but not in the manifest # ------------- extension_slugs = self.manifest.spec.extensions or [] for extension_link in LLMClientExtensions.objects.filter(llmclient=llmclient).select_related("extension"): if extension_link.extension.slug not in extension_slugs: extension_link.delete() relations_changed = True logger.debug( "detached Extension %s from LLMClient %s", extension_link.extension.slug, llmclient.name, ) for extension_slug in extension_slugs: extension = self.resolve_extension(extension_slug) if extension is None: raise SAMBrokerErrorNotFound( f"Extension {extension_slug} is not installed, or not available to {self.user_profile}", thing=self.kind, command=command, ) _, created = LLMClientExtensions.objects.get_or_create(llmclient=llmclient, extension=extension) if created: relations_changed = True logger.debug( "attached Extension %s to LLMClient %s", extension.slug, llmclient.name, ) # LLMClientGuardrails: add what's missing, remove what's in the model but not in the manifest # ------------- guardrail_names = self.manifest.spec.guardrails or [] for guardrail_link in LLMClientGuardrails.objects.filter(llmclient=llmclient).select_related("guardrail"): if guardrail_link.guardrail.name not in guardrail_names: guardrail_link.delete() relations_changed = True logger.debug( "detached Guardrail %s from LLMClient %s", guardrail_link.guardrail.name, llmclient.name, ) for guardrail_name in guardrail_names: guardrail = self.resolve_guardrail(guardrail_name) if guardrail is None: raise SAMBrokerErrorNotFound( f"Guardrail {guardrail_name} not found, or not shared with {self.user_profile}", thing=self.kind, command=command, ) _, created = LLMClientGuardrails.objects.get_or_create(llmclient=llmclient, guardrail=guardrail) if created: relations_changed = True logger.debug( "attached Guardrail %s to LLMClient %s", guardrail.name, llmclient.name, ) # LLMClientMCPClients: add what's missing, remove what's in the model but not in the manifest # ------------- mcpclient_names = self.manifest.spec.mcpClients or [] for mcpclient_link in LLMClientMCPClients.objects.filter(llmclient=llmclient).select_related("mcpclient"): if mcpclient_link.mcpclient.name not in mcpclient_names: mcpclient_link.delete() relations_changed = True logger.debug( "detached MCPClient %s from LLMClient %s", mcpclient_link.mcpclient.name, llmclient.name, ) for mcpclient_name in mcpclient_names: mcpclient = self.resolve_mcpclient(mcpclient_name) if mcpclient is None: raise SAMBrokerErrorNotFound( f"MCPClient {mcpclient_name} not found, or not shared with {self.user_profile}", thing=self.kind, command=command, ) _, created = LLMClientMCPClients.objects.get_or_create(llmclient=llmclient, mcpclient=mcpclient) if created: relations_changed = True logger.debug( "attached MCPClient %s to LLMClient %s", mcpclient.name, llmclient.name, ) # LLMClientVectorsearches: add what's missing, remove what's in the model but not in the manifest # ------------- vectorsearches_changed = self.apply_vectorsearches(command) relations_changed = relations_changed or vectorsearches_changed self.touch_when_relations_changed(relations_changed=relations_changed, llmclient_saved=changed) # done! return the response. Django will take care of committing the transaction self.cache_invalidations() return self.json_response_ok(command=command, data=self.command_result())
[docs] def touch_when_relations_changed(self, relations_changed: bool, llmclient_saved: bool) -> None: """ Move the llmclient's ``updated_at`` when apply changed what it uses, but not the llmclient itself. An llmclient's cached answers to first messages are keyed by its ``updated_at`` (see :mod:`smarter.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. :param relations_changed: Whether apply attached or detached any resource that the llmclient uses. :param llmclient_saved: Whether apply saved the llmclient's own row, which moved ``updated_at`` already. """ if not relations_changed: return if llmclient_saved: return llmclient = self.llmclient if not isinstance(llmclient, LLMClient): return llmclient.save(update_fields=["updated_at"])
[docs] def resolve_extension(self, slug: str) -> Optional[Extension]: """ 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. :param slug: The Extension's slug. :returns: The Extension, or ``None`` if it is not installed or not available to the user's account. :rtype: Optional[Extension] """ extension = Extension.objects.filter(slug=slug, installed_version__isnull=False).first() if extension is None: return None account = self.user_profile.account if self.user_profile else None return extension if extension.is_available_to(account) else None
[docs] def resolve_guardrail(self, name: str) -> Optional[Guardrail]: """ Return the Guardrail named ``name`` that 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 :func:`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. :param name: The name of the Guardrail. :returns: The Guardrail, or ``None`` if the user has none by that name. :rtype: Optional[Guardrail] """ if not self.user_profile: return None try: retval: Optional[Guardrail] = resolve_by_name( Guardrail.objects, name, self.user_profile # type: ignore[arg-type] ) except Guardrail.DoesNotExist: return None return retval
[docs] def resolve_mcpclient(self, name: str) -> Optional[MCPClient]: """ Return the MCPClient named ``name`` that this broker's user may use. The user's own MCPClient takes precedence over one that is shared with them. :param name: The name of the MCPClient. :returns: The MCPClient, or ``None`` if the user has none by that name. :rtype: Optional[MCPClient] """ if not self.user_profile: return None own = MCPClient.objects.filter(name=name, user_profile=self.user_profile).first() if own is not None: return own return ( MCPClient.objects.filter(name=name) .with_read_permission_for(self.user_profile.user) # type: ignore[attr-defined] .order_by("-updated_at") .first() )
[docs] def resolve_vectorsearch(self, name: str) -> Optional[Vectorsearch]: """ Return the Vectorsearch named ``name`` that this broker's user may use. The user's own Vectorsearch takes precedence over one that is shared with them. :param name: The name of the Vectorsearch. :returns: The Vectorsearch, or ``None`` if the user has none by that name. :rtype: Optional[Vectorsearch] """ if not self.user_profile: return None own = Vectorsearch.objects.filter(name=name, user_profile=self.user_profile).first() if own is not None: return own shared = ( Vectorsearch.objects.filter(name=name) .with_read_permission_for(self.user_profile.user) # type: ignore[attr-defined] .order_by("-updated_at") .first() ) return shared
[docs] def apply_vectorsearches(self, command: SmarterJournalCliCommands) -> bool: """ Link the LLMClient to the Vectorsearches that its manifest's ``spec.vectorsearches`` lists, and only those. :param command: The journal command, for errors. :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. """ changed = False vectorsearch_names = [] if self.manifest and self.manifest.spec: vectorsearch_names = self.manifest.spec.vectorsearches or [] links = LLMClientVectorsearches.objects.filter(llmclient=self.llmclient).select_related("vectorsearch") for link in links: if link.vectorsearch.name not in vectorsearch_names: link.delete() changed = True logger.debug("detached Vectorsearch %s from LLMClient %s", link.vectorsearch.name, self.name) for vectorsearch_name in vectorsearch_names: vectorsearch = self.resolve_vectorsearch(vectorsearch_name) if vectorsearch is None: raise SAMBrokerErrorNotFound( f"Vectorsearch {vectorsearch_name} not found, or not shared with {self.user_profile}", thing=self.kind, command=command, ) _, created = LLMClientVectorsearches.objects.get_or_create( llmclient=self.llmclient, vectorsearch=vectorsearch ) if created: changed = True logger.debug("attached Vectorsearch %s to LLMClient %s", vectorsearch.name, self.name) return changed
[docs] def prompt(self, request: HttpRequest, *args, **kwargs) -> SmarterJournaledJsonResponse: """ Not supported: the CLI does not prompt an LLMClient. :param request: The HTTP request. :param args: Positional arguments (unused). :param kwargs: Keyword arguments (unused). :raises SAMBrokerErrorNotImplemented: always. """ command = SmarterJournalCliCommands(self.prompt.__name__) raise SAMBrokerErrorNotImplemented(message="Prompt not implemented", thing=self.kind, command=command)
[docs] def describe(self, request: HttpRequest, *args, **kwargs) -> SmarterJournaledJsonResponse: """ Return the LLMClient as a manifest. :param request: The HTTP request. :param args: Positional arguments (unused). :param kwargs: Keyword arguments (unused). :returns: A response whose data is the LLMClient's manifest dict. :raises SAMBrokerErrorNotReady: if the broker has no name. :raises SAMBrokerErrorNotFound: if the LLMClient does not exist. :raises SAMLLMClientBrokerError: if the manifest cannot be built. """ command = SmarterJournalCliCommands(self.describe.__name__) if self.name is None: raise SAMBrokerErrorNotReady(f"{self.kind} name property is not set.", thing=self.kind, command=command) if self.llmclient: try: data = self.django_orm_to_manifest_dict() return self.json_response_ok(command=command, data=data) except Exception as e: logger.error( "failed to describe %s %s", self.kind, self.name, exc_info=True, ) raise SAMLLMClientBrokerError( f"Failed to describe {self.kind} {self.name}", thing=self.kind, command=command ) from e raise SAMBrokerErrorNotFound(f"{self.kind} {self.name} not found", thing=self.kind, command=command)
[docs] @classmethod def dependents(cls, instance: LLMClient) -> SAMDependents: """Return the Orchestrators that use an LLMClient. An LLMClient's Prompts are its chat history, not dependencies, so they are deleted with it. :param instance: The LLMClient. :type instance: LLMClient :return: The Orchestrators that list the LLMClient in their ``spec.llmClients``. :rtype: SAMDependents """ # pylint: disable=import-outside-toplevel from smarter.apps.api.v1.manifests.enum import SAMKinds from smarter.apps.orchestrator.models import Orchestrator, OrchestratorHarness orchestrators = Orchestrator.objects.filter( id__in=OrchestratorHarness.objects.filter(llmclient=instance).values("orchestrator_id") ) return [(SAMKinds.ORCHESTRATOR.value, orchestrators)]
[docs] @classmethod def references(cls, instance: LLMClient) -> SAMDependents: """Return the resources that an LLMClient uses. Its Provider, which ``spec.config.provider`` names, 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 of :meth:`dependency_tree`. :param instance: The LLMClient. :type instance: LLMClient :return: The resources that it uses. The plugins have their own kinds. :rtype: SAMDependents """ # The models that this module already imports are used as they are. These are imported here, # where they are used. # pylint: disable=import-outside-toplevel from smarter.apps.api.v1.manifests.enum import SAMKinds from smarter.apps.llmclient.models import LLMClientCustomDomain from smarter.apps.provider.manifest.brokers.provider import SAMProviderBroker def linked(link_model, field: str): return link_model.objects.filter(llmclient=instance).values(field) return [ (SAMKinds.PROVIDER.value, SAMProviderBroker.providers_named(instance.provider, instance.user_profile)), (None, PluginMeta.objects.filter(id__in=linked(LLMClientPlugin, "plugin_meta_id"))), (SAMKinds.MCP_CLIENT.value, MCPClient.objects.filter(id__in=linked(LLMClientMCPClients, "mcpclient_id"))), (SAMKinds.GUARDRAIL.value, Guardrail.objects.filter(id__in=linked(LLMClientGuardrails, "guardrail_id"))), ( SAMKinds.VECTORSEARCH.value, Vectorsearch.objects.filter(id__in=linked(LLMClientVectorsearches, "vectorsearch_id")), ), (Extension.__name__, Extension.objects.filter(id__in=linked(LLMClientExtensions, "extension_id"))), # custom_domain_id is the column of the custom_domain foreign key, which Django adds at runtime. ( SAMKinds.CUSTOM_DOMAIN.value, rows_with_pk(LLMClientCustomDomain.objects, instance.custom_domain_id), # type: ignore[attr-defined] ), (SAMKinds.AUTH_TOKEN.value, SmarterAuthToken.objects.filter(pk__in=linked(LLMClientAPIKey, "api_key_id"))), ]
[docs] @memoized_dependencies def dependencies(self) -> List[SAMDependency]: """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. :return: A broker for each Orchestrator that lists this LLMClient in its ``spec.llmClients``. :rtype: List[SAMDependency] """ return self.dependency_brokers_for(self.llmclient)
[docs] def delete(self, request: HttpRequest, *args, **kwargs) -> SmarterJournaledJsonResponse: """ 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. :param request: The HTTP request. :param args: Positional arguments (unused). :param kwargs: Keyword arguments (unused). :returns: A successful response with empty data. :raises SAMBrokerErrorNotReady: if the broker has no name. :raises SAMBrokerErrorNotFound: if the LLMClient does not exist. :raises SAMLLMClientBrokerError: if the delete fails. """ command = SmarterJournalCliCommands(self.delete.__name__) if self.name is None: raise SAMBrokerErrorNotReady(f"{self.kind} name property is not set.", thing=self.kind, command=command) self.verify_no_dependencies(command) if self.llmclient: try: # invalidate first: the llmclient no longer has an id once it is deleted. self.cache_invalidations() self.llmclient.delete() return self.json_response_ok(command=command, data={}) except Exception as e: logger.error( "failed to delete %s %s", self.kind, self.name, exc_info=True, ) raise SAMLLMClientBrokerError( f"Failed to delete {self.kind} {self.name}", thing=self.kind, command=command ) from e raise SAMBrokerErrorNotFound(f"{self.kind} {self.name} not found", thing=self.kind, command=command)
[docs] def deploy(self, request: HttpRequest, *args, **kwargs) -> SmarterJournaledJsonResponse: """ Set the LLMClient's ``deployed`` flag and save it. When the flag changes, ``LLMClient.save()`` sends ``llmclient_deploy``, whose receiver queues the ``deploy_default_api`` Celery task. :param request: The HTTP request. :param args: Positional arguments (unused). :param kwargs: Keyword arguments (unused). :returns: A successful response with empty data. :raises SAMBrokerErrorNotReady: if the broker has no name. :raises SAMBrokerErrorNotFound: if the LLMClient does not exist. :raises SAMLLMClientBrokerError: if the save fails. """ command = SmarterJournalCliCommands(self.deploy.__name__) if self.name is None: raise SAMBrokerErrorNotReady(f"{self.kind} name property is not set.", thing=self.kind, command=command) if self.llmclient: try: self.llmclient.deployed = True self.llmclient.save() self.llmclient.refresh_from_db() return self.json_response_ok(command=command, data={}) except Exception as e: logger.error( "failed to deploy %s %s", self.kind, self.name, exc_info=True, ) raise SAMLLMClientBrokerError( f"Failed to deploy {self.kind} {self.name}", thing=self.kind, command=command ) from e raise SAMBrokerErrorNotFound(f"{self.kind} {self.name} not found", thing=self.kind, command=command)
[docs] def undeploy(self, request: HttpRequest, *args, **kwargs) -> SmarterJournaledJsonResponse: """ Clear the LLMClient's ``deployed`` flag and save it. When the flag changes, ``LLMClient.save()`` sends ``llmclient_undeploy``, whose receiver queues the ``undeploy_default_api`` Celery task. :param request: The HTTP request. :param args: Positional arguments (unused). :param kwargs: Keyword arguments (unused). :returns: A successful response with empty data. :raises SAMBrokerErrorNotReady: if the broker has no name. :raises SAMBrokerErrorNotFound: if the LLMClient does not exist. :raises SAMLLMClientBrokerError: if the save fails. """ command = SmarterJournalCliCommands(self.undeploy.__name__) if self.name is None: raise SAMBrokerErrorNotReady(f"{self.kind} name property is not set.", thing=self.kind, command=command) if self.llmclient: try: self.llmclient.deployed = False self.llmclient.save() self.llmclient.refresh_from_db() return self.json_response_ok(command=command, data={}) except Exception as e: logger.error( "failed to undeploy %s %s", self.kind, self.name, exc_info=True, ) raise SAMLLMClientBrokerError( f"Failed to undeploy {self.kind} {self.name}", thing=self.kind, command=command ) from e raise SAMBrokerErrorNotFound(f"{self.kind} {self.name} not found", thing=self.kind, command=command)
[docs] def logs(self, request: HttpRequest, *args, **kwargs) -> SmarterJournaledJsonResponse: """ Return an empty logs response: LLMClient logs are not implemented. :param request: The HTTP request. :param args: Positional arguments (unused). :param kwargs: Keyword arguments (unused). :returns: A successful response whose data is an empty dict. """ command = SmarterJournalCliCommands(self.logs.__name__) data: SmarterDictType = {} return self.json_response_ok(command=command, data=data)