Source code for smarter.apps.prompt.views.detailviews.prompt_config_view

# pylint: disable=W0613,C0302
"""PromptConfigView is a Django class-based view responsible for providing configuration data to the ReactJS prompt UI component in the Smarter web application."""

from typing import Optional, Union

from django.db.models import QuerySet
from django.http import (
    HttpRequest,
    HttpResponse,
    HttpResponseNotAllowed,
    JsonResponse,
)
from pydantic import ValidationError

from smarter.apps.account.models import get_resolved_user
from smarter.apps.account.utils import is_platform_staff
from smarter.apps.llmclient.models import (
    LLMClient,
    LLMClientExtensions,
    LLMClientHelper,
    LLMClientPlugin,
    LLMClientRequests,
    get_cached_llmclient_by_request,
    get_cached_llmclient_tool_counts,
)
from smarter.apps.llmclient.serializers import (
    LLMClientConfigSerializer,
)
from smarter.apps.llmtool.models import (
    PluginSelectorHistory,
)
from smarter.apps.prompt.contract.builders import (
    PromptChatApiError,
    PromptChatApiErrorForbidden,
    PromptChatApiErrorInternal,
    PromptChatApiErrorNotFound,
    chat_error_response,
    requested_contract,
)
from smarter.apps.prompt.contract.const import (
    CHAT_CONTRACT_V1,
    CHAT_CONTRACT_V2,
    VERBOSE_PARAMETER,
    VERBOSE_VALUES,
)
from smarter.apps.prompt.contract.models import (
    PromptChatApiConfig,
    PromptChatApiExtensionList,
    PromptChatApiHistory,
    PromptChatApiListMetaData,
    PromptChatApiLLMClient,
    PromptChatApiLLMClientExtension,
    PromptChatApiLLMClientPlugin,
    PromptChatApiLLMClientRequest,
    PromptChatApiMetaData,
    PromptChatApiPluginList,
    PromptChatApiPluginSelection,
    PromptChatApiPromptPluginUsage,
    PromptChatApiPromptToolCall,
)
from smarter.apps.prompt.journal import chat_history_source
from smarter.apps.prompt.models import PromptHistory
from smarter.apps.prompt.signals import prompt_config_invoked
from smarter.apps.prompt.views.detailviews.prompt_workbench_view import (
    SmarterPromptSession,
)
from smarter.common.conf import smarter_settings
from smarter.common.const import (
    SmarterHttpMethods,
)
from smarter.common.helpers.url_helpers import clean_url
from smarter.common.utils import is_authenticated_request, mask_identifier
from smarter.lib import logging
from smarter.lib.django import waffle
from smarter.lib.django.validators import SmarterValidator
from smarter.lib.django.views import (
    SmarterOptionallyAuthenticatedApiView,
)
from smarter.lib.django.waffle import SmarterWaffleSwitches
from smarter.lib.drf.views.helpers import UnauthenticatedPermissionClass
from smarter.lib.journal.enum import SmarterJournalCliCommands, SmarterJournalThings
from smarter.lib.journal.http import (
    SmarterJournaledJsonErrorResponse,
    SmarterJournaledJsonResponse,
)
from smarter.lib.logging.redis_log_handler import session_key_context, valid_session_key
from smarter.lib.typing import SmarterDictType

MAX_RETURNED_PLUGINS = 10


[docs] def should_log(level): """Check if logging should be done based on the waffle switch.""" return waffle.switch_is_active(SmarterWaffleSwitches.PROMPT_LOGGING)
logger = logging.getSmarterLogger(__name__, condition_func=should_log)
[docs] def should_log_verbose(level): """Check if logging should be done based on the waffle switch.""" return smarter_settings.verbose_logging
verbose_logger = logging.getSmarterLogger(__name__, condition_func=should_log_verbose)
[docs] class PromptConfigView(SmarterOptionallyAuthenticatedApiView): """ Prompt configuration view for the Smarter web application. This view is responsible for providing all configuration information required by the ReactJS prompt UI component. It is designed to be performant and efficient, as it is invoked on every user-facing browser load and refresh. **Key Features:** - **Django Template-Based:** This view uses Django's template system for rendering and does not rely on Django REST Framework (DRF) serializers for its main response. The configuration data is returned as a JSON response, but the view itself is structured as a Django class-based view. - **CSRF Exempt:** The view is decorated with `@csrf_exempt` because it is read-only and does not modify server-side data. This exemption is safe in this context and avoids unnecessary CSRF validation for GET and POST requests that only retrieve configuration data. - **ReactJS UI Integration:** The endpoint provides all necessary configuration and context information for the ReactJS prompt component. This includes llmclient metadata, plugin information, session keys, and historical data relevant to the prompt session. The React app consumes this configuration to initialize and render the prompt UI in the user's browser. - **Session-Based Architecture:** Each prompt session is uniquely identified and managed by a globally unique 64-character session key. The session key is generated by RequestHelper.generate_session_key() and is persisted by the browser in a domain and path-specific cookie, meaning that this design supports an unlimited number of concurrent sessions per user, one per device per llmclient. - **Performance Considerations:** Since this endpoint is called on every browser load and refresh, performance is a primary concern. The view is optimized to minimize database queries and serialization overhead. Only a limited number of plugins (as defined by `MAX_RETURNED_PLUGINS`) are returned to avoid excessive payload sizes. Caching and efficient queryset usage are employed where possible to ensure fast response times for end users. **Example Usage:** https://smarter.3141-5926-5359.alpha.api.example.com/config/ **Returns:** JSON response containing: - `session_key`: Unique identifier for the prompt session. - `sandbox_mode`: Boolean indicating if the llmclient is running in sandbox mode. - `debug_mode`: Boolean indicating if debug mode is enabled. - `llmclient`: Serialized llmclient configuration. - `history`: The session's messages, and, with ``?verbose=true``, its tool calls. - `meta_data`: The llmclient's state, and, with ``?verbose=true``, the complete LLMClientHelper. - `plugins` and `extensions`: Their counts, and, with ``?verbose=true``, a limited list of each. See :attr:`verbose`. **Security:** - The view is protected and requires the user to be authenticated, unless the llmclient is configured to allow unauthenticated access. - If authentication is required and the user is not authenticated, a 403 Forbidden response is returned. **See Also:** - `SmarterPromptSession`: Helper class for managing prompt sessions. - `LLMClientConfigSerializer`: Serializer for the llmclient's data. - `LLMClientHelper`: Helper for llmclient-related operations. """ authentication_classes = None permission_classes = (UnauthenticatedPermissionClass,) thing: Optional[SmarterJournalThings] = None command: Optional[SmarterJournalCliCommands] = None session: Optional[SmarterPromptSession] = None legacy_keys: bool = True """Rename keys for older versions of the React app ('llmclient' to 'chatbot'), in version 1 of the contract. The cli passes as_view(legacy_keys=False). """ include_diagnostics: bool = False """Return the complete configuration, whatever url resolved the LLMClient. The cli passes as_view(include_diagnostics=True). See :meth:`full_config`. """ contract: int = CHAT_CONTRACT_V1 """The version of the contract that the client asked for. See :func:`~smarter.apps.prompt.contract.builders.requested_contract`. """ resolved_by_id: bool = False """True if the LLMClient was found by its id or hashed id, which also checks that the user may read it.""" verbose_requested: bool = False """True if the request's query string has ``?verbose=true``. See :attr:`verbose`. """ llmclient_name: Optional[str] = None _llmclient_helper: Optional[LLMClientHelper] = None _llmclient: Optional[LLMClient] = None chat_history_row: Optional[PromptHistory] = None """The PromptHistory row that :meth:`chat_history` read the thread from, which the journal reads again.""" @property def formatted_class_name(self) -> str: """Returns a formatted string of the class name for logging purposes.""" class_name = f"{__name__}.{PromptConfigView.__name__}[{id(self)}]" return self.formatted_text(class_name) @property def llmclient(self) -> Optional[LLMClient]: """The LLMClient of this config request, set by the ``llmclient_helper`` setter.""" return self._llmclient @property def llmclient_helper(self) -> Optional[LLMClientHelper]: """ The LLMClientHelper of this request, created on first access and cached. Built from the LLMClient when one is set, else from the LLMClient name of the view or the request. """ # "is not None", not truthiness, here and below: see the comment in dispatch_config(). if self._llmclient_helper is not None: return self._llmclient_helper if self.llmclient: # throw everything but the kitchen sink at the LLMClientHelper self._llmclient_helper = LLMClientHelper( request=self.smarter_request, session_key=self.session.session_key if self.session else None, name=self._llmclient.name if self._llmclient else self.llmclient_name, llmclient_id=self._llmclient.id if self._llmclient else None, # type: ignore[union-attr] account=self.account, user=self.user, user_profile=self.user_profile, ) else: self._llmclient_helper = LLMClientHelper( request=self.smarter_request, name=self.llmclient_name or self.smarter_request_llmclient_name, session_key=self.session.session_key if self.session else None, account=self.account, user=self.user, user_profile=self.user_profile, ) if self._llmclient_helper is not None: logger.debug( "property - instantiated LLMClientHelper with llmclient=%s, name=%s", self._llmclient_helper.llmclient, self._llmclient_helper.name, ) else: logger.warning("property - could not instantiate LLMClientHelper") return self._llmclient_helper @llmclient_helper.setter def llmclient_helper(self, value: Optional[LLMClientHelper]): """ Set the LLMClientHelper, and copy its LLMClient, account, user and user profile onto the view. :param value: The LLMClientHelper, or None. A helper without an LLMClient unsets ``llmclient``. """ self._llmclient_helper = value if self._llmclient_helper and self._llmclient_helper.llmclient: self._llmclient = self._llmclient_helper.llmclient self.account = self._llmclient_helper.account self.user = self._llmclient_helper.user self.user_profile = self._llmclient_helper.user_profile verbose_logger.debug("setter llmclient=%s", self.llmclient) else: self._llmclient = None verbose_logger.debug("setter llmclient is unset")
[docs] def clean_url(self, url: str) -> str: """Clean the url of any query strings and trailing '/config/' strings.""" retval = clean_url(url) if retval.endswith("/config/"): retval = retval[:-8] return retval
@property def full_config(self) -> bool: """ Whether the client receives the complete configuration. The complete configuration includes the LLMClient's every field, e.g. its owner's profile, the session's diagnostic histories, and the lists of plugins and extensions. It is returned when the LLMClient was found by its id or hashed id, i.e. by a workbench or platform api url, which checks that the user may read it, and to the cli. A deployed LLMClient's own host, which pages that embed Smarter Chat call, receives :func:`~smarter.apps.prompt.contract.builders.public_config`. :returns: True for the complete configuration. :rtype: bool """ return self.resolved_by_id or self.include_diagnostics @property def verbose(self) -> bool: """ Whether the configuration includes its diagnostic parts, which the workbench's Console displays. They are the session's tool calls, the complete ``meta_data`` (``LLMClientHelper.to_json()``), and the lists of the LLMClient's plugins and extensions. They cost database queries and serialization, and the tool calls grow with the session, so a client asks for them with ``?verbose=true`` (:data:`~smarter.apps.prompt.contract.const.VERBOSE_PARAMETER`) only when it displays them. Only a client that receives the complete configuration (:attr:`full_config`) may ask for them, and the cli always receives them. :returns: True for the diagnostic parts. :rtype: bool """ return self.include_diagnostics or (self.resolved_by_id and self.verbose_requested)
[docs] def prompt_url(self, url_llmclient: Optional[str]) -> Optional[str]: """ The url of the LLMClient's prompt api, on the host that served the configuration. A deployed LLMClient's host, or its custom domain, also serves its prompt api, at ``/prompt/``, so that a page that embeds Smarter Chat needs access to one host only. A workbench or platform api url keeps the platform's prompt api url. :param url_llmclient: The LLMClient's prompt api url on the platform, ``LLMClient.url_llmclient``. :type url_llmclient: Optional[str] :returns: The prompt api url to return to the client. :rtype: Optional[str] """ if self.resolved_by_id or not self.smarter_request: return url_llmclient host = self.smarter_request.get_host() return SmarterValidator.urlify(f"{host}/prompt/", environment=smarter_settings.environment)
[docs] def error_response(self, request: HttpRequest, error: PromptChatApiError) -> SmarterJournaledJsonErrorResponse: """ The configuration api's error response, the same shape for every error. See :func:`~smarter.apps.prompt.contract.builders.chat_error_response`. :param request: The request. :type request: django.http.HttpRequest :param error: The error. :type error: PromptChatApiError :returns: The error response, without a stack trace. :rtype: SmarterJournaledJsonErrorResponse """ return chat_error_response( request, error, thing=SmarterJournalThings(SmarterJournalThings.PROMPT_CONFIG), command=SmarterJournalCliCommands(SmarterJournalCliCommands.PROMPT_CONFIG), )
[docs] def chat_config(self) -> Optional[PromptChatApiConfig]: """ Assemble the configuration required by the ReactJS prompt UI component, as the contract's model. This method gathers all relevant context and configuration data for the prompt session and llmclient, and returns it as a :class:`~smarter.apps.prompt.contract.models.PromptChatApiConfig`, the Pydantic model of version 2 of the Smarter Chat api contract. :meth:`config` derives the response from it: the complete or public configuration, in version 2 or 1 of the contract. **Performance:** Since this endpoint is called on every browser load and refresh, the logic is optimized to minimize database queries and serialization overhead. The diagnostic parts, which the workbench's Console displays, are built only for a client that asks for them (see :attr:`verbose`), and only a limited number of plugins (see ``MAX_RETURNED_PLUGINS``) are returned. :returns: The configuration, or None if the session or the LLMClient helper is not set. Its fields: ``session_key``, ``sandbox_mode``, ``debug_mode``, ``llmclient`` (serialized by ``LLMClientConfigSerializer``, with ``url_llmclient`` from :meth:`prompt_url`), ``history`` (:meth:`chat_history`), ``meta_data`` (:meth:`meta_data`), ``plugins`` and ``extensions``. :rtype: Optional[PromptChatApiConfig] :raises pydantic.ValidationError: If the data breaks the contract. See Also -------- SmarterPromptSession : Helper class for managing prompt sessions. LLMClientConfigSerializer : Serializer for the llmclient's data. LLMClientHelper : Helper for llmclient-related operations. """ # add llmclient_request_history and plugin_selector_history to history # these have to be added here due to circular import issues. if self.session is None: logger.error( "session is None. Cannot retrieve llmclient request history.", ) return None if self.llmclient_helper is None: logger.error( "LLMClientHelper is None. Cannot retrieve llmclient request history.", ) return None llmclient_serializer = ( LLMClientConfigSerializer(self.llmclient, context={"request": self.smarter_request}) if self.llmclient else None ) # the plugins and extensions are counted. Their lists, which are constrained to a reasonable # number, since an llmclient may have hundreds of plugins, are diagnostic. See verbose. # counted once, and cached until the LLMClient's tools change. See get_cached_llmclient_tool_counts(). tool_counts = get_cached_llmclient_tool_counts(self.llmclient.id) # type: ignore[union-attr] llmclient_plugins_count = tool_counts.plugins llmclient_plugins: Union[QuerySet[LLMClientPlugin], list[LLMClientPlugin]] = ( LLMClientPlugin.objects.filter(llmclient=self.llmclient).select_related("plugin_meta") # django-stubs doesn't know taggit's TaggableManager, which is untyped, as a relation. .prefetch_related("plugin_meta__tags").order_by("-pk")[:MAX_RETURNED_PLUGINS] # type: ignore[misc] if self.verbose else [] ) llmclient_extensions_count = tool_counts.extensions llmclient_extensions: Union[QuerySet[LLMClientExtensions], list[LLMClientExtensions]] = ( LLMClientExtensions.objects.filter(llmclient=self.llmclient) .select_related("extension", "extension__installed_version") .defer("extension__installed_version__archive") .order_by("extension__slug")[:MAX_RETURNED_PLUGINS] if self.verbose else [] ) llmclient = self.to_snake_case(llmclient_serializer.data) if llmclient_serializer else {} llmclient["url_llmclient"] = self.prompt_url(llmclient.get("url_llmclient")) return PromptChatApiConfig( contract=CHAT_CONTRACT_V2, session_key=self.session.session_key, sandbox_mode=self.llmclient_helper.is_llmclient_sandbox_url, debug_mode=waffle.switch_is_active(SmarterWaffleSwitches.ENABLE_REACTAPP_DEBUG_MODE), llmclient=PromptChatApiLLMClient(**llmclient), history=self.chat_history(), meta_data=self.meta_data(), plugins=PromptChatApiPluginList( meta_data=PromptChatApiListMetaData( total_plugins=llmclient_plugins_count, plugins_returned=len(llmclient_plugins) ), plugins=[PromptChatApiLLMClientPlugin.from_model(plugin) for plugin in llmclient_plugins], ), extensions=PromptChatApiExtensionList( meta_data=PromptChatApiListMetaData( total_extensions=llmclient_extensions_count, extensions_returned=len(llmclient_extensions) ), extensions=[PromptChatApiLLMClientExtension.from_model(link) for link in llmclient_extensions], ), )
[docs] def chat_history(self) -> PromptChatApiHistory: """ The chat session's history, from its rows. - ``chat_history``, the session's messages, which restore the chat thread, always. - ``prompt_tool_call_history``, the session's tool calls, if :attr:`verbose`. - ``prompt_plugin_usage_history``, ``plugin_selector_history`` and ``llmclient_request_history`` for the cli only (:attr:`include_diagnostics`). Smarter Chat doesn't display them, and the requests, each of which holds the whole thread, grow with the square of the session's length. :returns: The history, empty without a session. :rtype: PromptChatApiHistory """ if self.session is None: return PromptChatApiHistory() # the messages are "prompt_history" in PromptHelper. The row is read once, and kept, so that # the journal can read the same thread from it. chat_helper = self.session.chat_helper session_key = self.session.session_key row = chat_helper.latest_prompt_history if chat_helper is not None else None self.chat_history_row = row messages = row.prompt_history if row is not None else [] history = PromptChatApiHistory( chat_history=messages or [], # type: ignore[arg-type] ) if self.verbose: history.prompt_tool_call_history = [ PromptChatApiPromptToolCall.from_model(row) for row in (chat_helper.prompt_tool_call if chat_helper is not None else []) ] if self.include_diagnostics: history.prompt_plugin_usage_history = [ PromptChatApiPromptPluginUsage.from_model(row) for row in (chat_helper.prompt_plugin_usage if chat_helper is not None else []) ] history.plugin_selector_history = [ PromptChatApiPluginSelection.from_model(row) for row in PluginSelectorHistory.objects.filter(session_key=session_key).order_by("-id") ] history.llmclient_request_history = [ PromptChatApiLLMClientRequest.from_model(row) for row in LLMClientRequests.objects.filter(session_key=session_key).order_by("-id") ] return history
[docs] def meta_data(self) -> PromptChatApiMetaData: """ The LLMClient's state. It is the complete ``LLMClientHelper.to_json()`` if :attr:`verbose`, and otherwise only the fields of :data:`~smarter.apps.prompt.contract.const.PUBLIC_META_DATA_FIELDS` that the helper has, which are what Smarter Chat reads. ``to_json()`` serializes the LLMClient a second time, with its tools, and the request. :returns: The meta data, empty without an LLMClient helper. :rtype: PromptChatApiMetaData """ helper = self.llmclient_helper if helper is None: return PromptChatApiMetaData() if self.verbose: return PromptChatApiMetaData(**self.to_snake_case(helper.to_json())) return PromptChatApiMetaData( ready=helper.ready, is_deployed=helper.is_deployed, is_custom_domain=helper.is_custom_domain, is_authentication_required=helper.is_authentication_required, )
[docs] def config(self) -> SmarterDictType: """ The configuration api's response body: :meth:`chat_config`, in the form that the client receives. - The complete configuration, or :meth:`PromptChatApiConfig.public() <smarter.apps.prompt.contract.models.PromptChatApiConfig.public>` unless :attr:`full_config`. - Version 2 of the contract to a client that asks for it, and to the cli (``legacy_keys=False``), or :meth:`PromptChatApiConfig.to_v1() <smarter.apps.prompt.contract.models.PromptChatApiConfig.to_v1>`. :returns: ``{"data": <the configuration>}``, or ``{}`` without a session or LLMClient helper. :rtype: SmarterDictType :raises pydantic.ValidationError: If the configuration breaks the contract. """ chat_config = self.chat_config() if chat_config is None: return {} if not self.full_config: chat_config = chat_config.public() if self.contract == CHAT_CONTRACT_V2 or not self.legacy_keys: data = chat_config.model_dump(mode="json", exclude_unset=True) else: # version 1, for older versions of the React app, which expect 'chatbot' instead of 'llmclient'. data = chat_config.to_v1().model_dump(mode="json", exclude_unset=True) retval = {"data": data} prompt_config_invoked.send(sender=self.__class__, instance=self, request=self.smarter_request, data=retval) return retval
[docs] def dispatch( self, request: HttpRequest, *args, **kwargs ) -> Union[JsonResponse, HttpResponse, SmarterJournaledJsonErrorResponse]: """ Handles incoming HTTP requests for the prompt configuration endpoint. This method is responsible for orchestrating the retrieval and assembly of all configuration data required by the ReactJS prompt UI component. It is invoked on every user-facing browser load and refresh, making performance a critical concern. **Key Details:** - **Django Template-Based:** This view uses Django's class-based view and template system, not Django REST Framework (DRF). The response is a JSON object, but the view logic is not DRF-based. - **CSRF Exempt:** The view is decorated with ``@csrf_exempt`` because it is strictly read-only and does not modify server-side data. This avoids unnecessary CSRF validation for GET and POST requests that only retrieve configuration data. - **ReactJS UI Integration:** The endpoint provides all configuration and context information needed by the ReactJS prompt component, including llmclient metadata, plugin information, session keys, and prompt history. - **Session-Based:** Sessions are managed by the :class:`SmarterPromptSession` helper, which uniquely defines a prompt session using a combination of the user's IP address and device-identifying information. This ensures each device/browser instance receives a unique session key, which is used to track prompt history and plugin usage. - **Performance:** Since this endpoint is called on every browser load and refresh, it is optimized to minimize database queries and serialization overhead. Only a limited number of plugins are returned (see ``MAX_RETURNED_PLUGINS``) to keep payloads small and response times fast. Parameters ---------- request : HttpRequest The incoming HTTP request object. llmclient_id : Optional[int], default=None The ID of the llmclient to retrieve configuration for, if specified. *args Additional positional arguments. **kwargs Additional keyword arguments. Returns ------- Union[JsonResponse, HttpResponse, SmarterJournaledJsonErrorResponse] A JSON response containing all configuration data required by the ReactJS prompt UI component, or an error response if the request is invalid or unauthorized. See Also -------- SmarterPromptSession : Helper class for managing prompt sessions. LLMClientConfigSerializer : Serializer for the llmclient's data. LLMClientHelper : Helper for llmclient-related operations. """ # the chat session key that the request sets, for its log records, is the request's only. The # log context middleware restores it too, but this view also runs without it, e.g. in tests. scope = session_key_context.set(session_key_context.get()) try: # before any of the work, e.g. creating a chat session's row, which a throttled request # must not do. super().dispatch() doesn't count the request again. throttled = self.throttle(request) if throttled is not None: return throttled return self.dispatch_config(request, *args, **kwargs) finally: session_key_context.reset(scope)
[docs] def dispatch_config( self, request: HttpRequest, *args, **kwargs ) -> Union[JsonResponse, HttpResponse, SmarterJournaledJsonErrorResponse]: """ Handle the request, for :meth:`dispatch`, which scopes the chat session key of its log records to it. :param request: The incoming HTTP request. :returns: The configuration, or an error response. """ self.thing = SmarterJournalThings(SmarterJournalThings.PROMPT_CONFIG) self.command = SmarterJournalCliCommands(SmarterJournalCliCommands.PROMPT_CONFIG) self.contract = requested_contract(request) self.resolved_by_id = False self.verbose_requested = str(request.GET.get(VERBOSE_PARAMETER, "")).strip().lower() in VERBOSE_VALUES hashed_id = kwargs.pop("hashed_id", None) if hashed_id: llmclient_id = LLMClient.id_from_hashed_id(hashed_id) else: llmclient_id = kwargs.pop("llmclient_id", None) if llmclient_id is not None: try: self._llmclient = LLMClient.get_cached_object(pk=llmclient_id) # a 404 rather than a 403, so that the ids of other accounts' LLMClients can't be discovered. # A url with an id is a workbench or platform api url, which requires a user who may read it. user = get_resolved_user(request.user) if not self.is_authenticated: raise LLMClient.DoesNotExist(f"LLMClient {llmclient_id} is not readable by an anonymous user") if not LLMClient.objects.with_read_permission_for(user).filter(pk=llmclient_id).exists(): # type: ignore[arg-type] raise LLMClient.DoesNotExist(f"LLMClient {llmclient_id} is not readable by {user}") self.resolved_by_id = True self.llmclient_name = self._llmclient.name verbose_logger.debug( "set llmclient=%s from llmclient_id=%s", self._llmclient, llmclient_id, ) except LLMClient.DoesNotExist: # the client's error, e.g. a chat still configured for a deleted LLMClient, not the platform's. # The journaled error response logs the 404 at WARNING. verbose_logger.info( "LLMClient with id=%s does not exist. Returning 404.", llmclient_id, ) return self.error_response(request, PromptChatApiErrorNotFound("LLMClient not found.")) else: self.llmclient_name = kwargs.get("name") try: self._llmclient = get_cached_llmclient_by_request(request=request) if not self._llmclient: verbose_logger.debug( "get_cached_llmclient_by_request() returned None. Attempting to instantiate LLMClientHelper with additional info", ) self.llmclient_helper = LLMClientHelper( request=self.smarter_request, session_key=self.session_key, llmclient_id=llmclient_id, name=self.llmclient_name, account=self.account, user=self.user, user_profile=self.user_profile, ) except LLMClient.DoesNotExist: return self.error_response(request, PromptChatApiErrorNotFound("LLMClient not found.")) # Initialize the prompt session for this request. session_key is generated # and managed by the /config/ endpoint for the llmclient # # examples: # - https://customer-support.3141-5926-5359.api.example.com/workbench/config/?session_key=123456 # - http://localhost:9357/api/v1/llm-clients/1556/prompt/config/?session_key=0733c7b3a33e7eb733c95f6d7fc88d671b6c957e6857a04d05b3f5905167116f # # The React app calls this endpoint at app initialization to get a # json dict that includes, among other pertinent info, this session_key # which uniquely identifies the device and the individual llmclient session # for the device. if not self.llmclient: # before the session, which requires an LLMClient. return self.error_response(request, PromptChatApiErrorNotFound("LLMClient not found.")) if self.llmclient.staff_only and not is_platform_staff(get_resolved_user(request.user)): # a 404, as for an LLMClient that doesn't exist, so that it can't be discovered. return self.error_response(request, PromptChatApiErrorNotFound("LLMClient not found.")) self.session = SmarterPromptSession(request, session_key=self.session_key, llmclient=self.llmclient) # a new chat's session key is created here, so the request's later log records carry it, # for the workbench's Console. dispatch() restores the log context after the request. if waffle.switch_is_active(SmarterWaffleSwitches.ENABLE_WEB_CONSOLE_SERVER_LOGS): session_key_context.set(valid_session_key(self.session.session_key)) # "is not None", not truthiness: LLMClientHelper is a SmarterRequestMixin, whose __bool__ is its # readiness, so a helper that isn't ready would skip this check. if ( self.llmclient_helper is not None and self.llmclient_helper.is_authentication_required and not is_authenticated_request(request) ): return self.error_response( request, PromptChatApiErrorForbidden( "Authentication failed. This LLMClient requires a Smarter api key, or a logged-in user." ), ) verbose_logger.debug( "llmclient=%s - llmclient_helper=%s", self.llmclient, self.llmclient_helper, ) if not (self.resolved_by_id or self.include_diagnostics) and not self.llmclient.deployed: # a host that isn't a workbench or platform api url serves deployed LLMClients only. return self.error_response(request, PromptChatApiErrorNotFound("LLMClient not found.")) # the session key is a credential for the chat, so only its masked form is logged. masked_session_key = mask_identifier(self.session.session_key) if self.session else "(Missing session)" verbose_logger.debug( "completed with llmclient=%s, session_key=%s", self.llmclient, masked_session_key, ) return super().dispatch(request, *args, **kwargs) # type: ignore[return-value]
def __str__(self) -> str: return str(self.llmclient) if self.llmclient else "PromptConfigView" # pylint: disable=unused-argument
[docs] def post( self, request: HttpRequest, *args, **kwargs ) -> Union[SmarterJournaledJsonResponse, SmarterJournaledJsonErrorResponse]: """Get the llmclient configuration.""" logger.debug("called") return self.config_response(request)
[docs] def config_response( self, request: HttpRequest ) -> Union[SmarterJournaledJsonResponse, SmarterJournaledJsonErrorResponse]: """ The configuration, as the response to the client. :param request: The request. :type request: django.http.HttpRequest :returns: The configuration, or an error response if it breaks the contract. :rtype: Union[SmarterJournaledJsonResponse, SmarterJournaledJsonErrorResponse] """ try: data = self.config() except ValidationError as e: logger.error("the configuration breaks the contract: %s", e) return self.error_response( request, PromptChatApiErrorInternal("The LLMClient's configuration could not be built.") ) # the thread is in the journal's database already: the journal reads it from its row, rather # than receive it with every configuration it journals. journal_sources = [] if self.chat_history_row is not None: journal_sources.append(chat_history_source(self.chat_history_row)) return SmarterJournaledJsonResponse( request=request, data=data, thing=self.thing, command=self.command, journal_sources=journal_sources, )
# pylint: disable=unused-argument
[docs] def get( self, request: HttpRequest, *args, **kwargs ) -> Union[SmarterJournaledJsonResponse, SmarterJournaledJsonErrorResponse, HttpResponseNotAllowed]: """Get the llmclient configuration.""" if not waffle.switch_is_active(SmarterWaffleSwitches.ALLOW_API_GET): # the client's error, not the platform's. logger.warning( "GET %s refused: use POST, or turn on the %s switch.", request.path, SmarterWaffleSwitches.ALLOW_API_GET ) return HttpResponseNotAllowed(permitted_methods=[SmarterHttpMethods.POST]) logger.warning("GET %s allowed by the %s switch: use POST.", request.path, SmarterWaffleSwitches.ALLOW_API_GET) return self.config_response(request)