Source code for smarter.apps.provider.services.text_completion.lib.chat_provider_base

"""Base class for prompt providers."""

from functools import cached_property
from typing import TYPE_CHECKING, Dict, List, Optional, Union

from openai.types.chat.chat_completion import ChatCompletion
from openai.types.chat.chat_completion_message_tool_call import (
    ChatCompletionMessageToolCallUnion,
)
from pydantic import SecretStr

from smarter.apps.account.models import charge_authorization
from smarter.apps.llmtool.plugin.base import PluginBase
from smarter.apps.prompt.models import Prompt
from smarter.apps.prompt.signals import (
    llm_provider_initialized,
)
from smarter.apps.provider.const import BUILTIN_PROVIDER_API_KEY_SECRET_NAMES
from smarter.apps.provider.models import Provider
from smarter.apps.provider.services.text_completion.const import OpenAIMessageKeys
from smarter.apps.provider.services.text_completion.utils import (
    get_request_body,
    parse_request,
)
from smarter.common.conf import smarter_settings
from smarter.common.conf.env import is_missing_value
from smarter.common.exceptions import (
    SmarterConfigurationError,
    SmarterValueError,
)
from smarter.common.helpers.console_helpers import SmarterFormattedText
from smarter.common.helpers.llm import get_date_time_string
from smarter.lib import json, logging
from smarter.lib.django import waffle
from smarter.lib.django.waffle import SmarterWaffleSwitches
from smarter.lib.typing import SmarterDictType

from .internal_keys import _InternalKeys
from .mixins import ChatDbMixin

if TYPE_CHECKING:
    from smarter.apps.llmclient.models import LLMClient


# 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)

EXAMPLE_PROMPTS_HEADING = "Some example prompts to get you started:"
"""The heading of the example prompts message, as Smarter Chat displays it (in English)."""


def example_prompts_message(prompts: Optional[list[str]]) -> str:
    """
    Return an LLMClient's example prompts as the assistant message that starts a session.

    It is the message that Smarter Chat displays after the welcome message.

    :param prompts: The LLMClient's example prompts.
    :type prompts: Optional[list[str]]
    :returns: The message, or an empty string if there are no example prompts.
    :rtype: str
    """
    if not prompts:
        return ""
    return EXAMPLE_PROMPTS_HEADING + "\n\n" + "".join(f"- {prompt}\n" for prompt in prompts)


def llmclient_welcome_message(llmclient: Optional["LLMClient"]) -> str:
    """
    Return an LLMClient's welcome message.

    :param llmclient: The LLMClient, or None.
    :type llmclient: Optional[LLMClient]
    :returns: The welcome message, or an empty string if it has none.
    :rtype: str
    """
    welcome_message = getattr(llmclient, "app_welcome_message", None) if llmclient else None
    if not isinstance(welcome_message, str):
        return ""
    return welcome_message


def llmclient_example_prompts(llmclient: Optional["LLMClient"]) -> list[str]:
    """
    Return an LLMClient's example prompts.

    :param llmclient: The LLMClient, or None.
    :type llmclient: Optional[LLMClient]
    :returns: The example prompts that are strings, or an empty list.
    :rtype: list[str]
    """
    example_prompts = getattr(llmclient, "app_example_prompts", None) if llmclient else None
    if not isinstance(example_prompts, list):
        return []
    return [prompt for prompt in example_prompts if isinstance(prompt, str)]


def introduction_messages(llmclient: Optional["LLMClient"]) -> list[SmarterDictType]:
    """
    Return the messages that start a new session's thread, before its first user message.

    They are the LLMClient's system role, which starts with the date and time (the date and time
    only, without an LLMClient or a system role), then its welcome message and its example prompts,
    as assistant messages, which is the introduction that Smarter Chat displays.

    :param llmclient: The LLMClient, or None.
    :type llmclient: Optional[LLMClient]
    :returns: The messages.
    :rtype: list[SmarterDictType]
    """
    # default_system_role_enhanced already starts with the date/time string.
    default_system_role = get_date_time_string()
    if llmclient and llmclient.default_system_role:
        default_system_role = llmclient.default_system_role_enhanced
    thread: list[SmarterDictType] = [
        {
            OpenAIMessageKeys.MESSAGE_ROLE_KEY: OpenAIMessageKeys.SYSTEM_MESSAGE_KEY,
            OpenAIMessageKeys.MESSAGE_CONTENT_KEY: default_system_role,
        }
    ]
    welcome_message = llmclient_welcome_message(llmclient)
    example_prompts = example_prompts_message(llmclient_example_prompts(llmclient))
    for introduction in (welcome_message, example_prompts):
        if introduction:
            thread.append(
                {
                    OpenAIMessageKeys.MESSAGE_ROLE_KEY: OpenAIMessageKeys.ASSISTANT_MESSAGE_KEY,
                    OpenAIMessageKeys.MESSAGE_CONTENT_KEY: introduction,
                }
            )
    return thread


[docs] class SmarterChatProviderBase(ChatDbMixin): """ Base class for all Smarter prompt providers. This class defines the core interface and shared logic for prompt providers that interact with LLMClients via the Smarter API, including both the Reactapp and deployed LLMClients accessible through named URLs. It is designed to be subclassed by specific provider_name implementations. The API is largely a superset of the OpenAI prompt completion API, with additional properties and methods for configuring the Reactapp and for managing additional message content types that are proprietary to Smarter. **Key Features:** - Provides a unified interface for prompt providers, supporting both OpenAI-compatible and proprietary Smarter features. - Handles message thread management, including system prompts, user/assistant messages, and plugin/tool messages. - Supports tools from plugins, MCPClients and extensions. - Manages provider_name configuration, validation, and readiness checks. - Tracks token usage and charge insertion for billing/auditing. **Usage:** Subclass this base class to implement a new prompt provider_name. Override or extend methods as needed for provider_name-specific logic. **Example:** .. code-block:: python class MyProvider(SmarterChatProviderBase): def my_custom_method(self): # Custom logic here pass """ __slots__ = ( "_default_model", "_default_system_role", "_default_temperature", "_default_max_completion_tokens", "_valid_chat_completion_models", "_messages", "_base_url", "_api_key", "_chat", "data", "plugins", "functions", "model", "temperature", "reasoning_effort", "model_warnings", "max_completion_tokens", "input_text", "completion_tokens", "prompt_tokens", "total_tokens", "reference", "iteration", "request_meta_data", "first_iteration", "first_response", "second_iteration", "second_response", "serialized_tool_calls", "tools", "available_functions", ) _default_model: Optional[str] _default_system_role: Optional[str] _default_temperature: Optional[float] _default_max_completion_tokens: Optional[int] _valid_chat_completion_models: Optional[list[str]] _messages: Optional[List[Dict[str, str]]] _base_url: Optional[str] _api_key: Optional[str] _chat: Optional[Prompt] data: Optional[SmarterDictType] plugins: Optional[List[PluginBase]] functions: Optional[List[str]] model: Optional[str] temperature: Optional[float] reasoning_effort: Optional[str] model_warnings: set[str] max_completion_tokens: Optional[int] input_text: Optional[str] completion_tokens: Optional[int] prompt_tokens: Optional[int] total_tokens: Optional[int] reference: Optional[str] iteration: int request_meta_data: SmarterDictType first_iteration: SmarterDictType first_response: Optional[ChatCompletion] second_response: Optional[ChatCompletion] second_iteration: Optional[SmarterDictType] serialized_tool_calls: Optional[list[SmarterDictType]] # built-in tools that we make available to all providers tools: Optional[list[SmarterDictType]] available_functions: SmarterDictType
[docs] def __init__( self, provider: Optional[Provider], provider_name: Optional[str], base_url: Optional[str], api_key: Optional[SecretStr], default_model: Optional[str], default_system_role: Optional[str] = smarter_settings.llm_default_system_role, default_temperature: Optional[float] = smarter_settings.llm_default_temperature, default_max_tokens: Optional[int] = smarter_settings.llm_default_max_tokens, valid_chat_completion_models: Optional[list[str]] = None, **kwargs, ): """ Initialize the SmarterChatProviderBase with the given parameters. :param provider: The Provider instance for the prompt provider. :type provider: Provider :param provider_name: The name of the prompt provider_name (e.g., "openai", "google"). :type provider_name: str :param base_url: The base URL for the prompt provider_name's API. :type base_url: str :param api_key: The API key for authenticating with the prompt provider_name. :type api_key: str :param default_model: The default model to use for prompt completions. :type default_model: str :param default_system_role: The default system role to use in the message thread. :type default_system_role: str :param default_temperature: The default temperature to use for prompt completions. :type default_temperature: float :param default_max_tokens: The default maximum number of tokens for prompt completions. :type default_max_tokens: int :param valid_chat_completion_models: A list of valid prompt completion models for the provider_name. :type valid_chat_completion_models: list[str] """ super().__init__( provider=provider, provider_name=provider_name, **kwargs, ) # constructor arguments self._default_model = None self._default_system_role = None self._default_temperature = None self._default_max_completion_tokens = None self._valid_chat_completion_models = None self._messages = [] self._base_url = None self._api_key = None self._chat = None self.data = None self.plugins = None self.functions = None self.model = None self.temperature = None self.reasoning_effort = None self.model_warnings = set() self.max_completion_tokens = None self.input_text = None self.completion_tokens = None self.prompt_tokens = None self.total_tokens = None self.reference = None self.iteration = 1 self.request_meta_data = {} self.first_iteration = { _InternalKeys.REQUEST_KEY: None, _InternalKeys.RESPONSE_KEY: None, } self.first_response = None self.second_response = None self.second_iteration = { _InternalKeys.REQUEST_KEY: {_InternalKeys.MESSAGES_KEY: []}, _InternalKeys.RESPONSE_KEY: {}, _InternalKeys.MESSAGES_KEY: [], } # initializations self.serialized_tool_calls = None self._chat = kwargs.get("prompt") self._provider_name = provider_name self._base_url = base_url self._api_key = api_key.get_secret_value() if api_key else None self._default_model = default_model self._default_system_role = default_system_role self._default_temperature = default_temperature self._default_max_completion_tokens = default_max_tokens self._valid_chat_completion_models = valid_chat_completion_models # the tools offered to the LLM, and the callables of their functions, by function name. They # are added per prompt, by the llmclient's plugins, MCPClients and extensions. self.tools = None self.available_functions = {} llm_provider_initialized.send(sender=self)
[docs] def prune_empty_values(self, data: SmarterDictType) -> SmarterDictType: """ Remove empty values from a dictionary. Some LLM providers, including MetaAI and GoogleAI will break if empty values are present in the completion request body. :param data: The completion request body. :returns: A copy of ``data`` without its ``None`` values, at every depth. :raises SmarterValueError: If ``data`` is not a dictionary. """ if not isinstance(data, dict): raise SmarterValueError(f"{self.formatted_class_name}: data must be a dictionary") def _prune(obj: object) -> object: if isinstance(obj, dict): return {k: _prune(v) for k, v in obj.items() if v is not None} if isinstance(obj, list): return [_prune(item) for item in obj if item is not None] return obj return {k: _prune(v) for k, v in data.items() if v is not None}
[docs] def validate(self): """ Validate that all required properties are set. Raise SmarterValueError if any required property is missing. :raises SmarterValueError: If any required property is missing. :returns: None :rtype: None """ if not self.prompt: raise SmarterValueError(f"{self.formatted_class_name}: prompt object is required") if not self.data: raise SmarterValueError(f"{self.formatted_class_name}: data object is required") if not self.user: raise SmarterValueError(f"{self.formatted_class_name}: user object is required") if not self.default_model: raise SmarterValueError(f"{self.formatted_class_name}: default_model is required") if not self.default_system_role: raise SmarterValueError(f"{self.formatted_class_name}: default_system_role is required") if not self.default_temperature: raise SmarterValueError(f"{self.formatted_class_name}: default_temperature is required") if not self.default_max_tokens: raise SmarterValueError(f"{self.formatted_class_name}: default_max_tokens is required") if is_missing_value(self.api_key): self.raise_missing_api_key() if self.valid_chat_completion_models and self.default_model not in self.valid_chat_completion_models: raise SmarterValueError( f"Internal error. Invalid default model: {self.default_model} not found in list of valid {self.provider_name} models {self.valid_chat_completion_models}." ) if not self.account: self.account = self.prompt.user_profile.account
[docs] def raise_missing_api_key(self): """ Log, with instructions, that the provider has no API key, and raise. A built-in Provider is created without a key when its Secret doesn't exist, so that the platform runs without it. Its prompts fail here, with an error that the prompt's response reports, rather than in the provider's SDK. The key's only source is the Provider's API key Secret, which no service reads from the environment (ADR-038, phase 3): the error says how to set the Secret. :raises SmarterConfigurationError: Always. """ secret_name = BUILTIN_PROVIDER_API_KEY_SECRET_NAMES.get(str(self.provider_name)) if secret_name is None: # not a built-in Provider: its key is the Secret that its manifest names, not a bootstrap secret. message = ( f"The {self.provider_name} Provider has no API key. Set the API key Secret that its manifest " "names, in the web console or with smarter apply." ) logger.error( SmarterFormattedText.banner( f"[PROVIDER WITHOUT API KEY] Prompts to the {self.provider_name} Provider fail: it has no API key.", "Set the API key Secret that its manifest names, in the web console or with smarter apply.", ) ) raise SmarterConfigurationError(message) message = ( f"The {self.provider_name} Provider has no API key. Set its API key Secret, {secret_name}, in the web " "console or with smarter apply. On a new platform, the init Job creates it from the platform's " "bootstrap secrets." ) logger.error( SmarterFormattedText.banner( f"[PROVIDER WITHOUT API KEY] Prompts to the {self.provider_name} Provider fail: it has no API key.", f"Set its API key Secret, {secret_name}, in the web console or with smarter apply.", "", "On a new platform, the init Job creates it from the platform's bootstrap secrets: the Helm", f"chart's bootstrapSecrets, or, locally, bootstrap-secrets/{secret_name} (make bootstrap-secrets).", ) ) raise SmarterConfigurationError(message)
[docs] @cached_property def ready(self) -> bool: """ Check if the prompt provider_name is ready to process requests. :returns: True if the prompt provider_name is ready, False otherwise. :rtype: bool """ retval = bool(self.prompt) and bool(self.data) and bool(self.account) if retval: charge_authorization(self.billed_user_profile.record_locator, self.__class__.__name__) # type: ignore return retval
@property def messages(self) -> Optional[List[Dict[str, str]]]: """ Get the list of messages in the prompt. This property returns the internal _messages attribute. :returns: The list of messages. :rtype: Optional[List[Dict[str, str]]] """ return self._messages @messages.setter def messages(self, value: List[Dict[str, str]]) -> None: """ Set the list of messages in the prompt. This property sets the internal _messages attribute. :param value: The list of messages to set. :type value: List[Dict[str, str]] :returns: None :rtype: None """ self._messages = value
[docs] @cached_property def formatted_class_name(self) -> str: """ Returns the class name in a formatted string along with the name of this mixin. :returns: The formatted class name. :rtype: str """ return f"{SmarterFormattedText.text(__name__)}.{SmarterChatProviderBase.__name__}[{id(self)}]"
@property def base_url(self) -> Optional[str]: """ Get the base URL of the prompt provider_name. This property returns the internal _base_url attribute. :returns: The base URL of the prompt provider_name. :rtype: Optional[str] """ return self._base_url @property def url(self) -> Optional[str]: """ Get the full URL for prompt completions. This property constructs the URL by appending the prompt completions endpoint to the base URL. :examples: If the base URL is "https://api.some-llm-company.com", the full URL will be "https://api.some-llm-company.com/v1/prompt/completions". :returns: The full URL for prompt completions. :rtype: Optional[str] """ return self._base_url + "prompt/completions" if self._base_url else None @property def api_key(self) -> Optional[str]: """ Get the API key of the prompt provider_name. This property returns the unmasked internal _api_key attribute. :returns: The unmasked API key of the prompt provider_name. :rtype: Optional[str] """ return self._api_key @property def default_model(self) -> Optional[str]: """ Get the default model of the prompt provider_name. This property returns the internal _default_model attribute. :returns: The default model of the prompt provider_name. :rtype: Optional[str] """ if self._default_model: return self._default_model if self.provider: return self.provider.default_model return None @property def default_system_role(self) -> Optional[str]: """ Get the default system role of the prompt provider_name. This property returns the internal _default_system_role attribute. :returns: The default system role of the prompt provider_name. :rtype: Optional[str] """ return self._default_system_role @property def default_temperature(self) -> Optional[float]: """ Get the default temperature of the prompt provider_name. This property returns the internal _default_temperature attribute. :returns: The default temperature of the prompt provider_name. :rtype: Optional[float] """ return self._default_temperature @property def default_max_tokens(self) -> Optional[int]: """ Get the default max completion tokens of the prompt provider_name. This property returns the internal _default_max_completion_tokens attribute. :returns: The default max completion tokens of the prompt provider_name. :rtype: Optional[int] """ return self._default_max_completion_tokens @property def valid_chat_completion_models(self) -> Optional[list[str]]: """ Get the list of valid prompt completion models for the prompt provider_name. This property returns the internal _valid_chat_completion_models attribute. A valid prompt completion model is one that is supported by the prompt provider_name's API for prompt completions. :returns: The list of valid prompt completion models. :rtype: Optional[list[str]] """ return self._valid_chat_completion_models
[docs] def messages_set_is_new(self, messages: list[SmarterDictType], is_new: bool = False) -> list[SmarterDictType]: """ Set the is_new flag for all messages in the message thread. This is used to track which messages are new and which have already been processed. This affects the treatment of messages in the Reactapp component, where new messages are styled differently. :param messages: The list of messages to set the is_new flag for. :type messages: list[SmarterDictType] """ retval = [] for message in messages: new_message = message.copy() new_message[_InternalKeys.SMARTER_IS_NEW] = is_new retval.append(new_message) return retval
[docs] def get_message_thread(self, data: SmarterDictType) -> List[Dict[str, str]]: """ Initialize the message thread of a session that has no stored history. The server is the authority on the system prompt and on the conversation's history, so the thread is built from the LLMClient's configuration, plus the client's latest user message, and nothing else: - the LLMClient's system role, which starts with the date and time. When the prompt has no LLMClient, or the LLMClient has no system role, the date and time only. - the LLMClient's welcome message and example prompts, as assistant messages, which is the introduction that Smarter Chat displays at the start of a session. - the client's latest user message, which the input guardrails scan. Everything else that the client sent is dropped: a ``system`` message, which would replace the LLMClient's system role, and earlier ``user``, ``assistant`` or ``tool`` turns, which no guardrail scans. Smarter Chat, the cli and the SDKs send a copy of the system role and of the introduction, which is expected. Anything else is logged as a warning, without its content. A session that has a stored history uses that history instead, so a client's messages never reach the LLM, other than the latest user message. :raises SmarterValueError: If the request body is invalid, or has no user message. :param data: The incoming data containing the message thread. :type data: SmarterDictType :returns: The initialized message thread. :rtype: List[Dict[str, str]] """ llmclient = self.prompt.llmclient if self.prompt else None request_body = get_request_body(data=data) client_message_thread, input_text = parse_request(request_body) if not isinstance(client_message_thread, list): raise SmarterValueError( f"{self.formatted_class_name}: Invalid request body. Expected a list of messages, got: {type(client_message_thread)}" ) if not input_text or not isinstance(input_text, str): raise SmarterValueError(f"{self.formatted_class_name}: Invalid request body. A user message is required.") welcome_message = llmclient_welcome_message(llmclient) example_prompts = llmclient_example_prompts(llmclient) thread = introduction_messages(llmclient) thread.append( { OpenAIMessageKeys.MESSAGE_ROLE_KEY: OpenAIMessageKeys.USER_MESSAGE_KEY, OpenAIMessageKeys.MESSAGE_CONTENT_KEY: input_text, } ) self.log_dropped_client_messages( client_message_thread=client_message_thread, system_role=getattr(llmclient, "default_system_role", None) if llmclient else None, welcome_message=welcome_message, example_prompts=example_prompts, ) retval = self.messages_set_is_new(thread, is_new=False) return retval
[docs] def log_dropped_client_messages( self, client_message_thread: list[SmarterDictType], system_role: Optional[str], welcome_message: str, example_prompts: list[str], ) -> None: """ Log the messages of a new session's request that :meth:`get_message_thread` dropped. Every message except the latest user message is dropped. A copy of the LLMClient's system role, welcome message or example prompts, which Smarter Chat, the cli and the SDKs send at the start of a session, is expected, and logged at debug level. Any other message, such as a system message that would replace the system role, or an earlier turn of the conversation, is logged as a warning. Only the number of messages, and their roles, are logged, never their content. :param client_message_thread: The messages that the client sent. :type client_message_thread: list[SmarterDictType] :param system_role: The LLMClient's system role, without the date and time. :type system_role: Optional[str] :param welcome_message: The LLMClient's welcome message. :type welcome_message: str :param example_prompts: The LLMClient's example prompts. :type example_prompts: list[str] :returns: None :rtype: None """ role_key, content_key = OpenAIMessageKeys.MESSAGE_ROLE_KEY, OpenAIMessageKeys.MESSAGE_CONTENT_KEY latest_user_index = max( ( index for index, message in enumerate(client_message_thread) if message.get(role_key) == OpenAIMessageKeys.USER_MESSAGE_KEY ), default=-1, ) expected_system_roles = { role.strip() for role in (system_role, smarter_settings.llm_default_system_role) if role } def is_expected(message: SmarterDictType) -> bool: content = message.get(content_key) text = content.strip() if isinstance(content, str) else None if text is None: return False if not text: return True if message.get(role_key) == OpenAIMessageKeys.SYSTEM_MESSAGE_KEY: # Smarter Chat and the SDKs send the system role as is, the cli maybe with the date and time. return any(text.endswith(role) for role in expected_system_roles) if message.get(role_key) == OpenAIMessageKeys.ASSISTANT_MESSAGE_KEY: # the example prompts' heading is translated by Smarter Chat, so look for the prompts. return bool(welcome_message and welcome_message.strip() in text) or bool( example_prompts and all(prompt in text for prompt in example_prompts) ) return False dropped = [message for index, message in enumerate(client_message_thread) if index != latest_user_index] unexpected = [message for message in dropped if not is_expected(message)] if unexpected: roles = sorted({str(message.get(role_key)) for message in unexpected}) logger.warning( "dropped %d of the client's messages that a new session does not accept, " "with the roles %s, for prompt %s. The LLMClient's system role, and the client's latest user message, " "are used instead.", len(unexpected), roles, self.prompt.id if self.prompt else None, ) if len(dropped) > len(unexpected): logger.debug( "dropped %d of the client's messages that copy the LLMClient's introduction.", len(dropped) - len(unexpected), )
[docs] def get_input_text_prompt(self, data: SmarterDictType) -> str: """ Extract the input text prompt from the incoming data. This method validates that the input text is present and is a string. :raises SmarterValueError: If the input text is missing or invalid. :param data: The incoming data containing the input text. :type data: SmarterDictType :returns: The input text prompt. :rtype: str """ request_body = get_request_body(data=data) _, input_text = parse_request(request_body) if not input_text: raise SmarterValueError(f"{self.formatted_class_name}: input_text is required") if not isinstance(input_text, str): raise SmarterValueError(f"{self.formatted_class_name}: input_text must be a string") return input_text
[docs] def append_message( self, role: str, content: Optional[Union[SmarterDictType, list, str]], message: Optional[SmarterDictType] = None ) -> None: """ Append a message to the internal message list. This method validates the role and content before appending the message. :param role: The role of the message (e.g., "user", "assistant", "system"). :type role: str :param content: The content of the message. Can be a string, SmarterDictType, or list. :type content: Optional[Union[SmarterDictType, list, str]] :param message: An optional message dictionary to append. If provided, it will be used instead of creating a new message. :raises SmarterValueError: If the role is invalid or if both content and message are empty. :returns: None :rtype: None """ if role not in OpenAIMessageKeys.all_roles: raise SmarterValueError( f"Internal error. Invalid message role: {role} not found in list of valid {self.provider_name} message roles {OpenAIMessageKeys.all_roles}." ) if not content and not message: raise SmarterValueError( f"{self.formatted_class_name}: content or message must be provided. Both cannot be empty." ) message = message or {} if not isinstance(message, dict): raise SmarterValueError(f"{self.formatted_class_name}: message must be a dictionary") new_message = message.copy() new_message[OpenAIMessageKeys.MESSAGE_ROLE_KEY] = role new_message[OpenAIMessageKeys.MESSAGE_CONTENT_KEY] = content new_message[_InternalKeys.SMARTER_IS_NEW] = True if isinstance(self.messages, list): self.messages.append(new_message)
[docs] def append_message_plugin_selected(self, plugin: str) -> None: """ Append a message indicating that a plugin was selected. :param plugin: The name of the selected plugin. :type plugin: str :returns: None :rtype: None """ content = f"Smarter selected this plugin: {plugin}" self.append_message(role=OpenAIMessageKeys.SMARTER_MESSAGE_KEY, content=content)
[docs] def append_message_tool_called( self, tool_call: ChatCompletionMessageToolCallUnion, tool_name: Optional[str] = None ) -> None: """ Append a message indicating that a tool was called. :param tool_call: The tool call object containing function name and arguments. :type tool_call: ChatCompletionMessageToolCallUnion :param tool_name: The tool's name as users know it, e.g. a plugin's name rather than its symbolic function name, ``smarter_plugin_0000000016``. Defaults to the function name. The tool call's json, below the message, keeps the function name that the LLM called. :type tool_name: Optional[str] :returns: None :rtype: None """ tool_call_to_json = tool_call.model_dump() name = tool_name or tool_call.function.name # type: ignore content = f"{self.provider_name} called this tool: {name}({tool_call.function.arguments})" # type: ignore content = content + f"\n\nTool call:\n--------------------\n{json.dumps(tool_call_to_json, indent=4)}" self.append_message(role=OpenAIMessageKeys.SMARTER_MESSAGE_KEY, content=content)
[docs] def append_error_response(self, error_message: str) -> None: """ Append a message indicating that an error occurred. :param error_message: The error message to append. :type error_message: str :returns: None :rtype: None """ content = f"LLM responded with the following error: {error_message}" self.append_message(role=OpenAIMessageKeys.SMARTER_ERROR_KEY, content=content)
def _insert_charge_by_type(self, resource_locators: list[str], charge_type: str, charge_user: bool = True) -> None: """ Insert a charge record based on the charge type. This method uses the internal db_insert_charge method to create a charge record in the database. :param resource_locators: The resources to charge. :type resource_locators: list[str] :param charge_type: The type of charge (e.g., prompt completion, tool, plugin). :type charge_type: str :param charge_user: Whether to charge the user and the account too. See ``db_insert_charge``. :type charge_user: bool :returns: None :rtype: None """ if not resource_locators: raise SmarterValueError(f"{self.formatted_class_name}: resource_locators must be provided") if self.completion_tokens is None or self.prompt_tokens is None or self.total_tokens is None: raise SmarterValueError( f"{self.formatted_class_name}: completion_tokens, prompt_tokens, and total_tokens must be set before inserting a charge." ) self.db_insert_charge( resource_locators=resource_locators, charge_type=charge_type, completion_tokens=self.completion_tokens, prompt_tokens=self.prompt_tokens, total_tokens=self.total_tokens, charge_user=charge_user, )
__all__ = ["SmarterChatProviderBase"]