# pylint: disable=C0115
"""PromptHelper for the prompt app."""
from functools import cached_property
from typing import Optional, Union
from django.db import models
from django.db.utils import IntegrityError
from django.http import HttpRequest
from rest_framework import serializers
from smarter.apps.llmclient.models import LLMClient, get_cached_llmclient_by_request
from smarter.common.exceptions import SmarterConfigurationError, SmarterValueError
from smarter.common.utils import mask_identifier
from smarter.lib import logging
from smarter.lib.django.request import SmarterRequestMixin
from smarter.lib.django.waffle import SmarterWaffleSwitches
from smarter.lib.typing import SmarterDictType
from .prompt import Prompt, get_cached_prompt_by_session_key
from .prompt_history import PromptHistory
from .prompt_plugin_usage import PromptPluginUsage
from .prompt_tool_call import PromptToolCall
logger = logging.getSmarterLogger(__name__, any_switches=[SmarterWaffleSwitches.PROMPT_LOGGING])
# --------------------------------------------------------------------------------
# Mini Serializers - only used by PromptHelper.
# --------------------------------------------------------------------------------
[docs]
class PromptSerializer(serializers.ModelSerializer):
"""Serializer for the Prompt model, with all of its fields."""
class Meta:
model = Prompt
fields = "__all__"
[docs]
class PromptPluginUsageSerializer(serializers.ModelSerializer):
"""Serializer for the PromptPluginUsage model."""
prompt = PromptSerializer(read_only=True)
class Meta:
model = PromptPluginUsage
fields = "__all__"
[docs]
class PromptHelper(SmarterRequestMixin):
"""
Helper class for working with :class:`Prompt` objects.
This class provides methods for creating and retrieving :class:`Prompt` objects,
as well as managing the cache for prompt sessions. It is designed to simplify
the process of interacting with prompt-related data and to ensure consistent
handling of prompt sessions, llmclients, and associated metadata.
**Features**
- Abstracts the logic for creating and retrieving prompt sessions.
- Manages caching of prompt objects to improve performance and reduce database queries.
- Provides access to related prompt history, tool calls, and plugin usage.
- Integrates with Django's request and session handling.
- Ensures that prompt sessions are always associated with a valid :class:`LLMClient` and :class:`Account`.
**Usage**
Typically, this class is instantiated with a Django :class:`HttpRequest` object and a session key.
Optionally, a :class:`LLMClient` instance can be provided to associate the prompt session with a specific llmclient.
Example
-------
.. code-block:: python
helper = PromptHelper(request, session_key)
if helper.ready:
prompt = helper.prompt
llmclient = helper.llmclient
history = helper.history
:param request: The Django HttpRequest object for the current session.
:type request: django.http.HttpRequest
:param session_key: The session key identifying the prompt session.
:type session_key: Optional[str]
:param llmclient: An optional LLMClient instance to associate with the prompt session.
:type llmclient: Optional[LLMClient]
:param args: Additional positional arguments.
:param kwargs: Additional keyword arguments.
:raises SmarterValueError: If neither a session key nor a LLMClient instance is provided.
:raises SmarterConfigurationError: If there is an error creating a new Prompt object.
.. note::
This class is intended for internal use within the Smarter platform and
should not be used directly in user-facing code without proper validation.
.. todo::
- Remove the session_key parameter and rely solely on the LLMClient instance for prompt session management.
.. seealso::
- :class:`smarter.apps.llmclient.models.LLMClient`
- :class:`smarter.apps.account.models.Account`
- :class:`smarter.apps.prompt.models.Prompt`
- :class:`smarter.lib.django.request.SmarterRequestMixin`
"""
_chat: Optional[Prompt] = None
_llmclient: Optional[LLMClient] = None
_prompt_tool_call: Optional[Union[models.QuerySet, list]] = None
_prompt_plugin_usage: Optional[Union[models.QuerySet, list]] = None
_history: Optional[SmarterDictType] = None
[docs]
def __init__(
self,
request: Optional[HttpRequest],
session_key: Optional[str],
*args,
llmclient: Optional[LLMClient] = None,
**kwargs,
) -> None:
"""
Initialize the PromptHelper instance.
:param request: The Django HttpRequest object for the current session. It is required: None raises.
:type request: Optional[django.http.HttpRequest]
:param session_key: The session key identifying the prompt session.
:type session_key: Optional[str]
:param llmclient: An optional LLMClient instance to associate with the prompt session.
:type llmclient: Optional[LLMClient]
:param args: Additional positional arguments.
:param kwargs: Additional keyword arguments.
:raises SmarterValueError: If there is no request, or neither a session key nor a LLMClient instance is provided.
:raises SmarterConfigurationError: If there is an error creating a new Prompt object.
"""
if not request:
raise SmarterValueError(f"{self.formatted_class_name} request object is required.")
super().__init__(request, session_key=session_key, **kwargs)
self._chat = None
self._llmclient = llmclient
self._prompt_tool_call = None
self._prompt_plugin_usage = None
self._history = None
if not session_key and not llmclient:
raise SmarterValueError(
f"{self.formatted_class_name} either a session_key or a LLMClient instance is required"
)
if llmclient and llmclient.user_profile:
self._user_profile = llmclient.user_profile
self._account = llmclient.user_profile.account
self._user = llmclient.user_profile.user
# rerun the ready status check to ensure that the account is authorized and ready.
self._am_ready = False
# pylint: disable=W0104
self.am_ready
if session_key:
self._session_key = session_key
if self.session_key:
self._chat = self.get_cached_chat()
def __str__(self) -> str:
return self.session_key
@property
def ready(self) -> bool:
"""
Check if the PromptHelper is ready to use.
This property returns ``True`` if the prompt instance is available and all required
attributes are set, otherwise returns ``False``. It is useful for determining
whether the PromptHelper is fully initialized and ready for prompt operations.
:returns: ``True`` if the PromptHelper is ready to use, otherwise ``False``.
:rtype: bool
"""
return bool(super().ready) and bool(self._session_key) and bool(self._chat) and bool(self._llmclient)
[docs]
def to_json(self) -> SmarterDictType:
"""
Convert the PromptHelper instance to a JSON serializable dictionary.
This method returns a dictionary representation of the PromptHelper instance,
including key metadata and related objects such as the prompt, llmclient, prompt history,
and a unique client string.
:returns: A dictionary containing the serialized state of the PromptHelper.
:rtype: SmarterDictType
"""
return self.sorted_dict(
{
**super().to_json(),
"ready": self.ready,
"session_key": self.session_key,
"prompt": self.prompt.id if self.prompt else None, # type: ignore[return]
"llmclient": self.llmclient.id if self.llmclient else None, # type: ignore[return]
"history": self.history,
"unique_client_string": self.unique_client_string,
}
)
@property
def prompt(self):
"""
Get the prompt instance for the current request.
:returns: The Prompt instance associated with the current session.
:rtype: Prompt
"""
return self._chat
@property
def llmclient(self):
"""
Returns a lazy instance of the LLMClient.
Examples
--------
- ``https://hr.3141-5926-5359.alpha.api.example.com/llm-client/``
returns ``LLMClient(name='hr', account=Account(...))``
:returns: The LLMClient instance.
:rtype: LLMClient
"""
if self._llmclient:
return self._llmclient
request = self.smarter_request
if request is None:
return None
self._llmclient = get_cached_llmclient_by_request(request=request)
return self._llmclient
@property
def latest_prompt_history(self) -> Optional[PromptHistory]:
"""
Get the newest PromptHistory row of the current prompt session: its latest prompt.
:returns: The newest PromptHistory, or None if the session has sent no prompt.
:rtype: Optional[PromptHistory]
"""
rec = PromptHistory.objects.filter(prompt=self.prompt).order_by("-created_at").first()
return rec
@property
def prompt_history(self) -> Union[models.QuerySet, list]:
"""
Get the most recent prompt history for the current prompt session.
:returns: The most recent PromptHistory instance's prompt_history field, or an empty list if none found.
:rtype: Union[models.QuerySet, list]
"""
rec = self.latest_prompt_history
return rec.prompt_history if rec else []
@property
def prompt_tool_call(self) -> Union[models.QuerySet, list]:
"""
Get the most recent prompt tool call history for the current prompt session.
:returns: A queryset of PromptToolCall instances for the current prompt session, ordered by creation date.
:rtype: Union[models.QuerySet, list]
"""
# "is not None": an empty result is cached too, rather than queried again on every access.
if self._prompt_tool_call is not None:
return self._prompt_tool_call
self._prompt_tool_call = PromptToolCall.objects.filter(prompt=self.prompt).order_by("-created_at") or []
return self._prompt_tool_call
@property
def prompt_plugin_usage(self) -> Union[models.QuerySet, list]:
"""
Get the most recent prompt plugin usage history for the current prompt session.
:returns: A queryset of PromptPluginUsage instances for the current prompt session, ordered by creation date.
:rtype: Union[models.QuerySet, list]
"""
if self._prompt_plugin_usage is not None:
return self._prompt_plugin_usage
self._prompt_plugin_usage = PromptPluginUsage.objects.filter(prompt=self.prompt).order_by("-created_at") or []
return self._prompt_plugin_usage
@property
def history(self) -> SmarterDictType:
"""
Serialize the most recent logged history output for the prompt session.
:returns: A dictionary containing serialized prompt, prompt history, tool calls, and plugin usage.
:rtype: dict
"""
if self._history is not None:
return self._history
chat_serializer = PromptSerializer(self.prompt)
prompt_tool_call_serializer = PromptToolCallSerializer(self.prompt_tool_call, many=True)
prompt_plugin_usage_serializer = PromptPluginUsageSerializer(self.prompt_plugin_usage, many=True)
self._history = {
"prompt": chat_serializer.data,
"prompt_history": self.prompt_history,
"prompt_tool_call_history": prompt_tool_call_serializer.data,
"prompt_plugin_usage_history": prompt_plugin_usage_serializer.data,
# these two will be added upstream.
"llmclient_request_history": None, # LLMClientRequests
}
return self._history
[docs]
def get_cached_chat(self) -> Optional[Prompt]:
"""
Get the prompt instance for the current request.
This method retrieves the Prompt instance associated with the current session key
from the cache. If the Prompt instance is not found in the cache, it attempts to
retrieve it from the database. If it still cannot be found, a new Prompt instance
is created using the provided LLMClient and request metadata.
:returns: The Prompt instance associated with the current session, or ``None`` if not found.
:rtype: Optional[Prompt]
"""
if not self.smarter_request:
logger.error("request object is required for PromptHelper.")
return None
prompt: Optional[Prompt] = None
if self.session_key:
try:
prompt = get_cached_prompt_by_session_key(self.session_key)
except Prompt.DoesNotExist:
pass
if prompt and self.llmclient and prompt.llmclient_id != self.llmclient.id: # type: ignore[attr-defined]
# A session belongs to one llmclient. A key of another llmclient's session, e.g. a
# session_key cookie that the browser sends to every host of the platform's domain,
# starts a new session rather than continuing the other llmclient's chat.
# The key is masked: it is a credential for the other llmclient's chat.
masked_session_key = mask_identifier(self.session_key)
logger.warning(
"session_key %s belongs to llmclient %s, not %s. Starting a new session.",
masked_session_key,
prompt.llmclient_id, # type: ignore[attr-defined]
self.llmclient.id, # type: ignore[attr-defined]
)
prompt = None
self._session_key = self.generate_session_key()
if not prompt:
if not self.llmclient:
raise SmarterValueError(
f"{self.formatted_class_name} LLMClient instance is required for creating a Prompt object."
)
# both columns are NOT NULL, so the database would refuse the row with an IntegrityError.
if self.user_profile is None:
raise SmarterConfigurationError(
f"{self.formatted_class_name} user_profile is required for creating a Prompt object."
)
if self.ip_address is None:
raise SmarterConfigurationError(
f"{self.formatted_class_name} ip_address is required for creating a Prompt object."
)
try:
# modify the unit test server URL
# to a more Django friendly URL.
django_friendly_url = self.url or ""
django_friendly_url = django_friendly_url.replace("http://testserver/", "http://testserver.local/")
# The User-Agent header has no length limit, but its column does: a longer value
# would make the database raise DataError, and the request fail with a 500.
# pylint: disable=W0212
user_agent_field = Prompt._meta.get_field("user_agent")
user_agent_max_length = None
if isinstance(user_agent_field, models.CharField):
user_agent_max_length = user_agent_field.max_length
user_agent = self.user_agent
if not user_agent:
user_agent = "user_agent"
user_agent = user_agent[:user_agent_max_length]
# annotated, so that type checkers without the Django plugin (Pylance) know it's not None.
new_prompt: Prompt = Prompt.objects.create(
session_key=self.session_key,
user_profile=self.user_profile,
llmclient=self.llmclient,
ip_address=self.ip_address,
user_agent=user_agent,
url=django_friendly_url,
)
prompt = new_prompt
except IntegrityError as e:
raise SmarterConfigurationError(f"{self.formatted_class_name} - IntegrityError: {str(e)}") from e
if not prompt.llmclient:
raise ValueError(f"{self.formatted_class_name} LLMClient instance is required for Prompt object.")
return prompt