Source code for smarter.apps.llmclient.models.llmclient

"""LLMClient model."""

import warnings
from functools import cached_property
from typing import Optional
from urllib.parse import urljoin, urlparse

from cache_results import cache_results
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models

from smarter.apps.account.models import (
    Account,
    MetaDataWithOwnershipModel,
    SmarterQuerySetWithPermissions,
    User,
    UserProfile,
)
from smarter.apps.account.utils import (
    get_cached_admin_user_for_account,
    is_platform_staff,
)
from smarter.apps.llmclient.signals import (
    llmclient_deploy,
    llmclient_deploy_failed,
    llmclient_deploy_status_changed,
    llmclient_dns_failed,
    llmclient_dns_verification_initiated,
    llmclient_dns_verification_status_changed,
    llmclient_dns_verified,
    llmclient_undeploy,
)
from smarter.common.conf import smarter_settings
from smarter.common.exceptions import SmarterValueError
from smarter.common.helpers.llm import get_date_time_string
from smarter.common.utils import rfc1034_compliant_str
from smarter.lib import json, logging
from smarter.lib.django.shortcuts import reverse
from smarter.lib.django.validators import SmarterValidator
from smarter.lib.django.waffle.switches import SmarterWaffleSwitches
from smarter.lib.openai.enum import OPENAI_REASONING_EFFORTS

from .llmclient_custom_domain import LLMClientCustomDomain
from .llmclient_custom_domain_dns import LLMClientCustomDomainDNS

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


def validate_provider(value):
    """
    Validate that the provider is in the list of valid prompt providers.

    :param value: The provider value to validate.
    :raises ValidationError: If the provider is not valid.

    :returns: None
    """
    # pylint: disable=C0415
    from smarter.apps.provider.services.text_completion.providers import (
        smarter_compatible_client,
    )

    provider_names = [name.lower() for name in smarter_compatible_client.all]
    if value not in provider_names:
        raise ValidationError(
            "%(value)s is not a valid provider. Valid providers are: %(providers)s",
            params={"value": value, "providers": str(provider_names)},
        )


[docs] class LLMClient(MetaDataWithOwnershipModel): """ Implements the LLMClient API model for a customer account. This Django model represents an llmclient instance associated with a specific customer account. It provides configuration, deployment status, domain management, and API endpoint properties for each llmclient. The model supports multiple modes of operation (sandbox, custom, default), DNS verification, TLS certificate management, and integration with external providers. **Key Features** - Associates each llmclient with a customer :class:`Account`. - Supports custom domains and DNS verification via :class:`LLMClientCustomDomain`. - Tracks deployment status, TLS certificate issuance, and DNS verification. - Configures default provider, model, system role, temperature, and max tokens. - Provides properties for generating RFC 1034-compliant names, hosts, and URLs. - Supports sandbox, default, and custom domain modes. - Integrates with Django signals for deployment and verification events. - Serializes llmclient configuration for API and frontend consumption. **Usage Example** .. code-block:: python llmclient = LLMClient.objects.get(account=my_account, name="example") if llmclient.ready(): print(llmclient.url_llmclient) **Signals** - Emits signals on deployment, DNS verification, and certificate status changes. **See Also** - :class:`LLMClientCustomDomain` - :class:`LLMClientCustomDomainDNS` - :class:`LLMClientPlugin` - :class:`LLMClientAPIKey` - :class:`LLMClientExtensions` - :class:`LLMClientRequests` :raises SmarterValueError: If invalid URLs or domains are provided. :raises ValidationError: If provider is not valid. """ # pylint: disable=C0115 class Meta: verbose_name_plural = "LLMClients" constraints = [ models.UniqueConstraint(fields=["user_profile", "name"], name="llmclient_llmclient_unique"), ]
[docs] class Modes: """ LLMClient API Modes. Defines the operational mode of the LLMClient instance. Also affects the url scheme and hostname used to access the LLMClient API. """ SANDBOX = "sandbox" CUSTOM = "custom" DEFAULT = "default" UNKNOWN = "unknown"
[docs] class Schemes: """LLMClient API Schemes.""" HTTP = "http" HTTPS = "https"
[docs] class DnsVerificationStatusChoices(models.TextChoices): """ DNS Verification Status Choices for LLMClient Custom Domains. This is managed by the asynchronous LLMClient deployment process. """ VERIFYING = "Verifying", "Verifying" NOT_VERIFIED = "Not Verified", "Not Verified" VERIFIED = "Verified", "Verified" FAILED = "Failed", "Failed"
[docs] class TlsCertificateIssuanceStatusChoices(models.TextChoices): """ TLS Certificate Issuance Status Choices for LLMClient Custom Domains. This is managed by the asynchronous LLMClient deployment process. """ NO_CERTIFICATE = "No Certificate", "No Certificate" REQUESTED = "Requested", "Requested" ISSUED = "Issued", "Issued" FAILED = "Failed", "Failed"
# objects: MetaDataWithOwnershipModelManager["LLMClient"] = MetaDataWithOwnershipModelManager() #: The subdomain DNS record associated with this LLMClient. #: Example: LLMClientCustomDomainDNS(id=1, domain="my-llmclient.example.com") subdomain = models.OneToOneField(LLMClientCustomDomainDNS, on_delete=models.CASCADE, blank=True, null=True) #: The custom domain associated with this LLMClient. #: Example: LLMClientCustomDomain(id=1, domain="example.com") custom_domain = models.OneToOneField(LLMClientCustomDomain, on_delete=models.CASCADE, blank=True, null=True) #: Indicates whether the LLMClient is deployed and accessible via its custom or default domain. #: Modifying this value triggers asynchronous deployment or undeployment processes. #: Example: True deployed = models.BooleanField(default=False, blank=True, null=True) #: The Smarter Provider for the LLMClient's language model. #: Example: "openai" provider = models.CharField( default=smarter_settings.llm_default_provider, max_length=255, blank=True, null=True, validators=[validate_provider], ) #: The default language model used by the LLMClient. #: Example: "gpt-6-luna" default_model = models.CharField(max_length=255, blank=True, null=True) #: The default system role prompt for the LLMClient. #: Example: "You are a helpful assistant." default_system_role = models.TextField(default=smarter_settings.llm_default_system_role, blank=True, null=True) #: The default temperature setting for the LLMClient's language model. #: Example: 0.7 default_temperature = models.FloatField(default=smarter_settings.llm_default_temperature, blank=True, null=True) #: How much a reasoning model reasons before it answers, the chat completions api's #: ``reasoning_effort``. None leaves it to the model's own default. #: Example: "high" default_reasoning_effort = models.CharField( max_length=16, choices=[(effort, effort) for effort in OPENAI_REASONING_EFFORTS], blank=True, null=True, ) #: The default maximum tokens for the LLMClient's language model responses. #: Example: 1024 default_max_tokens = models.IntegerField(default=smarter_settings.llm_default_max_tokens, blank=True, null=True) #: The LLMClient UI configuration fields. Appears in the title bar of the Smarter React LLMClient component. #: Example: "Stackademy Support Bot" app_name = models.CharField(default="llmclient", max_length=255, blank=True, null=True) #: The LLMClient UI configuration fields. Appears in the text input area placeholder. #: Example: "Stan" app_assistant = models.CharField(default="Smarter", max_length=255, blank=True, null=True) #: The LLMClient UI configuration fields. Appears in the welcome message area of the Smarter React LLMClient component. #: Example: "Welcome to Stackademy!" app_welcome_message = models.CharField(default="Welcome to the llmclient!", max_length=255, blank=True, null=True) #: The LLMClient UI configuration fields. Example prompts shown to the user in the Smarter React LLMClient component. #: Example: ["What AI courses do you offer?", "Is your program free?"] app_example_prompts = models.JSONField( default=list, blank=True, null=True, encoder=json.SmarterJSONEncoder, ) #: The LLMClient UI configuration fields. Placeholder text in the prompt input area. #: Example: "Ask me anything about Stackademy..." app_placeholder = models.CharField(default="Type something here...", max_length=255, blank=True, null=True) #: The LLMClient UI configuration fields. URL to the app information button in the top-right #: of the Smarter React LLMClient component. #: Example: "https://smarter.sh" app_info_url = models.URLField(default="https://smarter.sh", blank=True, null=True) #: The LLMClient UI configuration fields. Enables or disables file attachment feature in the Smarter React LLMClient component. #: Example: True app_file_attachment = models.BooleanField(default=False, blank=True, null=True) #: The look of the LLMClient's chat: its manifest's ``spec.config.styles``, validated by #: :class:`~smarter.apps.llmclient.manifest.models.llmclient.styles.SAMLLMClientSpecConfigStyles`, #: with its camelCase keys, and without the settings that the manifest leaves out. #: Example: {"appLogoUrl": "https://cdn.smarter.sh/images/logo/smarter-crop.png", #: "conversationHeader": {"backgroundColor": "#1b1f3b"}} styles = models.JSONField( default=dict, blank=True, null=True, encoder=json.SmarterJSONEncoder, ) #: The origins of the web pages that may call the LLMClient from a browser, with the @smarter.sh/ui-chat #: React component, in addition to those that the platform's CORS settings allow. See #: :mod:`smarter.apps.llmclient.cors`. #: Example: ["https://www.example.com"] allowed_origins = models.JSONField( default=list, blank=True, encoder=json.SmarterJSONEncoder, ) #: Whether only the platform's own staff may see and use the LLMClient, e.g. ``smarter_sysadmin``, #: whose MCPClient reads the platform's logs and its users' accounts. See #: :func:`~smarter.apps.account.utils.is_platform_staff` and :meth:`restrict_readable`. #: Example: True staff_only = models.BooleanField(default=False) # : The DNS verification status of the LLMClient's custom domain. This is part of the deployment process and is managed by # : the asynchronous LLMClient deployment workflow. # : Example: "Verified" dns_verification_status = models.CharField( max_length=255, default=DnsVerificationStatusChoices.NOT_VERIFIED, blank=True, null=True, choices=DnsVerificationStatusChoices, ) # : The TLS certificate issuance status of the LLMClient's custom domain. This is part of the deployment process and is managed by # : the asynchronous LLMClient deployment workflow. # : Example: "Issued" tls_certificate_issuance_status = models.CharField( max_length=255, default=TlsCertificateIssuanceStatusChoices.NO_CERTIFICATE, blank=True, null=True, choices=TlsCertificateIssuanceStatusChoices, ) def __str__(self) -> str: """ The LLMClient's name and id. Not its :attr:`url`, which reads the account's admin user from the cache: log records format LLMClients often, e.g. several times per request of Smarter Chat's configuration api. """ return f"{self.name} ({self.pk})" if self.name else "undefined"
[docs] @classmethod def restrict_readable( cls, queryset: "SmarterQuerySetWithPermissions[LLMClient]", user: User ) -> "SmarterQuerySetWithPermissions[LLMClient]": """ Hide the staff-only LLMClients from a user who is not one of the platform's staff. Called last by :meth:`~smarter.apps.account.models.metadata_with_ownership.SmarterQuerySetWithPermissions.with_read_permission_for`, so that a staff-only LLMClient, e.g. ``smarter_sysadmin``, is in no list, workbench or api of anyone else, even a superuser of another account. **Side effects:** one database query, by :func:`~smarter.apps.account.utils.is_platform_staff`. :param queryset: The LLMClients that the user's account and the Smarter account let them read. :param user: The user. :returns: The queryset, without the staff-only LLMClients unless the user is one of the platform's staff. """ if is_platform_staff(user): return queryset visible = queryset.exclude(staff_only=True) return visible
@property def is_billable_resource(self) -> bool: """ Indicates whether the model instance is considered a billable resource. This property can be overridden in subclasses to specify which models are billable. By default, it returns False, indicating that the base TimestampedModel is not billable. :returns: True if the instance is billable, False otherwise. :rtype: bool """ return True @property def rfc1034_compliant_name(self) -> str: """ Returns a RFC 1034 compliant name for the LLMClient. This name is used in the hostname of the LLMClient's default and custom URLs. The name is constructed by combining the LLMClient's name and the username of the associated user profile, separated by a dot. The resulting name adheres to the following rules: - lower case - alphanumeric characters and hyphens only [a-z0-9-] - starts and ends with an alphanumeric character - max length of 63 characters - no consecutive hyphens - no leading or trailing hyphens - no underscores or special characters - no spaces - no dots except for separating the LLMClient name and username - no more than one dot Examples: - For a LLMClient with name "example" and associated user profile "adminuser", that IS the account admin, the resulting RFC 1034 compliant name would be "example" - For a LLMClient with name "example" and associated user profile "user123", that is NOT the account admin, the resulting RFC 1034 compliant name would be "example.user123" :returns: RFC 1034 compliant name :rtype: str """ user_profile: UserProfile = self.user_profile admin_user = get_cached_admin_user_for_account(account=user_profile.cached_account) # type: ignore[arg-type] if user_profile.cached_user == admin_user: raw_str = self.name else: # note: rfc1034_compliant_str() filters out the "." raw_str = f"{self.name}-{user_profile.user.username}" return rfc1034_compliant_str(raw_str) @property def default_system_role_enhanced(self) -> str: """ Prepends a date/time string to the default_system_role. Example: "2024-06-01 12:00:00 System: You are a helpful assistant." :returns: enhanced system role string :rtype: str """ return f"{get_date_time_string()}{self.default_system_role}" @property def base_api_domain(self) -> str: """ The base API domain for the LLMClient. This is the domain that is used in the default hostname for the LLMClient. Examples: example 1. given: - environment is "alpha" - environment API domain "alpha.api.example.com" the resulting base API domain would be: 'alpha.api.example.com' example 2. given: - environment is "local" - environment API domain "api.localhost:9357" the resulting base API domain would be: 'api.local.example.com' """ return smarter_settings.environment_api_dns_domain @property def base_default_host(self) -> str: """ The base default hostname for the LLMClient. This is the part of the hostname that comes after the RFC 1034 compliant name. It includes the account number and the environment API domain. Examples: example 1. given: - a LLMClient associated with an account number "1234-5678-9012" - environment is "alpha" - environment API domain "alpha.api.example.com" the resulting base default host would be: '.1234-5678-9012.alpha.api.example.com' example 2. given: - a LLMClient associated with an account number "1234-5678-9012" - environment is "local" - environment API domain "api.localhost:9357" the resulting base default host would be: '.1234-5678-9012.api.local.example.com' """ user_profile: UserProfile = self.user_profile return f"{user_profile.account.account_number}.{self.base_api_domain}" @property def default_host(self) -> str: """ The default hostname for the LLMClient. Examples: example 1. given: - self.name: 'example' - self.account.account_number: '1234-5678-9012' - smarter_settings.environment = "alpha" - smarter_settings.environment_api_domain: 'alpha.api.example.com' The domain would be: 'example.1234-5678-9012.alpha.api.example.com' example 2. given: - self.name: 'example' - self.account.account_number: '1234-5678-9012' - smarter_settings.environment = "local" - smarter_settings.environment_api_domain: 'api.localhost:9357' The domain would be: 'example.1234-5678-9012.api.local.example.com' :returns: default hostname :rtype: str """ domain = f"{self.rfc1034_compliant_name}.{self.base_default_host}" SmarterValidator.validate_domain(domain) return domain @property def default_url_host(self) -> str: """ The host at which the platform serves the deployed LLMClient, the host of :attr:`default_url`. In an AWS environment, it is :attr:`default_host`. In local Docker, :attr:`default_host` is in the developers' shared DNS zone, e.g. ``api.local.example.com``, which doesn't resolve to the computer that runs the platform, while the platform's own api domain is a localhost domain, which every browser resolves to that computer, and which the platform answers. Examples: - an AWS environment: 'example.1234-5678-9012.alpha.api.example.com' - local Docker: 'example.1234-5678-9012.api.localhost:9357' :returns: The host of the LLMClient's default url. :rtype: str """ user_profile: UserProfile = self.user_profile account_number = user_profile.account.account_number host = f"{self.rfc1034_compliant_name}.{account_number}.{smarter_settings.environment_api_domain}" return host @property def default_url(self) -> str: """ The default URL for the LLMClient: the url at which it answers once it is deployed. Its host is :attr:`default_url_host`, which is :attr:`default_host` except in local Docker. DNS records, ingresses and certificates use :attr:`default_host`, never this url. example 'https://example.1234-5678-9012.alpha.api.example.com' :returns: default URL :rtype: str """ url = SmarterValidator.urlify(self.default_url_host, environment=smarter_settings.environment) return url # type: ignore[return-value] @property def custom_host(self) -> Optional[str]: """ The custom hostname for the LLMClient. Examples: - self.name: 'example' - self.custom_domain.domain_name: 'example.com' example 'example.example.com' :returns: custom hostname :rtype: Optional[str] """ if self.custom_domain and self.custom_domain.is_verified: domain = f"{self.rfc1034_compliant_name}.{self.custom_domain.domain_name}" SmarterValidator.validate_domain(domain) return domain return None @property def custom_url(self) -> Optional[str]: """ The custom URL for the LLMClient. example 'https://example.example.com' :returns: custom URL :rtype: Optional[str] """ if self.custom_host: return SmarterValidator.urlify(self.custom_host, environment=smarter_settings.environment) # type: ignore[return-value] return None @property def sandbox_host(self) -> str: """ The sandbox hostname for the LLMClient. This is the hostname that is used when the LLMClient is in sandbox mode. For example, when the LLMClient is being used in the Smarter Workbench. example 'alpha.platform.smarter.sh' :returns: sandbox hostname :rtype: str """ return smarter_settings.environment_platform_domain @property def sandbox_url(self) -> str: """ The sandbox URL for the LLMClient. This is the URL that is used when the LLMClient is in sandbox mode. For example, when the LLMClient is being used in the Smarter Workbench. maps to "<int:llmclient_id>/" example: 'https://alpha.platform.smarter.sh/workbench/llm-clients/<str:hashed_id>/' :returns: sandbox URL :rtype: str """ # pylint: disable=C0415 from smarter.apps.prompt.urls import PromptReverseNames path = reverse(f"{PromptReverseNames.namespace}:{PromptReverseNames.sandbox_by_hashed_id}", kwargs={"hashed_id": self.hashed_id}, urlconf=settings.ROOT_URLCONF) # type: ignore[arg-type] url = urljoin(smarter_settings.environment_url, path) url = SmarterValidator.urlify(url, environment=smarter_settings.environment) # type: ignore[return-value] return url @property def manifest_url(self) -> str: """ The URL for the LLMClient's manifest file. This is used for integration with external platforms that require a manifest URL. example: 'https://alpha.platform.smarter.sh/workbench/llm-clients/<str:hashed_id>/manifest/' :returns: manifest URL :rtype: str """ # pylint: disable=C0415 from smarter.apps.prompt.urls import PromptReverseNames path = reverse(f"{PromptReverseNames.namespace}:{PromptReverseNames.manifest_by_hashed_id}", kwargs={"hashed_id": self.hashed_id}, urlconf=settings.ROOT_URLCONF) # type: ignore[arg-type] url = urljoin(smarter_settings.environment_url, path) url = SmarterValidator.urlify(url, environment=smarter_settings.environment) # type: ignore[return-value] return url @property def workbench_url(self) -> str: """ The URL of the LLMClient's Prompt Engineer's Workbench, in the web console. example: 'https://alpha.platform.smarter.sh/workbench/llm-clients/<str:hashed_id>/prompt/' :returns: workbench URL :rtype: str """ # pylint: disable=C0415 from smarter.apps.prompt.urls import PromptReverseNames path = reverse(f"{PromptReverseNames.namespace}:{PromptReverseNames.chat_by_hashed_id}", kwargs={"hashed_id": self.hashed_id}, urlconf=settings.ROOT_URLCONF) # type: ignore[arg-type] url = urljoin(smarter_settings.environment_url, path) url = SmarterValidator.urlify(url, environment=smarter_settings.environment) # type: ignore[return-value] return url @property def hostname(self) -> str: """ The hostname for the LLMClient depending on its deployment status. Returns either the custom hostname (if deployed), the default hostname, or the sandbox hostname. :returns: hostname :rtype: str """ if self.deployed: return self.custom_host or self.default_host return self.sandbox_host @property def url(self) -> str: """ The URL for the LLMClient depending on its deployment status. example: 'https://my-llmclient.1234-5678-9012.alpha.api.example.com' (custom, deployed) :returns: URL :rtype: str """ if self.deployed: return self.custom_url or self.default_url return self.sandbox_url @property def url_llmclient(self) -> str: """ The Smarter Api url returned by PromptConfigView.config() as the key, "url_llmclient". This url is consumed by React.js app for http requests on new prompts. maps to "<int:llmclient_id>/prompt/" example: "http://localhost:9357/api/v1/llm-clients/5174/prompt/" :returns: URL for llmclient API :rtype: str """ # pylint: disable=C0415 from smarter.apps.llmclient.api.v1.urls import LLMClientApiV1ReverseViews path = reverse( f"{LLMClientApiV1ReverseViews.namespace}:{LLMClientApiV1ReverseViews.default_llmclient_api_view_by_hashed_id}", kwargs={"hashed_id": self.hashed_id}, urlconf=settings.ROOT_URLCONF, ) url = urljoin(smarter_settings.environment_url, path) url = SmarterValidator.urlify(url, environment=smarter_settings.environment) # type: ignore[return-value] if not isinstance(url, str): raise SmarterValueError("LLMClient.url_llmclient is not a valid string") return url @property def url_chat_config(self) -> str: """ The Smarter Api url for the Prompt config json dict. The React.js app requests this url during react app startup to retrieve the UI configuration for the llmclient. maps to "<int:llmclient_id>/config/" example: "http://localhost:9357/api/v1/llm-clients/5174/config/" :returns: URL for llmclient config API :rtype: str """ # pylint: disable=C0415 from smarter.apps.llmclient.api.v1.urls import LLMClientApiV1ReverseViews path = reverse( f"{LLMClientApiV1ReverseViews.namespace}:{LLMClientApiV1ReverseViews.chat_config_view_by_hashed_id}", kwargs={"hashed_id": self.hashed_id}, urlconf=settings.ROOT_URLCONF, ) url = urljoin(smarter_settings.environment_url, path) url = SmarterValidator.urlify(url, environment=smarter_settings.environment) # type: ignore[return-value] return url @property def url_chatapp(self) -> str: """ (Deprecated) The Smarter Api url for the ChatApp endpoint. This url is used by the React.js app to load the ChatApp web page. maps to "prompt/" """ warnings.warn( "LLMClient.url_chatapp is deprecated and will be removed in a future release.", DeprecationWarning, stacklevel=2, ) # pylint: disable=C0415 from smarter.apps.prompt.urls import PromptReverseNames path = reverse(f"{PromptReverseNames.namespace}:{PromptReverseNames.chat_by_hashed_id}", kwargs={"hashed_id": self.hashed_id}, urlconf=settings.ROOT_URLCONF) # type: ignore[arg-type] url = urljoin(smarter_settings.environment_url, path) url = SmarterValidator.urlify(url, environment=smarter_settings.environment) # type: ignore[return-value] return url @property def ready(self) -> bool: """ The readiness status of the LLMClient. A LLMClient is ready if it is its in sandbox mode, or, if it is: - deployed - has a verified DNS A record - has a valid, issued tls certificate. :returns: readiness status :rtype: bool """ if isinstance(self.url, str) and self.mode(self.url) == self.Modes.SANDBOX: return True if self.dns_verification_status != self.DnsVerificationStatusChoices.VERIFIED: logger.warning( "LLMClient %s is not ready. DNS verification status is %s", self.rfc1034_compliant_name, self.dns_verification_status, ) return False if self.tls_certificate_issuance_status != self.TlsCertificateIssuanceStatusChoices.ISSUED: logger.warning( "LLMClient %s is not ready. TLS certificate issuance status is %s", self.rfc1034_compliant_name, self.tls_certificate_issuance_status, ) return False if not self.deployed: logger.warning("LLMClient %s is not ready. It is not deployed.", self.rfc1034_compliant_name) return False return True
[docs] @cached_property def is_authentication_required(self) -> bool: """ Determines if authentication is required to access the LLMClient. :returns: ``True`` if authentication is required, otherwise ``False``. :rtype: bool """ # pylint: disable=C0415 from smarter.apps.llmclient.models.llmclient_api_key import LLMClientAPIKey llmclientapikeys = LLMClientAPIKey.get_cached_objects(llmclient=self) if llmclientapikeys.filter(api_key__is_active=True).exists(): return True return False
def _hostname_of(self, attribute: str) -> Optional[str]: """ Return one of the LLMClient's hosts as the hostname of its url in this environment, with its port, or None. :param attribute: The name of the host's property, e.g. ``default_host``. :returns: The hostname, or None if the LLMClient has no such host, or it isn't valid. :rtype: Optional[str] """ try: host = getattr(self, attribute) if not host: return None url = SmarterValidator.urlify(host, environment=smarter_settings.environment) except SmarterValueError: return None if not url: return None hostname = urlparse(url).netloc return hostname
[docs] def mode(self, url: str) -> str: """ Determine the mode of the LLMClient based on the provided URL. :param url: The URL to evaluate. :returns: The mode of the LLMClient (sandbox, custom, default, unknown). :rtype: str """ logger.debug("mode: %s", url) if not url: return self.Modes.UNKNOWN SmarterValidator.validate_url(url) url = SmarterValidator.urlify(url, environment=smarter_settings.environment) # type: ignore[return-value] parsed_url = urlparse(url) input_hostname = parsed_url.netloc # most likely case first when running in production, at scale. In local Docker, the # llmclient answers at its default url's host, which differs from its default host. # The custom domain is the least likely case. hosts_by_mode = ( ("default_host", self.Modes.DEFAULT), ("default_url_host", self.Modes.DEFAULT), ("sandbox_host", self.Modes.SANDBOX), ("custom_host", self.Modes.CUSTOM), ) for attribute, mode in hosts_by_mode: hostname = self._hostname_of(attribute) if hostname and input_hostname == hostname: return mode logger.error( "Invalid LLMClient url %s received for default_url: %s, sandbox_url: %s, custom_url: %a", url, self.default_url, self.sandbox_url, self.custom_url, ) # default to default mode as a safety measure return self.Modes.UNKNOWN
[docs] @classmethod def get_cached_object( cls, *args, invalidate: Optional[bool] = False, pk: Optional[int] = None, name: Optional[str] = None, user: Optional[User] = None, user_profile: Optional[UserProfile] = None, account: Optional[Account] = None, **kwargs, ) -> "LLMClient": """ Retrieve a model instance using caching to optimize performance. Example usage: .. code-block:: python # Retrieve a LLMClient instance by primary key with caching llmclient = LLMClient.get_cached_object(pk=1) # Retrieve a LLMClient instance by name and user profile with caching llmclient = LLMClient.get_cached_object(name="example", user_profile=my_user_profile) :param pk: The primary key of the model instance to retrieve. :param name: The name of the model instance to retrieve. :param user: The user associated with the model instance. :param user_profile: The user profile associated with the model instance. :param account: The account associated with the model instance. :returns: The model instance if found, otherwise None. :rtype: Optional["LLMClient"] """ logger.debug( "called %s with pk=%s, name=%s, user=%s, user_profile=%s, account=%s, invalidate=%s", cls.__name__, pk, name, user, user_profile, account, invalidate, ) retval = super().get_cached_object(*args, invalidate=invalidate, pk=pk, name=name, user=user, user_profile=user_profile, account=account, **kwargs) # type: ignore[assignment] if retval is None: raise LLMClient.DoesNotExist(f"{cls.__name__} matching query does not exist.") return retval # type: ignore[return-value]
[docs] @classmethod def get_cached_objects( cls, invalidate: Optional[bool] = False, user_profile: Optional[UserProfile] = None, taggit=True, **kwargs ) -> models.QuerySet["LLMClient"]: """ Retrieve a list of LLMClient instances associated with a user profile using caching. Example usage: .. code-block:: python # Retrieve LLMClient instances for a user profile with caching llmclients = LLMClient.get_cached_objects(my_user_profile, invalidate=True) :param invalidate: Whether to invalidate the cache for this retrieval. :param user_profile: The user profile for which to retrieve LLMClient instances. :param taggit: Unused. Accepted for the signature of the base class. :param kwargs: Unused. Accepted for the signature of the base class. :returns: A queryset of LLMClient instances associated with the user profile. :rtype: models.QuerySet["LLMClient"] """ @cache_results() def _get_llmclients_for_user_profile_id( user_profile_id: int, class_name: str = cls.__name__ ) -> models.QuerySet["LLMClient"]: logger.debug("called with user_profile=%s, invalidate=%s", user_profile, invalidate) retval = ( cls.objects.with_read_permission_for(user=user_profile.user) # type: ignore .prefetch_related("tags") .select_related("user_profile", "user_profile__account", "user_profile__user") ) logger.debug( "fetched and cached %s llmclients for user_profile_id: %s", len(retval), user_profile_id, ) return retval if invalidate and user_profile: _get_llmclients_for_user_profile_id.invalidate(user_profile_id=user_profile.id, class_name=cls.__name__) # type: ignore[union-attr] if user_profile: return _get_llmclients_for_user_profile_id(user_profile_id=user_profile.id, class_name=cls.__name__) # type: ignore[return-value] return super().get_cached_objects(user_profile=user_profile, invalidate=invalidate) # type: ignore[return-value]
[docs] def save(self, *args, asynchronous=False, **kwargs): """ Override save() to validate domain and send signals on status changes. :raises SmarterValueError: If invalid hostname is provided. :args: Positional arguments for the save method. :asynchronous: If True, skips signal sending for asynchronous operations. :kwargs: Keyword arguments for the save method. :returns: None """ logger.debug("called for LLMClient id: %s %s", self.pk, self.default_host) if asynchronous: logger.debug( "running in asynchronous mode for LLMClient id: %s. Skipping signal sending.", self.pk, ) super().save(*args, **kwargs) return is_new = self.pk is None SmarterValidator.validate_domain(self.hostname) should_deploy = False should_undeploy = False if is_new: if self.deployed: llmclient_deploy.send(sender=self.__class__, llmclient=self) else: orig: LLMClient try: orig = LLMClient.objects.get(id=self.pk) except LLMClient.DoesNotExist: logger.error("could not find original LLMClient with id: %s", self.pk) return super().save(*args, **kwargs) if orig.dns_verification_status != self.dns_verification_status: llmclient_dns_verification_status_changed.send(sender=self.__class__, llmclient=self) llmclient_deploy_status_changed.send(sender=self.__class__, llmclient=self) if self.dns_verification_status == LLMClient.DnsVerificationStatusChoices.VERIFYING: llmclient_dns_verification_initiated.send(sender=self.__class__, llmclient=self) if self.dns_verification_status == LLMClient.DnsVerificationStatusChoices.VERIFIED: llmclient_dns_verified.send(sender=self.__class__, llmclient=self) if self.dns_verification_status == LLMClient.DnsVerificationStatusChoices.FAILED: llmclient_dns_failed.send(sender=self.__class__, llmclient=self) llmclient_deploy_failed.send(sender=self.__class__, llmclient=self) if self.deployed and not orig.deployed: should_deploy = True if not self.deployed and orig.deployed: should_undeploy = True super().save(*args, **kwargs) if should_deploy: llmclient_deploy.send(sender=self.__class__, llmclient=self) if should_undeploy: llmclient_undeploy.send(sender=self.__class__, llmclient=self)
# pylint: disable=C0415
[docs] def clone( self, new_name: Optional[str] = None, new_version: Optional[str] = None, user_profile: Optional[UserProfile] = None, ) -> "LLMClient": """ Clone the LLMClient instance, creating a new instance with the same configuration. The clone has the same plugins, MCPClients, guardrails, Vectorsearches and extensions, except those that its owner may not use: see :meth:`clone_links`. :param new_name: Optional new name for the cloned LLMClient. If not provided, the name will be suffixed with "-copy". :param new_version: Optional new version for the cloned LLMClient. :param user_profile: Optional owner of the cloned LLMClient; this LLMClient's owner if not provided. :returns: The cloned LLMClient instance. :rtype: LLMClient """ logger.debug( "called for LLMClient id: %s with new_name: %s, new_version: %s, user_profile: %s", self.pk, new_name, new_version, user_profile, ) cloned_llmclient = super().clone(new_name=new_name, new_version=new_version, user_profile=user_profile) # type: ignore self.clone_links(cloned_llmclient) # type: ignore[arg-type] logger.debug("completed Returning cloned instance %s", cloned_llmclient) return cloned_llmclient # type: ignore[return-value]
__all__ = ["LLMClient"]