"""This file contains the mixins for the provider model."""
from typing import Optional
from django.db.models.query import QuerySet
from smarter.apps.account.mixins import AccountMixin
from smarter.apps.account.models import UserProfile
from smarter.apps.account.tasks import create_charge
from smarter.apps.prompt.const import SMARTER_CHAT_SESSION_KEY_NAME
from smarter.apps.prompt.models import (
Prompt,
PromptHistory,
PromptPluginUsage,
PromptToolCall,
)
from smarter.apps.prompt.tasks import (
create_prompt_plugin_usage,
create_prompt_tool_call_history,
)
from smarter.apps.provider.models import (
Provider,
get_cached_active_provider_for_user,
)
from smarter.common.exceptions import SmarterValueError
from smarter.lib import logging
from smarter.lib.django import waffle
from smarter.lib.django.waffle import SmarterWaffleSwitches
from smarter.lib.typing import SmarterDictType
# pylint: disable=W0613
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]
class ChatDbMixin(AccountMixin):
"""
Mixin for database-related methods for provider models.
This mixin provides database access and persistence logic for prompt provider
models, including management of prompt sessions, prompt history, plugin/tool
usage, and charge records. It is intended to be used as a base class for
provider implementations that require integration with the Smarter database
models. This provides layers of abstraction for asynchronously creating
history and charge records resulting from provider requests.
**Key Features:**
- Manages retrieval and caching of prompt, prompt history, tool calls, and plugin usage.
- Provides properties for accessing and updating prompt-related data.
- Supports insertion of new tool call, plugin usage, and charge records via asynchronous tasks.
**Usage:**
Inherit from this mixin in a provider class to enable database-backed prompt session and usage tracking.
**Example:**
.. code-block:: python
class MyProvider(ChatDbMixin):
def custom_method(self):
# Access prompt history
history = self.prompt_history
# Insert a charge
self.db_insert_charge(...)
"""
__slots__ = (
"_chat",
"_chat_tool_call",
"_chat_plugin_usage",
"_chat_history",
"_message_history",
"_provider_name",
"_provider",
"_prompting_user_profile",
"_ready",
)
[docs]
def __init__(self, *args, **kwargs):
"""
Initialize the ChatDbMixin.
This constructor sets up the database-related attributes for the
provider model, including prompt session, tool call, plugin usage,
charge, and prompt history references. It attempts to retrieve the
current prompt session using a session key if provided, or falls
back to a prompt object in kwargs.
Parameters
----------
*args : tuple
Positional arguments passed to the superclass constructor.
**kwargs : dict
Keyword arguments passed to the superclass constructor. Recognized keys:
- SMARTER_CHAT_SESSION_KEY_NAME (str): Default is 'session_key'. Session key for the prompt session.
- prompt (Prompt): Prompt instance to use if session key is not provided.
- prompting_user_profile (UserProfile): The profile of the person who prompts from the
web console's workbench, who is charged for it. See :attr:`billed_user_profile`.
Example
-------
.. code-block:: python
mixin = ChatDbMixin(prompt=my_chat)
# or
mixin = ChatDbMixin(session_key="abc123")
"""
self._chat: Optional[Prompt] = None
self._chat_tool_call: QuerySet[PromptToolCall] = None # type: ignore
self._chat_plugin_usage: Optional[QuerySet[PromptPluginUsage]] = None
self._chat_history: Optional[QuerySet[PromptHistory]] = None
self._message_history: Optional[list[SmarterDictType]] = None
self._provider_name: Optional[str] = kwargs.get("provider_name", None)
self._provider: Optional[Provider] = kwargs.get("provider", None)
self._prompting_user_profile: Optional[UserProfile] = kwargs.get("prompting_user_profile", None)
self._ready: bool = False
super().__init__(*args, **kwargs)
session_key = kwargs.get(SMARTER_CHAT_SESSION_KEY_NAME, None)
if session_key:
self._chat = Prompt.get_cached_object(session_key=session_key) # type: ignore
else:
# normal: a provider is created before its prompt, which it is given per request.
self._chat = kwargs.get("prompt", None)
@property
def ready(self) -> bool:
"""
Indicates whether the mixin and its dependencies are ready for use.
This property checks if both the superclass and the prompt instance are ready.
It is useful for determining if the provider is fully initialized and can
interact with the database and prompt session.
Returns
-------
bool
True if both the superclass and prompt are ready, False otherwise.
Example
-------
.. code-block:: python
if provider.ready:
# Safe to proceed with database operations
...
"""
if self._ready:
return True
super_ready = bool(super().ready)
if not super_ready:
logger.warning("is not ready because the superclass is not ready.")
return False
self._ready = isinstance(self.prompt, Prompt)
if not self._ready:
logger.warning("is not ready because prompt is not set.")
return self._ready
@property
def prompt(self) -> Optional[Prompt]:
"""
Get the current prompt session instance.
This property returns the active `Prompt` object associated with the provider,
or `None` if no prompt session is set. It is used to access prompt-specific
data and operations throughout the provider's logic.
Returns
-------
Prompt or None
The current prompt session instance, or None if not set.
Example
-------
.. code-block:: python
prompt = provider.prompt
if prompt is not None:
print(prompt.session_key)
"""
return self._chat
@prompt.setter
def prompt(self, value: Optional[Prompt]):
"""
Set the current prompt session instance.
This setter updates the active `Prompt` object for the provider. It also
resetsall cached database-related attributes to ensure consistency
with the new prompt session. If the provided value is not a `Prompt`
instance or `None`, a `SmarterValueError` is raised.
Parameters
----------
value : Prompt or None
The new prompt session instance to associate with the provider, or None to unset.
Raises
------
SmarterValueError
If the value is not a `Prompt` instance or None.
Side Effects
------------
Resets lazy attributes: `_chat_tool_call`, `_chat_plugin_usage`,
`_chat_history`, and `_message_history`.
Example
-------
.. code-block:: python
provider.prompt = new_chat
# All cached database attributes are reset
"""
if not isinstance(value, Prompt) and value is not None:
raise SmarterValueError("Prompt must be an instance of Prompt or None")
self._chat = value
self._chat_tool_call = None # type: ignore
self._chat_plugin_usage = None # type: ignore
self._chat_history = None
self._message_history = None
@property
def prompting_user_profile(self) -> Optional[UserProfile]:
"""
The profile of the person who prompts from the web console's workbench.
It is not :attr:`user_profile`, the LLMClient's owner, whose provider, plugins and secrets
the prompt runs with. It is None for every other prompt, e.g. to a deployed LLMClient,
from the cli or an SDK, or from an Orchestrator's run.
:returns: The workbench user's profile, or None.
:rtype: Optional[UserProfile]
"""
return self._prompting_user_profile
@prompting_user_profile.setter
def prompting_user_profile(self, value: Optional[UserProfile]) -> None:
"""
Set the profile of the person who sent the prompt.
:param value: The workbench user's profile, or None for any other prompt.
:type value: Optional[UserProfile]
:raises SmarterValueError: If the value is neither a UserProfile nor None.
"""
if value is not None and not isinstance(value, UserProfile):
raise SmarterValueError(f"prompting_user_profile must be a UserProfile or None, got {type(value)}")
self._prompting_user_profile = value
@property
def billed_user_profile(self) -> Optional[UserProfile]:
"""
The profile that a prompt's completion is charged to, and whose budgets it must respect.
The LLMClient's owner, :attr:`user_profile`, pays for its prompts once it is deployed,
except in the web console's workbench, where the person who is prompting pays:
:attr:`prompting_user_profile`.
:returns: The profile to charge.
:rtype: Optional[UserProfile]
"""
if self._prompting_user_profile is not None:
return self._prompting_user_profile
return self.user_profile
@property
def prompt_history(self) -> Optional[QuerySet[PromptHistory]]:
"""
Get the prompt history queryset for the current prompt session.
This property returns a Django QuerySet of `PromptHistory` objects associated
with the current prompt session. If no prompt is set, or if there is no history,
returns None. The queryset is cached for efficiency.
Returns
-------
QuerySet[PromptHistory] or None
QuerySet of prompt history records for the current prompt, or None if unavailable.
Example
-------
.. code-block:: python
history_qs = provider.prompt_history
if history_qs is not None:
for record in history_qs:
print(record.created_at, record.messages)
"""
if self._chat_history is None and self.prompt is not None:
self._chat_history = PromptHistory.objects.filter(prompt=self.prompt)
return self._chat_history
@property
def db_message_history(self) -> Optional[list[SmarterDictType]]:
"""
Get the most recently persisted messages in the prompt history.
This property returns the latest list of messages stored in the prompt history
for the current prompt session. If no messages are available, returns None.
The result is cached for efficiency.
Returns
-------
list[dict] or None
The most recent list of message dictionaries from prompt history, or None if unavailable.
Example
-------
.. code-block:: python
messages = provider.db_message_history
if messages:
for msg in messages:
print(msg['role'], msg['content'])
"""
if isinstance(self._message_history, list):
return self._message_history
prompt_history = self.prompt_history
# one query for the newest record. Testing the queryset's truth would fetch every record
# and its messages, and exists() and latest() would each be another query.
newest_record = prompt_history.order_by("-created_at").first() if prompt_history is not None else None
if newest_record is not None and newest_record.messages:
self._message_history = newest_record.messages
if not isinstance(self._message_history, list):
logger.warning(
"expected messages to be a list but got %s.",
type(self._message_history).__name__,
)
return self._message_history
@property
def db_chat_tool_call(self) -> QuerySet[PromptToolCall]:
"""
Get the queryset of prompt tool call records for the current prompt session.
This property returns a Django QuerySet of `PromptToolCall` objects associated with
the current prompt session. If no prompt is set, returns an empty queryset. The queryset
is cached for efficiency.
Returns
-------
QuerySet[PromptToolCall]
QuerySet of prompt tool call records for the current prompt session, or an empty queryset if unavailable.
Example
-------
.. code-block:: python
tool_calls = provider.db_chat_tool_call
for tool_call in tool_calls:
print(tool_call.function_name, tool_call.created_at)
"""
if self._chat_tool_call is None and self.prompt is not None:
self._chat_tool_call = PromptToolCall.objects.filter(prompt=self.prompt)
if self._chat_tool_call is not None:
return self._chat_tool_call
return PromptToolCall.objects.none()
@property
def db_chat_plugin_usage(self) -> QuerySet[PromptPluginUsage]:
"""
Get the prompt plugin usage instance for the current prompt session.
This property returns the `PromptPluginUsage` object associated with the
current prompt session, if available. The result is cached for efficiency.
If no prompt is set or no plugin usage exists, returns None.
Returns
-------
PromptPluginUsage or None
The prompt plugin usage instance for the current prompt, or None if unavailable.
Example
-------
.. code-block:: python
plugin_usage = provider.db_chat_plugin_usage
if plugin_usage is not None:
print(plugin_usage.plugin, plugin_usage.input_text)
"""
if self._chat_plugin_usage is None and self.prompt is not None:
self._chat_plugin_usage = PromptPluginUsage.objects.filter(prompt=self.prompt)
if self._chat_plugin_usage is not None:
return self._chat_plugin_usage
return PromptPluginUsage.objects.none()
@property
def provider_name(self) -> Optional[str]:
"""
Get the provider name associated with this provider model.
This property returns the name of the provider that this model is configured to use.
It is typically used to determine which provider's handler to invoke for prompt completions.
Returns
-------
str or None
The name of the provider, or None if not set.
Example
-------
.. code-block:: python
print(provider.provider_name)
"""
if self.provider:
return self.provider.name
return None
@property
def provider(self) -> Optional[Provider]:
"""
Get the Provider instance associated with this provider model.
This property returns the `Provider` object that represents the provider
configuration for this model. It is typically used to access provider-specific
settings and information.
Returns
-------
Provider or None
The Provider instance associated with this model, or None if not set.
Example
-------
.. code-block:: python
provider_instance = provider.provider
if provider_instance:
print(provider_instance.name)
"""
if self._provider is None and self._provider_name is not None:
self._provider = get_cached_active_provider_for_user(self._provider_name, self.user_profile.user.username) # type: ignore[union-attr]
if not self._provider:
logger.warning(
"property could not find an active provider with name '%s' for user %s.",
self._provider_name,
self.user_profile.user.username if self.user_profile and self.user_profile.user else "Unknown",
)
return self._provider
[docs]
def db_refresh(self):
"""
Refresh the provider instance and its cached database attributes.
This method refreshes the prompt instance from the database and resets its cached
querysets. Use this method to ensure the provider has the latest data
after external changes to the prompt or related records.
Example
-------
.. code-block:: python
provider.db_refresh()
# Now provider.db_chat_tool_call and related properties are up to date
"""
if self.prompt:
# resets all lazy attributes to force reload on next access
self.prompt = self.prompt
[docs]
def db_insert_chat_plugin_usage(self, *args, **kwargs):
"""
Insert a prompt plugin usage record for the specified prompt session.
This method creates a new `PromptPluginUsage` record associated with the given prompt session.
The insertion is performed asynchronously using a background task. If no prompt is provided,
the method logs a warning and returns without action.
Parameters
----------
prompt : Prompt
The prompt instance for which to record plugin usage. Required.
plugin : Plugin, optional
The plugin instance used in the prompt (default: None).
input_text : str, optional
The input text sent to the plugin (default: None).
Example
-------
.. code-block:: python
provider.db_insert_chat_plugin_usage(
prompt=my_chat,
plugin=my_plugin,
input_text="search for weather"
)
"""
prompt = kwargs.get("prompt", None)
if not prompt:
logger.warning(
"Prompt is required to create a prompt plugin usage record.",
)
return
prompt_id = prompt.id # type: ignore
plugin = kwargs.get("plugin", None)
plugin_id = plugin.id if plugin else None
input_text = kwargs.get("input_text", None)
create_prompt_plugin_usage.delay(prompt_id=prompt_id, plugin_id=plugin_id, input_text=input_text)
[docs]
def db_insert_charge(
self,
resource_locators: list[str],
charge_type: str,
completion_tokens: int,
prompt_tokens: int,
total_tokens: int,
charge_user: bool = True,
):
"""
Insert a new charge record for the current account and prompt session.
This method asynchronously creates a new `Charge` record associated with the current account, user, and prompt session. It is typically used to persist billing or usage information for a model completion or related operation.
Parameters
----------
resource_locators : list[str]
A list of resource locators associated with the charge (e.g., provider, user profile).
charge_type : str
The type of charge (e.g., "completion", "plugin").
completion_tokens : int
The number of completion tokens used.
prompt_tokens : int
The number of prompt tokens used.
total_tokens : int
The total number of tokens used.
charge_user : bool
Whether to charge the user and their account too, which every model call's completion charge
does. The user is :attr:`billed_user_profile`: the LLMClient's owner, or in the web
console's workbench, the person who is prompting. A plugin's or a tool's charge, whose tokens are the completion's, is
charged to the tool's own resources only, so that a model call's tokens are counted once for
the user and the account.
Raises
------
SmarterValueError
If the account or prompt is not set.
Example
-------
.. code-block:: python
provider.db_insert_charge(
resource_locators=["provider-xyz", "user-profile-abc"],
charge_type="completion",
completion_tokens=42,
prompt_tokens=58,
total_tokens=100,
)
"""
billed_user_profile = self.billed_user_profile
if not isinstance(billed_user_profile, UserProfile):
raise SmarterValueError("Account is required to create a charge record.")
if not resource_locators:
raise SmarterValueError("Resource locators are required to create a charge record.")
if not self.prompt:
raise SmarterValueError("Prompt is required to create a charge record.")
if charge_user:
resource_locators.append(billed_user_profile.record_locator)
resource_locators.append(billed_user_profile.account.record_locator)
# the same for every charge, so read once rather than per resource locator.
provider_name = getattr(self, "provider_name", None)
model = getattr(self, "model", None)
for resource_locator in resource_locators:
create_charge.delay(
resource_locator=resource_locator,
charge_type=charge_type,
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
total_tokens=total_tokens,
provider=provider_name,
model=model,
)
__all__ = ["ChatDbMixin"]