# pylint: disable=W0602,C0302
"""Base class for prompt providers."""
import ast
import re
import time
import traceback
from http import HTTPStatus
from typing import Optional, Union
import openai
from openai.types.chat.chat_completion import ChatCompletion, Choice
from openai.types.chat.chat_completion_message import ChatCompletionMessage
from openai.types.chat.chat_completion_message_tool_call import (
ChatCompletionMessageToolCall,
ChatCompletionMessageToolCallUnion,
)
from openai.types.completion_usage import CompletionUsage
from pydantic import JsonValue
from smarter.apps.account.models import (
ChargeTypes,
SmarterBudgetExceeded,
UserProfile,
charge_authorization,
)
from smarter.apps.guardrail.services import (
GuardrailBlockedError,
GuardrailPipeline,
GuardrailStage,
PipelineDisposition,
PipelineResult,
)
from smarter.apps.llmtool.extension.toolkit import ExtensionToolkit
from smarter.apps.llmtool.manifest.controller import PluginController
from smarter.apps.llmtool.models import PluginMeta, PluginPrompt
from smarter.apps.llmtool.plugin.base import PluginBase
from smarter.apps.llmtool.runner import ToolCallLabel, labeled_tool_calls
from smarter.apps.llmtool.serializers import PluginMetaSerializer
from smarter.apps.mcpclient.models import MCPClient
from smarter.apps.mcpclient.toolkit import MCP_INSTRUCTIONS_PREFIX, MCPToolkit
from smarter.apps.prompt.models import Prompt
from smarter.apps.prompt.receivers import (
llm_tool_presented,
llm_tool_requested,
llm_tool_responded,
)
from smarter.apps.prompt.signals import (
chat_plugin_called,
chat_request,
chat_response,
chat_response_failure,
chat_tool_called,
prompt_finished,
prompt_started,
)
from smarter.apps.provider.services.text_completion.const import OpenAIMessageKeys
from smarter.apps.provider.services.text_completion.lib.protocols import (
SmarterChatCompletionResponseType,
)
from smarter.apps.provider.services.text_completion.utils import (
cap_message_history,
http_response_factory,
pair_tool_messages,
)
from smarter.apps.vectorsearch.toolkit import VectorsearchToolkit
from smarter.common.conf import smarter_settings
from smarter.common.exceptions import (
SmarterConfigurationError,
SmarterIlligalInvocationError,
SmarterValueError,
)
from smarter.common.utils import mask_identifier
from smarter.lib import json, logging
from smarter.lib.cache.tool_results import is_error_result
from smarter.lib.django import waffle
from smarter.lib.django.waffle import SmarterWaffleSwitches
from smarter.lib.logging import WaffleSwitchedLoggerWrapper
from smarter.lib.logging.redis_log_handler import request_id_context
from smarter.lib.openai.model_capabilities import closest_reasoning_effort
from smarter.lib.openai.model_quirks import (
DEFAULT_TEMPERATURE_ONLY_MODELS,
REASONING_EFFORT_NONE,
REASONING_MODEL_DEFAULT_TEMPERATURE,
SUPPORTED_REASONING_EFFORTS,
TEMPERATURE_REJECTED_MODELS,
TOOLS_MODEL_SUGGESTION,
TOOLS_REJECT_REASONING_EFFORT_MODELS,
TOOLS_REQUIRE_NO_REASONING_MODELS,
TOOLS_UNSUPPORTED_MODELS,
TOOLS_WITH_REASONING_MODEL_SUGGESTION,
apply_model_quirks,
rejected_parameter,
rejects_tools_at_reasoning_effort,
supported_reasoning_efforts,
)
from smarter.lib.typing import SmarterDictType
from .chat_provider_base import SmarterChatProviderBase
from .exception_map import exception_status_and_message
from .internal_keys import _InternalKeys
from .prompt_cache import (
PromptCacheHit,
PromptCacheKey,
cache_prompt_response,
claim_first_message,
get_cached_prompt_response,
message_digest,
)
# pylint: disable=W0613
[docs]
def should_log(level):
"""Check if logging should be done based on the waffle switch."""
return waffle.switch_is_active(SmarterWaffleSwitches.PROMPT_LOGGING)
OPENAI_TOOL_CHOICE = "auto"
MAX_REQUEST_ATTEMPTS = 4
"""The most times that one request is sent while the vendor's rejections teach Smarter what its model accepts."""
MAX_HISTORY_CHARACTERS = 100_000
"""
The most characters of a prompt's message history that are sent to the LLM, about 25,000 tokens.
A chat's whole history is persisted, and without a limit every prompt would send all of it again,
so that a long chat grows slower and more expensive with each prompt. The oldest turns are left out
of the request first, never the system prompt or the current turn. See
:func:`~smarter.apps.provider.services.text_completion.utils.cap_message_history`.
"""
base_logger = logging.getSmarterLogger(__name__)
logger = WaffleSwitchedLoggerWrapper(base_logger, should_log)
BLOCKED_MESSAGE_PLACEHOLDER = "[This message was blocked by a guardrail.]"
"""What replaces a user message that an input guardrail blocked, in the conversation's history."""
MARKDOWN_SYSTEM_PROMPT = (
"Your responses are displayed in a chat window that renders GitHub flavored Markdown: headings, bold, "
"italics, strikethrough, lists, tables, block quotes, inline code, fenced code blocks, links and images. "
"Use Markdown when it makes a response clearer, and name the language of each fenced code block. "
"It also typesets math written in LaTeX: \\( ... \\) for inline math, and \\[ ... \\] or $$ ... $$ for a "
"displayed equation. A single dollar sign is not math, so never use $ ... $ for math. "
"It draws a fenced code block whose language is mermaid as a Mermaid diagram, such as a flowchart, "
"sequence diagram, class diagram, state diagram or entity relationship diagram. Draw one when a "
"process, architecture or set of relationships is easier to understand as a picture, and keep its "
"syntax simple: quote labels that contain punctuation. "
"The chat window does not render HTML, so do not use it. "
"To show an image, use Markdown image syntax, , but only with an image url "
"that the user gave you or that a tool returned. NEVER invent an image url, because a broken image "
"looks worse than no image."
)
"""
Added to the system prompt of every request, so that the LLM knows what the chat window renders.
It is the single source of the chat window's rendering rules, so an LLMClient's ``defaultSystemRole``
need not repeat them, and should only describe the formatting that suits its own persona.
It is added to the request's messages only (see :attr:`OpenAISmarterClient.openai_messages`), and is
never saved in the conversation's history, nor displayed in the chat.
"""
[docs]
def add_markdown_system_prompt(messages: list[SmarterDictType]) -> list[SmarterDictType]:
"""
Tell the LLM that its responses may use Markdown.
:data:`MARKDOWN_SYSTEM_PROMPT` is appended to the first system message, or is the system
message of a thread that has none. The messages are copies, so the conversation's history
is unchanged.
:param messages: The request's messages.
:type messages: list[SmarterDictType]
:returns: The request's messages, with the Markdown instructions.
:rtype: list[SmarterDictType]
"""
for i, message in enumerate(messages):
if message.get(OpenAIMessageKeys.MESSAGE_ROLE_KEY) == OpenAIMessageKeys.SYSTEM_MESSAGE_KEY:
content = message.get(OpenAIMessageKeys.MESSAGE_CONTENT_KEY) or ""
if MARKDOWN_SYSTEM_PROMPT not in content:
messages[i] = {
**message,
OpenAIMessageKeys.MESSAGE_CONTENT_KEY: f"{content}\n\n{MARKDOWN_SYSTEM_PROMPT}".strip(),
}
return messages
return [
{
OpenAIMessageKeys.MESSAGE_ROLE_KEY: OpenAIMessageKeys.SYSTEM_MESSAGE_KEY,
OpenAIMessageKeys.MESSAGE_CONTENT_KEY: MARKDOWN_SYSTEM_PROMPT,
},
*messages,
]
[docs]
def provider_messages(messages: list[SmarterDictType]) -> list[SmarterDictType]:
"""
Return a conversation's messages as they are sent to the LLM provider.
The conversation's history holds Smarter's own messages and fields, which are only displayed
in the chat, and which an OpenAI-compatible api would reject. This is the one place that
removes them, for every request that Smarter sends, and for the request that the workbench
downloads (see :class:`~smarter.apps.prompt.views.detailviews.prompt_provider_request_view.PromptProviderRequestView`):
- only the messages whose role is in :attr:`OpenAIMessageKeys.all` are kept, so the ``smarter``
and ``smarter_error`` messages are left out.
- the ``smarter_is_new`` field is removed.
- :data:`MARKDOWN_SYSTEM_PROMPT` is added to the system prompt.
- the oldest turns are left out of a long conversation (:data:`MAX_HISTORY_CHARACTERS`).
- every tool call is paired with its reply.
The messages are copies, so the conversation's history is unchanged.
:param messages: The conversation's messages, as they are saved in its history.
:type messages: list[SmarterDictType]
:returns: The request's messages.
:rtype: list[SmarterDictType]
"""
retval = []
for message in messages:
role = message.get(OpenAIMessageKeys.MESSAGE_ROLE_KEY)
if role not in OpenAIMessageKeys.all:
continue
message_copy = message.copy()
message_copy.pop(_InternalKeys.SMARTER_IS_NEW, None)
retval.append(message_copy)
retval = add_markdown_system_prompt(retval)
retval = cap_message_history(retval, MAX_HISTORY_CHARACTERS)
# the thread may come from the client, which keeps the tool replies but not the
# assistant's tool_calls, and OpenAI refuses a tool reply without its tool call.
retval = pair_tool_messages(retval)
return retval
[docs]
class OpenAISmarterClient(SmarterChatProviderBase):
"""
Prompt provider for OpenAI-compatible text completion APIs.
This provider class enables seamless integration with any vendor or service
that implements the OpenAI prompt completion API, including both OpenAI and third-party providers
that adhere to the same protocol and message formats.
**Key Features:**
- Supports OpenAI's prompt completion API and compatible alternatives.
- Handles message formatting, tool calls, plugin integration, and billing.
- Manages multi-step prompt completion workflows, including tool and plugin responses.
- Provides hooks for plugin selection, function registration, and error handling.
**Usage:**
Inherit from this class to implement a prompt provider that communicates with any OpenAI-compatible API endpoint.
This class is suitable for use cases where you want to support multiple LLM vendors with a unified interface.
**Example:**
.. code-block:: python
class MyProvider(OpenAISmarterClient):
pass
provider = MyProvider()
response = provider.handler(user_profile, prompt, data)
.. seealso::
- https://developers.openai.com/api/reference/overview/prompt
- :class:`SmarterChatProviderBase`
"""
mcp_toolkit: Optional[MCPToolkit] = None
"""The MCP tools of the current prompt.
See :meth:`handle_mcp_clients`.
"""
prompt_cache_key: Optional[PromptCacheKey] = None
"""The cache key of the current prompt, if it is the first message of a conversation.
See :meth:`handle_prompt_cache_lookup`.
"""
prompt_cacheable: bool = False
"""Whether the current prompt's answer may be cached.
A tool call that may change something clears it.
"""
extension_toolkit: Optional[ExtensionToolkit] = None
"""The extension tools of the current prompt.
See :meth:`handle_extensions`.
"""
vectorsearch_toolkit: Optional[VectorsearchToolkit] = None
"""The Vectorsearch tools of the current prompt.
See :meth:`handle_vectorsearches`.
"""
guardrail_pipeline: Optional[GuardrailPipeline] = None
"""The MCP tools of the current prompt.
See :meth:`handle_mcp_clients`.
"""
@property
def openai_messages(self) -> list[SmarterDictType]:
"""
Return a sanitized list of messages compatible with OpenAI's prompt completion API.
This property processes the internal message list, removing Smarter-specific annotations
(such as metadata about tool calls and interim completion token charges) to ensure that
only valid OpenAI message fields are included. This is essential for avoiding API errors
related to unexpected or extraneous fields.
:returns: A list of dictionaries representing prompt messages, formatted for OpenAI's API.
:rtype: list[SmarterDictType]
:raises SmarterValueError: If the internal message list is not a list.
Example::
[
{
"role": "assistant",
"content": "Welcome to Smarter!",
"tool_calls": [
{
"id": "call_ABC123",
"type": "function",
"function": {
"name": "smarter_plugin_0000000045",
"arguments": "{\"description\":\"AI\"}"
}
}
]
},
{
"role": "tool",
"name": "smarter_plugin_0000000045",
"content": "SqlPlugin stackademy_sql response: ...",
"tool_call_id": "call_ABC123"
}
]
.. important::
- OpenAI expects that every assistant message with a ``tool_calls`` field is immediately followed by a corresponding ``tool`` message for each ``tool_call_id``. Failure to do so will result in an API error.
- If you include Smarter-specific fields (such as ``smarter_is_new``) in the message list, OpenAI's API may reject the request.
- On the first iteration, tool call responses are excluded from the message list to comply with OpenAI's requirements.
.. seealso::
- https://developers.openai.com/api/reference/overview/prompt/create
- :class:`OpenAIMessageKeys`
"""
if not isinstance(self.messages, list):
raise SmarterValueError(f"{self.formatted_class_name}: messages must be a list, got {type(self.messages)}")
return provider_messages(self.messages)
[docs]
@staticmethod
def add_markdown_system_prompt(messages: list[SmarterDictType]) -> list[SmarterDictType]:
"""
Tell the LLM that its responses may use Markdown.
See :func:`add_markdown_system_prompt`.
:param messages: The request's messages.
:type messages: list[SmarterDictType]
:returns: The request's messages, with the Markdown instructions.
:rtype: list[SmarterDictType]
"""
return add_markdown_system_prompt(messages)
@property
def new_messages(self) -> list[SmarterDictType]:
"""
Return a list of messages that are marked as new.
This property filters the internal message list to return only those messages
that have the 'smarter_is_new' flag set to True.
:returns: A list of new messages.
:rtype: list[SmarterDictType]
"""
if self.messages is None:
return []
try:
return [message for message in self.messages if message[_InternalKeys.SMARTER_IS_NEW]]
except KeyError:
logger.error("KeyError: '%s' key not found in a message", _InternalKeys.SMARTER_IS_NEW)
return self.messages
[docs]
def prep_first_request(self):
"""
Prepare the first request for the prompt completion.
This is called
at the beginning of the prompt completion process.
:raises SmarterValueError: If the messages are not a list, or if tool definitions are invalid.
:returns: None
:rtype: None
"""
logger.debug("called")
# ensure that all message history is marked as not new
if isinstance(self.messages, list):
self.messages = self.messages_set_is_new(self.messages, is_new=False)
tool_choice = OPENAI_TOOL_CHOICE
self.first_iteration[_InternalKeys.REQUEST_KEY] = {
_InternalKeys.API_URL: self.base_url,
_InternalKeys.API_KEY: self.mask_string(self.api_key),
_InternalKeys.MODEL_KEY: self.model,
_InternalKeys.MESSAGES_KEY: self.openai_messages,
_InternalKeys.TEMPERATURE_KEY: self.temperature,
_InternalKeys.MAX_COMPLETION_TOKENS_KEY: self.max_completion_tokens,
_InternalKeys.TOOLS_KEY: self.tools,
}
reasoning_effort = getattr(self, "reasoning_effort", None)
if reasoning_effort:
# pylint: disable=E1137
self.first_iteration[_InternalKeys.REQUEST_KEY][_InternalKeys.REASONING_EFFORT_KEY] = reasoning_effort
# create a Smarter UI message with the established configuration
content = f"Prompt configuration: llm={self.provider_name}, url={self.url} api_key={self.mask_string(self.api_key)} model={self.model}, temperature={self.temperature}, max_completion_tokens={self.max_completion_tokens}"
if reasoning_effort:
content = content + f", reasoning_effort={reasoning_effort}"
if self.tools:
content = content + f", tool_choice={tool_choice}."
self.append_message(role=OpenAIMessageKeys.SMARTER_MESSAGE_KEY, content=content)
if self.tools:
# this is necessary because of this 400 response in cases where
# tool_choice is set but not tools are provided:
# 'Error code: 400 - Invalid value 'tool_choice' is only allowed when 'tools' are specified."
#
# pylint: disable=E1137
self.first_iteration[_InternalKeys.REQUEST_KEY][_InternalKeys.TOOL_CHOICE] = tool_choice
# for any tools that are included in the request, add Smarter UI messages for each tool
for tool in self.tools:
tool_type = tool.get("type")
if not tool_type:
logger.warning(
"tool type is required in tool definition: %s. This is a bug",
tool,
)
this_tool = tool.get(tool_type) if tool_type else {}
if not isinstance(this_tool, dict):
raise SmarterValueError(
f"{self.formatted_class_name}: tool definition for tool type '{tool_type}' must be a dictionary. Got {type(this_tool)}. Tool definition: {tool}"
)
tool_name = this_tool.get("name")
if not tool_name:
logger.warning(
"tool name is required in tool definition: %s. This is a bug",
tool,
)
tool_description = this_tool.get("description")
if not tool_description:
logger.warning(
"tool description is required in tool definition: %s. This is a bug",
tool,
)
tool_parameters = this_tool.get("parameters", {}).get("properties", {})
inputs = []
for parameter, details in tool_parameters.items():
if "description" in details:
inputs.append(f"{parameter}: {details['description']}")
elif "enum" in details:
inputs.append(f"{parameter}: {', '.join(details['enum'])}")
inputs_text = ", ".join(inputs)
# the tool's name as users know it, e.g. a plugin's name rather than its symbolic function
# name, smarter_plugin_0000000016. The definition below has the function name the LLM sees.
display_name = self.tool_display_name(tool_name) if tool_name else tool_name
content = f"Tool presented: {display_name}({inputs_text}) - {tool_description} "
content = content + f"\n\nTool definition:\n--------------------\n{json.dumps(tool, indent=4)}"
self.append_message(role=OpenAIMessageKeys.SMARTER_MESSAGE_KEY, content=content)
# send a prompt completion request signal. this triggers a variety of db records to be created
# asynchronously in the background via Celery tasks.
chat_request.send(
sender=self.handler,
prompt=self.prompt,
iteration=self.iteration,
data=self.first_iteration[_InternalKeys.REQUEST_KEY],
)
[docs]
def prep_second_request(self):
"""
Prepare the second request for the prompt completion.
This is called
in response to a tool call that requires a second request to the LLM.
:returns: None
:rtype: None
"""
logger.debug("called.")
if not isinstance(self.second_iteration, dict):
raise SmarterValueError(
f"{self.formatted_class_name}: second_iteration must be a dictionary, got {type(self.second_iteration)}"
)
self.second_iteration[_InternalKeys.REQUEST_KEY] = {
_InternalKeys.API_URL: self.base_url,
_InternalKeys.API_KEY: self.mask_string(self.api_key),
_InternalKeys.MODEL_KEY: self.model,
_InternalKeys.MESSAGES_KEY: self.openai_messages,
}
chat_request.send(
sender=self.handler,
prompt=self.prompt,
iteration=self.iteration,
data=self.second_iteration[_InternalKeys.REQUEST_KEY],
)
[docs]
def append_openai_response(self, response: ChatCompletion) -> None:
"""
Append the OpenAI-compatible response message to the internal message list.
2025-06-20: updated to use model_dump_json() to ensure compatibility with Pydantic v2.
2025-10-02: updated to validate that the response message is indeed a ChatCompletionMessage.
:param response: The OpenAI-compatible prompt completion response.
:type response: ChatCompletion
:returns: None
:rtype: None
"""
logger.debug("called.")
response_message = response.choices[0].message
message_json = json.loads(response_message.model_dump_json())
if not isinstance(response_message, ChatCompletionMessage):
raise SmarterConfigurationError(
f"{self.formatted_class_name}: response_message is not of the expected type ChatCompletionMessage. Received response of type {type(response_message)}. Response: {response.model_dump_json()}"
)
self.append_message(role=response_message.role, content=response_message.content, message=message_json) # type: ignore[call-arg]
[docs]
def append_openai_error_response(self, response: ChatCompletion, e: Optional[Exception] = None) -> None:
"""
Append an error message to the internal message list based on the OpenAI response.
:param response: The OpenAI prompt completion response containing the error.
:type response: ChatCompletion
:returns: None
:rtype: None
"""
def extract_json_objects(text) -> Optional[SmarterDictType]:
"""
Evaluate the text to attempt to extract any JSON objects that may be present.
This is useful for extracting json error information that might exist inside of the error messages.
Find all curly-brace blocks (non-greedy) and attempt to parse
them as JSON objects.
example: a string like this:
'Error code: 404 - {
'error': {
'message': 'The model `gpt-not-a-valid-model` does not exist or you do not have access to it.',
'type': 'invalid_request_error',
'param': None,
'code': 'model_not_found'
}
}'
"""
candidates = re.findall(r"{.*}", text, re.DOTALL)
for candidate in candidates:
try:
logger.debug(
"trying ast to parse candidate: %s",
candidate,
)
obj = ast.literal_eval(candidate)
json.dumps(obj) # validate the json
return obj
# pylint: disable=broad-except
except Exception:
logger.debug(
"ast failed to parse candidate: %s",
candidate,
)
continue
return None
logger.debug("called.")
response_message = response.choices[0].message
if not isinstance(response_message, ChatCompletionMessage):
raise SmarterConfigurationError(
f"{self.formatted_class_name}: response_message is not of the expected type ChatCompletionMessage. Received response of type {type(response_message)}. Response: {response.model_dump_json()}"
)
content = str(response_message.content)
details = content
json_objects = extract_json_objects(content)
if json_objects:
# create a more nicely formatted message.
details = f"{self.base_url} raised the following {e.__class__.__name__} exception: {json.dumps(json_objects, indent=4)}"
provider_message = self.provider_error_text(json_objects)
if provider_message:
content = f"The LLM provider rejected the request: {provider_message}"
else:
content = details
# The chat displays smarter_error messages in production mode too, so this one is only
# the error. The stack trace is in the server's log, and in a debug_mode platform's
# smarter message, which the chat displays in sandbox mode only.
self.append_message(role=OpenAIMessageKeys.SMARTER_ERROR_KEY, content=content)
if smarter_settings.debug_mode:
stack_trace = traceback.format_exc()
details = details + f"\n\nPython Stack trace:\n--------------------\n{stack_trace}"
self.append_message(role=OpenAIMessageKeys.SMARTER_MESSAGE_KEY, content=details)
[docs]
@staticmethod
def provider_error_text(error_object: SmarterDictType) -> Optional[str]:
"""
The message of an LLM provider's error object, e.g. ``{'error': {'message': '...'}}``.
:param error_object: The error object that the provider returned.
:type error_object: SmarterDictType
:returns: The error's message, or None if it has none.
:rtype: Optional[str]
"""
error = error_object.get("error")
if not isinstance(error, dict):
return None
message = error.get("message")
if not isinstance(message, str):
return None
if not message:
return None
return message
[docs]
def provider_record_locator(self) -> str:
"""
Return the record locator of the Provider that a charge is billed to.
:returns: The Provider's record locator.
:rtype: str
:raises SmarterValueError: If the Provider is not set.
"""
if self.provider is None:
raise SmarterValueError(f"{self.formatted_class_name}: provider is required to insert a charge.")
return self.provider.record_locator
[docs]
def handle_response(self) -> None:
"""
Handle internal billing, and append messages to the response for prompt completion and the billing summary.
:returns: None
:rtype: None
"""
logger.debug("iteration: %s", self.iteration)
response = self.second_response if self.iteration >= 2 else self.first_response
if not response:
raise SmarterValueError(
f"{self.formatted_class_name}.handle_response(): response is required for iteration {self.iteration}, but was not set."
)
if not response.usage:
raise SmarterValueError(
f"{self.formatted_class_name}.handle_response(): response.usage is required for iteration {self.iteration}, but was not set."
)
self.prompt_tokens = response.usage.prompt_tokens
self.completion_tokens = response.usage.completion_tokens
self.total_tokens = response.usage.total_tokens
self.reference = response.system_fingerprint
if self.prompt is None:
raise SmarterValueError(
f"{self.formatted_class_name}.handle_response(): prompt is required for iteration {self.iteration}, but was not set."
)
resource_locators = [self.provider_record_locator(), self.prompt.llmclient.record_locator]
self._insert_charge_by_type(resource_locators, ChargeTypes.PROMPT_COMPLETION.value)
self.append_message(
role=OpenAIMessageKeys.SMARTER_MESSAGE_KEY,
content=f"{self.provider_name} prompt charges: {self.prompt_tokens} prompt tokens, {self.completion_tokens} completion tokens = {self.total_tokens} total tokens charged.",
)
if self.iteration == 1:
if not self.first_response:
raise SmarterIlligalInvocationError(
f"{self.formatted_class_name}.handle_response(): first_response is required for iteration 1, but was not set."
)
self.first_iteration[_InternalKeys.RESPONSE_KEY] = json.loads(self.first_response.model_dump_json())
if self.iteration >= 2:
if not self.second_response:
raise SmarterIlligalInvocationError(
f"{self.formatted_class_name}.handle_response(): second_response is required for iteration 2, but was not set."
)
if not isinstance(self.second_iteration, dict):
raise SmarterValueError(
f"{self.formatted_class_name}.handle_response(): second_iteration must be a dictionary, got {type(self.second_iteration)}"
)
self.second_iteration[_InternalKeys.RESPONSE_KEY] = json.loads(self.second_response.model_dump_json())
serialized_request = None
serialized_response = None
if self.iteration == 1:
serialized_request = self.first_iteration[_InternalKeys.REQUEST_KEY]
serialized_response = self.first_iteration[_InternalKeys.RESPONSE_KEY]
elif self.second_iteration:
serialized_request = self.second_iteration[_InternalKeys.REQUEST_KEY]
serialized_response = self.second_iteration[_InternalKeys.RESPONSE_KEY]
chat_response.send(
sender=self.handler,
prompt=self.prompt,
iteration=self.iteration,
request=serialized_request,
response=serialized_response,
messages=self.messages,
)
[docs]
def handle_plugin_called(self, plugin: PluginBase) -> None:
"""
Handle a plugin tool call.
example: SqlPlugin, ApiPlugin, StaticPlugin etc.
:param plugin: The plugin instance that was called.
:type plugin: PluginBase
:returns: None
:rtype: None
"""
chat_plugin_called.send(
sender=self.handler,
prompt=self.prompt,
plugin=plugin,
input_text=self.input_text,
)
# the model call's tokens were charged to the provider, the llmclient, the user and the account
# as its completion. The plugin's charge goes to the plugin and its connection only, so that
# those tokens are counted once for each resource.
resource_locators = [plugin.plugin_meta.record_locator] # type: ignore[union-attr]
if plugin.plugin_data and hasattr(plugin.plugin_data, "connection"):
resource_locators.append(plugin.plugin_data.connection.record_locator) # type: ignore[union-attr]
self._insert_charge_by_type(resource_locators, ChargeTypes.PLUGIN.value, charge_user=False)
self.db_insert_chat_plugin_usage(prompt=self.prompt, plugin=plugin, input_text=self.input_text)
[docs]
def authorize_budgets(self) -> None:
"""
Check the budgets of everything that a prompt completion is charged to, before calling the LLM.
The user is :attr:`billed_user_profile`: the LLMClient's owner, or in the web console's
workbench, the person who is prompting.
:raises SmarterBudgetExceeded: if a budget's resource lock forbids charges to the provider,
the llmclient, the user, or their account.
"""
billed_user_profile = self.billed_user_profile
resources = [
getattr(self, "provider", None),
getattr(self.prompt, "llmclient", None),
billed_user_profile,
getattr(billed_user_profile, "account", None),
]
charge_authorization(
[resource.record_locator for resource in resources if resource is not None], self.__class__.__name__
)
[docs]
def first_message_cache_key(self) -> Optional[PromptCacheKey]:
"""
Return the cache key of the prompt, if its answer may be cached.
Only the first message of a conversation is cached, because the answers to later
messages depend on the conversation. See
:mod:`~smarter.apps.provider.services.text_completion.lib.prompt_cache`.
:returns: The key, or None if the prompt is not the conversation's first message,
or the cache is disabled.
"""
if not smarter_settings.subsystem_cache_prompt_response_expiration:
return None
llmclient = getattr(self.prompt, "llmclient", None)
if llmclient is None or not self.input_text or not isinstance(self.messages, list):
return None
user_messages = [
message
for message in self.messages
if isinstance(message, dict)
and message.get(OpenAIMessageKeys.MESSAGE_ROLE_KEY) == OpenAIMessageKeys.USER_MESSAGE_KEY
]
if len(user_messages) != 1:
return None
if not isinstance(self.prompt, Prompt) or not claim_first_message(self.prompt.pk):
# a later message, sent before the conversation's history was saved.
return None
return PromptCacheKey(
llmclient_id=llmclient.pk,
llmclient_updated_at=llmclient.updated_at.isoformat() if llmclient.updated_at else "",
provider=str(self.provider_name or ""),
model=str(self.model or ""),
temperature=float(self.temperature or 0),
max_completion_tokens=int(self.max_completion_tokens or 0),
message=message_digest(self.input_text),
)
[docs]
def handle_prompt_cache_lookup(self) -> None:
"""
Answer the first message of a conversation from the cache, if its answer is cached.
Otherwise, remember the prompt's cache key, so that :meth:`handle_prompt_cache_store`
can cache its answer.
:raises PromptCacheHit: If the answer is cached.
"""
self.prompt_cache_key = self.first_message_cache_key()
self.prompt_cacheable = self.prompt_cache_key is not None
if self.prompt_cache_key is None:
return
cached = get_cached_prompt_response(self.prompt_cache_key)
if cached is not None:
raise PromptCacheHit(cached)
[docs]
def handle_prompt_cache_store(self, response: Optional[ChatCompletion]) -> None:
"""
Cache the answer to the first message of a conversation, if everything that it used can be cached.
The answer is not cached if a tool call made the prompt uncacheable (see
:meth:`tool_call_is_cacheable`), or if the LLM did not finish its answer.
:param response: The LLM's final answer, after the output guardrails.
"""
if not self.prompt_cacheable or self.prompt_cache_key is None or response is None:
return
if not response.choices or response.choices[0].finish_reason != "stop":
return
cache_prompt_response(self.prompt_cache_key, response)
[docs]
def handle_plugin_selected(self, plugin: PluginBase) -> None:
"""
Handle a plugin being selected.
does the prompt have anything to do with any of the search terms defined in a plugin?
The LLMClient's model, temperature and max_completion_tokens are used whichever plugins
are selected: a plugin customizes the prompt's messages and tools, not the LLM settings.
2025-10-02: updated to validate that messages and tools are lists.
2025-10-02: updated to use plugin.plugin_meta.name for the plugin name.
:param plugin: The plugin instance that was selected.
:type plugin: PluginBase
:returns: None
:rtype: None
"""
logger.debug("called.")
if not isinstance(self.messages, list):
raise SmarterValueError(f"{self.formatted_class_name}: messages must be a list, got {type(self.messages)}")
if not isinstance(plugin.plugin_prompt, PluginPrompt):
raise SmarterValueError(
f"{self.formatted_class_name}: plugin_prompt must be an instance of PluginPrompt, got {type(plugin.plugin_prompt)}"
)
self.messages = plugin.customize_prompt(self.messages)
if self.tools is None:
self.tools = []
self.tools.append(plugin.custom_tool)
self.available_functions[plugin.function_calling_identifier] = plugin.tool_call_fetch_plugin_response
if plugin.plugin_meta is None:
raise SmarterValueError(f"{self.formatted_class_name}: plugin_meta is required, but was not set.")
self.append_message_plugin_selected(plugin=plugin.plugin_meta.name)
llm_tool_presented.send(sender=self.handle_plugin_selected, tool=plugin.custom_tool, plugin=plugin)
# note to self: Plugin sends a plugin_selected signal, so no need to send it here.
[docs]
def append_guardrail_message(self, stage: str, result: PipelineResult) -> None:
"""
Append a Smarter message that summarizes what the guardrails of a stage did, if anything.
Nothing is appended when no guardrail triggered and none failed to run.
:param stage: The guardrail stage, e.g. ``input`` or ``output``, used in the message text.
:param result: The pipeline result whose disposition, triggered findings and failed
outcomes are summarized.
"""
triggered = [finding.guardrail_name for finding in result.triggered_findings]
failed = [outcome.guardrail_name for outcome in result.outcomes if outcome.error]
if not triggered and not failed:
return
content = f"Smarter {stage} guardrails: {result.disposition.value}."
if triggered:
content += f" Triggered: {', '.join(sorted(set(triggered)))}."
if failed:
content += f" Failed to run: {', '.join(sorted(set(failed)))}."
self.append_message(role=OpenAIMessageKeys.SMARTER_MESSAGE_KEY, content=content)
[docs]
def handle_output_guardrails(self, response: ChatCompletion) -> ChatCompletion:
"""
Run the LLMClient's output guardrails on the LLM's final reply.
:param response: The LLM's final response.
:returns: The response, with its reply redacted or transformed, or replaced with the
guardrail's message if a guardrail blocks it.
"""
if self.guardrail_pipeline is None or not self.guardrail_pipeline.guardrails_for(GuardrailStage.POST):
return response
payload = json.loads(response.model_dump_json())
result = self.guardrail_pipeline.run_post(payload)
self.append_guardrail_message("output", result)
if result.blocked:
payload["choices"] = payload["choices"][:1]
message = payload["choices"][0]["message"]
message.update({"content": result.fallback_message, "refusal": None, "tool_calls": None})
payload["choices"][0]["finish_reason"] = "content_filter"
return ChatCompletion.model_validate(payload)
if result.disposition in (PipelineDisposition.REDACTED, PipelineDisposition.TRANSFORMED):
return ChatCompletion.model_validate(result.payload)
return response
[docs]
def handle_mcp_clients(self) -> None:
"""
Offer the LLM the tools of the LLMClient's MCP servers.
The LLMClient's active MCPClients, listed in its manifest's ``spec.mcpClients``, are
loaded into an :class:`~smarter.apps.mcpclient.toolkit.MCPToolkit`, whose tools are
added to the request, and whose servers' instructions are added to the system prompt.
An MCP server that cannot be reached is skipped, and reported in a Smarter message.
:returns: None
:rtype: None
"""
# pylint: disable=import-outside-toplevel
from smarter.apps.llmclient.models import LLMClientMCPClients
self.mcp_toolkit = None
llmclient = self.prompt.llmclient if isinstance(self.prompt, Prompt) else None
if llmclient is None:
return
mcpclients = LLMClientMCPClients.mcpclients_for(llmclient)
if not mcpclients:
return
logger.debug(
"loading MCPClients: %s",
[mcpclient.name for mcpclient in mcpclients],
)
self.mcp_toolkit = MCPToolkit(mcpclients).load()
if self.mcp_toolkit.tools:
if self.tools is None:
self.tools = []
if self.available_functions is None:
self.available_functions = {}
self.tools.extend(self.mcp_toolkit.tools)
for function_name in self.mcp_toolkit.functions:
self.available_functions[function_name] = self.mcp_toolkit.call
instructions = self.mcp_toolkit.system_prompt()
if instructions and isinstance(self.messages, list):
for i, message in enumerate(self.messages):
if message.get(OpenAIMessageKeys.MESSAGE_ROLE_KEY) == OpenAIMessageKeys.SYSTEM_MESSAGE_KEY:
content = message.get(OpenAIMessageKeys.MESSAGE_CONTENT_KEY) or ""
# the persisted thread keeps the system message that an earlier prompt
# extended, so its instructions are replaced, never added again.
content = content.split(MCP_INSTRUCTIONS_PREFIX, 1)[0].rstrip()
self.messages[i] = {
**message,
OpenAIMessageKeys.MESSAGE_CONTENT_KEY: (
f"{content}\n\n{instructions}" if content else instructions
),
}
break
else:
self.messages.insert(
0,
{
OpenAIMessageKeys.MESSAGE_ROLE_KEY: OpenAIMessageKeys.SYSTEM_MESSAGE_KEY,
OpenAIMessageKeys.MESSAGE_CONTENT_KEY: instructions,
},
)
if self.mcp_toolkit.connected:
names = ", ".join(mcpclient.name for mcpclient in self.mcp_toolkit.connected)
self.append_message(
role=OpenAIMessageKeys.SMARTER_MESSAGE_KEY,
content=f"Smarter added the tools of these MCP servers: {names}",
)
for name, error in self.mcp_toolkit.errors.items():
self.append_message(
role=OpenAIMessageKeys.SMARTER_ERROR_KEY,
content=f"Smarter could not use the {name} MCP server: {error}",
)
[docs]
def handle_extensions(self) -> None:
"""
Offer the LLM the tools of the LLMClient's extensions.
The LLMClient's extensions, listed in its manifest's ``spec.extensions``, are loaded
into an :class:`~smarter.apps.llmtool.extension.toolkit.ExtensionToolkit`, whose
tools are added to the request. An extension that is disabled, not available to the
LLMClient's account, or whose code does not load, is skipped, and reported in a
Smarter message.
:returns: None
:rtype: None
"""
# pylint: disable=import-outside-toplevel
from smarter.apps.llmclient.models import LLMClientExtensions
self.extension_toolkit = None
llmclient = self.prompt.llmclient if isinstance(self.prompt, Prompt) else None
if llmclient is None:
return
extensions = LLMClientExtensions.extensions_for(llmclient)
if not extensions:
return
logger.debug(
"loading extensions: %s",
[extension.slug for extension in extensions],
)
self.extension_toolkit = ExtensionToolkit(
extensions,
account=getattr(llmclient.user_profile, "account", None),
user_profile=self.user_profile if isinstance(self.user_profile, UserProfile) else None,
llmclient=llmclient,
).load()
if self.tools is None:
self.tools = []
if self.available_functions is None:
self.available_functions = {}
for tool in self.extension_toolkit.tools:
self.tools.append(tool)
self.available_functions[tool["function"]["name"]] = self.extension_toolkit.call
llm_tool_presented.send(sender=self.handle_extensions, tool=tool, plugin=None)
if self.extension_toolkit.loaded:
names = ", ".join(extension.slug for extension in self.extension_toolkit.loaded)
self.append_message(
role=OpenAIMessageKeys.SMARTER_MESSAGE_KEY,
content=f"Smarter added the tools of these extensions: {names}",
)
for slug, error in self.extension_toolkit.errors.items():
self.append_message(
role=OpenAIMessageKeys.SMARTER_ERROR_KEY,
content=f"Smarter could not use the {slug} extension: {error}",
)
[docs]
def handle_vectorsearches(self) -> None:
"""
Offer the LLM a search tool for each of the LLMClient's Vectorsearches.
The LLMClient's enabled Vectorsearches, listed in its manifest's ``spec.vectorsearches``, are
loaded into a :class:`~smarter.apps.vectorsearch.toolkit.VectorsearchToolkit`, whose tools,
one per Vectorsearch, are added to the request. The LLM calls one with a search query, and
answers from the passages that the search returns.
:returns: None
:rtype: None
"""
# pylint: disable=import-outside-toplevel
from smarter.apps.llmclient.models import LLMClientVectorsearches
self.vectorsearch_toolkit = None
llmclient = self.prompt.llmclient if isinstance(self.prompt, Prompt) else None
if llmclient is None:
return
vectorsearches = LLMClientVectorsearches.vectorsearches_for(llmclient)
if not vectorsearches:
return
logger.debug(
"loading vectorsearches: %s",
[vectorsearch.name for vectorsearch in vectorsearches],
)
self.vectorsearch_toolkit = VectorsearchToolkit(vectorsearches)
if self.tools is None:
self.tools = []
if self.available_functions is None:
self.available_functions = {}
for tool in self.vectorsearch_toolkit.tools:
self.tools.append(tool)
self.available_functions[tool["function"]["name"]] = self.vectorsearch_toolkit.call
llm_tool_presented.send(sender=self.handle_vectorsearches, tool=tool, plugin=None)
names = ", ".join(vectorsearch.name for vectorsearch in vectorsearches)
self.append_message(
role=OpenAIMessageKeys.SMARTER_MESSAGE_KEY,
content=f"Smarter added a search tool for these vectorsearches: {names}",
)
[docs]
def handle_completion(self) -> SmarterDictType:
"""
Handle prompt completion response.
This method
formats the final response to be returned to the client.
:returns: A dictionary representing the final prompt completion response.
:rtype: dict
"""
logger.debug("called")
if not isinstance(self.second_iteration, dict):
raise SmarterValueError(
f"{self.formatted_class_name}: second_iteration must be a dictionary, got {type(self.second_iteration)}"
)
response = self.second_iteration.get(_InternalKeys.RESPONSE_KEY) or self.first_iteration.get(
_InternalKeys.RESPONSE_KEY
)
if not isinstance(response, dict):
raise SmarterValueError(f"{self.formatted_class_name}: response must be a dictionary, got {type(response)}")
response["metadata"] = {"tool_calls": self.serialized_tool_calls, **self.request_meta_data}
smarter_message: SmarterDictType = {
"first_iteration": json.loads(json.dumps(self.first_iteration)),
"second_iteration": json.loads(json.dumps(self.second_iteration)),
_InternalKeys.PLUGINS_KEY: [plugin.name for plugin in self.plugins or []],
_InternalKeys.MESSAGES_KEY: self.new_messages,
}
if self.tools:
smarter_message[_InternalKeys.TOOLS_KEY] = [tool["function"]["name"] for tool in self.tools]
response[OpenAIMessageKeys.SMARTER_MESSAGE_KEY] = smarter_message
return response
[docs]
def create_completion(self, completions_kwargs: SmarterDictType, none_is_for_tools: bool = False) -> ChatCompletion:
"""
Send one request to v1/chat/completions, changed to what its model accepts.
Every request of a prompt goes through here. The rules that are known before the request
is sent are applied by :func:`~smarter.lib.openai.model_quirks.apply_model_quirks`. When
the model rejects the request anyway, what the rejection teaches is remembered, and the
request is sent again, at most :data:`MAX_REQUEST_ATTEMPTS` times in all:
- a rejected temperature is left out, and, when the request omitted reasoning_effort, the
model is added to :data:`DEFAULT_TEMPERATURE_ONLY_MODELS`.
- a rejected reasoning_effort value records the values that the model supports, from the
vendor's message, in :data:`SUPPORTED_REASONING_EFFORTS`, so that it is left out. The
request's own temperature is put back, since it may be accepted without the effort.
When the request is accepted, the smarter messages of sandbox mode warn about the
LLMClient's settings that it left out. See :meth:`warn_about_llmclient_settings`.
:param completions_kwargs: The keyword arguments of ``openai.chat.completions.create()``.
It is changed in place to what was sent.
:param none_is_for_tools: Whether the request's reasoning_effort 'none' is there so that the
model accepts its tools, as :meth:`retry_with_no_reasoning` sets it. If the model rejects
it, the request is not sent again: the model can't use tools, and the caller sends it
without them.
:returns: The LLM's response.
:rtype: ChatCompletion
:raises openai.APIStatusError: When the provider rejects the request for another reason,
e.g. its tools, which :meth:`create_first_completion` handles.
"""
requested_temperature = completions_kwargs.get(_InternalKeys.TEMPERATURE_KEY)
attempts = 0
while True:
attempts += 1
apply_model_quirks(completions_kwargs, self.model)
try:
response = openai.chat.completions.create(**completions_kwargs) # type: ignore[call-arg]
except openai.BadRequestError as e:
if attempts >= MAX_REQUEST_ATTEMPTS:
raise
learned = self.learn_from_rejection(e, completions_kwargs, requested_temperature, none_is_for_tools)
if not learned:
raise
continue
self.warn_about_llmclient_settings(completions_kwargs)
return response
[docs]
def learn_from_rejection(
self,
error: openai.BadRequestError,
completions_kwargs: SmarterDictType,
requested_temperature: Optional[float],
none_is_for_tools: bool = False,
) -> bool:
"""
Remember what a rejected request teaches about its model, and change the request to be sent again.
:param error: The vendor's rejection.
:param completions_kwargs: The rejected request, changed in place.
:param requested_temperature: The request's temperature before any was left out.
:param none_is_for_tools: Whether the request's reasoning_effort 'none' is there for its tools.
:returns: Whether the request may be sent again. False when the rejection is about something
else, or about the tools, which :meth:`create_first_completion` handles.
:rtype: bool
"""
model = str(self.model)
parameter = rejected_parameter(error)
sends_temperature = _InternalKeys.TEMPERATURE_KEY in completions_kwargs
if parameter == _InternalKeys.TEMPERATURE_KEY and sends_temperature:
base_logger.warning(
"model %s rejected temperature=%s. Retrying with its default temperature.",
model,
completions_kwargs[_InternalKeys.TEMPERATURE_KEY],
)
if _InternalKeys.REASONING_EFFORT_KEY not in completions_kwargs:
DEFAULT_TEMPERATURE_ONLY_MODELS.add(model)
completions_kwargs.pop(_InternalKeys.TEMPERATURE_KEY)
return True
if parameter != _InternalKeys.REASONING_EFFORT_KEY:
return False
reasoning_effort = completions_kwargs.get(_InternalKeys.REASONING_EFFORT_KEY)
if reasoning_effort is None:
return False
supported = supported_reasoning_efforts(error)
if supported is None:
return False
base_logger.warning(
"model %s rejected reasoning_effort=%s. It supports: %s.",
model,
reasoning_effort,
supported,
)
SUPPORTED_REASONING_EFFORTS[model] = supported
if reasoning_effort == REASONING_EFFORT_NONE and none_is_for_tools:
# the model can't use tools here: create_first_completion() sends it without them.
return False
if requested_temperature is not None:
completions_kwargs[_InternalKeys.TEMPERATURE_KEY] = requested_temperature
return True
[docs]
def create_first_completion(self, completions_kwargs: SmarterDictType) -> ChatCompletion:
"""
Send a request that offers the LLM its tools: the first, and the later rounds of tool calls.
Some reasoning models reject function tools on v1/chat/completions unless reasoning_effort
is 'none'. Requests with tools set reasoning_effort to 'none' for the models in
:data:`TOOLS_REQUIRE_NO_REASONING_MODELS`, and, when the LLMClient sets another effort, for
the models in :data:`TOOLS_REJECT_REASONING_EFFORT_MODELS`. If another model rejects the
request's tools at its effort, it is retried with reasoning_effort 'none', and the model is
added to one of these sets when the retry succeeds.
Other models can't use function tools on v1/chat/completions at all: reasoning models that
don't support 'none', e.g. gpt-6.1-sol, and the search models. Requests to the models in
:data:`TOOLS_UNSUPPORTED_MODELS` are sent without their tools, so that the LLM still
answers, and a smarter message names the tools that were left out. A model that rejects
'none' with tools, or rejects tools altogether, is added to that set and the request is
sent once more without its tools, at the LLMClient's own reasoning effort.
Each request is sent with :meth:`create_completion`.
:param completions_kwargs: The keyword arguments of ``openai.chat.completions.create()``.
:returns: The LLM's response.
:rtype: ChatCompletion
:raises openai.APIStatusError: When the provider rejects the request for another reason.
"""
offered_tools = completions_kwargs.get(_InternalKeys.TOOLS_KEY) or []
# a preview: create_completion() applies the quirks itself, once it has kept the request's temperature.
preview = apply_model_quirks(dict(completions_kwargs), self.model)
sends_tools = bool(preview.get(_InternalKeys.TOOLS_KEY))
if offered_tools and not sends_tools:
self.append_message_tools_unsupported(offered_tools)
return self.create_completion(completions_kwargs)
try:
return self.create_completion(completions_kwargs)
except (openai.BadRequestError, openai.NotFoundError) as e:
if not sends_tools:
raise
parameter = rejected_parameter(e)
if parameter == _InternalKeys.TOOLS_KEY:
return self.retry_without_tools(completions_kwargs, offered_tools)
if parameter != _InternalKeys.REASONING_EFFORT_KEY:
raise
reasoning_effort = completions_kwargs.get(_InternalKeys.REASONING_EFFORT_KEY)
if reasoning_effort == REASONING_EFFORT_NONE:
return self.retry_without_tools(completions_kwargs, offered_tools)
if not rejects_tools_at_reasoning_effort(e):
raise
return self.retry_with_no_reasoning(completions_kwargs, offered_tools, reasoning_effort)
[docs]
def retry_with_no_reasoning(
self,
completions_kwargs: SmarterDictType,
offered_tools: list[SmarterDictType],
rejected_effort: Optional[str],
) -> ChatCompletion:
"""
Send a request with tools again, with reasoning_effort 'none', after the model rejected its tools at another effort.
When the retry succeeds, the model is added to :data:`TOOLS_REQUIRE_NO_REASONING_MODELS`
if it rejected its tools at its default effort, or to
:data:`TOOLS_REJECT_REASONING_EFFORT_MODELS` if at the LLMClient's. When the model doesn't
support 'none', the request is sent without its tools, by :meth:`retry_without_tools`.
:param completions_kwargs: The rejected request. reasoning_effort is set in it.
:param offered_tools: The request's tools.
:param rejected_effort: The reasoning_effort that the model rejected tools at, or None for its default.
:returns: The LLM's response.
:rtype: ChatCompletion
:raises openai.BadRequestError: When the provider rejects the retry for another reason.
"""
model = str(self.model)
supported = SUPPORTED_REASONING_EFFORTS.get(model)
if supported is not None and REASONING_EFFORT_NONE not in supported:
return self.retry_without_tools(completions_kwargs, offered_tools)
base_logger.warning(
"model %s rejected function tools at reasoning_effort=%s. Retrying with reasoning_effort='%s'.",
model,
rejected_effort,
REASONING_EFFORT_NONE,
)
completions_kwargs[_InternalKeys.REASONING_EFFORT_KEY] = REASONING_EFFORT_NONE
try:
response = self.create_completion(completions_kwargs, none_is_for_tools=True)
except openai.BadRequestError as e:
if rejected_parameter(e) != _InternalKeys.REASONING_EFFORT_KEY:
raise
return self.retry_without_tools(completions_kwargs, offered_tools)
if rejected_effort is None:
TOOLS_REQUIRE_NO_REASONING_MODELS.add(model)
else:
TOOLS_REJECT_REASONING_EFFORT_MODELS.add(model)
return response
[docs]
def llmclient_settings(self) -> tuple[Optional[float], Optional[str]]:
"""
The temperature and reasoning effort that the prompt's LLMClient sets in its manifest, if any.
:returns: ``(defaultTemperature, defaultReasoningEffort)``, each None when the LLMClient
leaves it to the defaults, or when there is no LLMClient.
:rtype: tuple[Optional[float], Optional[str]]
"""
prompt = getattr(self, "prompt", None)
llmclient = getattr(prompt, "llmclient", None)
temperature = getattr(llmclient, "default_temperature", None)
if not isinstance(temperature, (int, float)):
temperature = None
reasoning_effort = getattr(llmclient, "default_reasoning_effort", None)
if not isinstance(reasoning_effort, str):
reasoning_effort = None
if not reasoning_effort:
reasoning_effort = None
return temperature, reasoning_effort
[docs]
def warn_about_llmclient_settings(self, sent_kwargs: SmarterDictType) -> None:
"""
Warn, in sandbox mode, about the LLMClient's settings that an accepted request left out or changed.
:param sent_kwargs: The request that the model accepted.
:returns: None
:rtype: None
"""
temperature, reasoning_effort = self.llmclient_settings()
sent_effort = sent_kwargs.get(_InternalKeys.REASONING_EFFORT_KEY)
sent_temperature = _InternalKeys.TEMPERATURE_KEY in sent_kwargs
if temperature is not None and not sent_temperature:
if self.temperature_was_used(temperature):
logger.debug(
"model %s ran at its default temperature %s, the LLMClient's",
self.model,
temperature,
)
else:
self.append_message_temperature_unsupported(temperature, sent_effort)
if reasoning_effort is None:
return
if sent_effort == reasoning_effort:
return
has_tools = bool(sent_kwargs.get(_InternalKeys.TOOLS_KEY))
if sent_effort == REASONING_EFFORT_NONE and has_tools:
self.append_message_reasoning_effort_for_tools(reasoning_effort)
return
self.append_message_reasoning_effort_unsupported(reasoning_effort)
[docs]
def temperature_was_used(self, temperature: float) -> bool:
"""
Whether a request without temperature still ran at the LLMClient's defaultTemperature.
A model that accepts only its default temperature runs at that default when the request omits
temperature. If the LLMClient asked for the default, nothing was ignored. A model that rejects
every temperature, e.g. a search model, didn't use it.
:param temperature: The LLMClient's temperature.
:returns: True if the model's default temperature is the LLMClient's.
:rtype: bool
"""
if str(self.model) in TEMPERATURE_REJECTED_MODELS:
return False
is_default = temperature == REASONING_MODEL_DEFAULT_TEMPERATURE
return is_default
[docs]
def append_message_temperature_unsupported(self, temperature: float, sent_effort: Optional[str]) -> None:
"""
Append a smarter message that says the model ignored the LLMClient's defaultTemperature, which it doesn't accept.
:param temperature: The LLMClient's temperature.
:param sent_effort: The reasoning_effort of the accepted request, if any.
:returns: None
:rtype: None
"""
if sent_effort is not None and sent_effort != REASONING_EFFORT_NONE:
content = (
f"Warning: model {self.model} accepts only its default temperature while it reasons, so it "
f"ignored spec.config.prompt.defaultTemperature: {temperature} at reasoning effort {sent_effort}. "
f"To use this temperature, set defaultReasoningEffort: {REASONING_EFFORT_NONE}, if the model "
"supports it. Otherwise remove defaultTemperature."
)
self.append_model_warning(content)
return
supported = SUPPORTED_REASONING_EFFORTS.get(str(self.model)) or ()
content = (
f"Warning: model {self.model} doesn't accept spec.config.prompt.defaultTemperature: {temperature}, "
f"so it used its default temperature. Remove defaultTemperature, or set it to the default of "
f"reasoning models, defaultTemperature: {REASONING_MODEL_DEFAULT_TEMPERATURE}."
)
if REASONING_EFFORT_NONE in supported:
content = (
content + f" This model accepts other temperatures without reasoning: to use {temperature}, set "
f"defaultReasoningEffort: {REASONING_EFFORT_NONE}."
)
self.append_model_warning(content)
[docs]
def append_message_reasoning_effort_unsupported(self, reasoning_effort: str) -> None:
"""
Append a smarter message that says the model doesn't support the LLMClient's defaultReasoningEffort.
:param reasoning_effort: The LLMClient's reasoning effort.
:returns: None
:rtype: None
"""
supported = SUPPORTED_REASONING_EFFORTS.get(str(self.model))
if not supported:
content = (
f"Warning: model {self.model} doesn't reason, so it ignored "
f"spec.config.prompt.defaultReasoningEffort: {reasoning_effort}. Remove defaultReasoningEffort, "
f"or choose a reasoning model, e.g. defaultModel: {TOOLS_WITH_REASONING_MODEL_SUGGESTION}."
)
self.append_model_warning(content)
return
suggestion = closest_reasoning_effort(reasoning_effort, supported)
listed = ", ".join(supported)
content = (
f"Warning: model {self.model} doesn't support spec.config.prompt.defaultReasoningEffort: "
f"{reasoning_effort}, so it reasoned at its default effort. It supports {listed}: e.g. set "
f"defaultReasoningEffort: {suggestion}."
)
self.append_model_warning(content)
[docs]
def append_model_warning(self, content: str) -> None:
"""
Append a smarter message that warns that the LLMClient's settings don't suit its model, once per prompt.
Smarter Chat displays smarter messages in sandbox mode only, so the prompt engineer sees the
warning and the LLMClient's users don't. A prompt's later requests, e.g. after tool calls,
don't repeat it.
:param content: The warning.
:returns: None
:rtype: None
"""
warnings = getattr(self, "model_warnings", None)
if warnings is None:
warnings = set()
self.model_warnings = warnings
if content in warnings:
return
warnings.add(content)
base_logger.warning(
"%s",
content,
)
self.append_message(role=OpenAIMessageKeys.SMARTER_MESSAGE_KEY, content=content)
[docs]
def handler(
self,
user_profile: UserProfile,
prompt: Prompt,
data: Union[SmarterDictType, list],
plugins: Optional[list[PluginBase]] = None,
prompting_user_profile: Optional[UserProfile] = None,
) -> SmarterChatCompletionResponseType:
"""
Process a prompt prompt request and invoke the appropriate OpenAI-compatible API endpoint.
This method orchestrates the entire prompt completion workflow, including:
- Validating input and internal state.
- Initializing or updating the message thread.
- Answering the first message of a conversation from the cache, when its answer is cached,
and caching it otherwise. See
:mod:`~smarter.apps.provider.services.text_completion.lib.prompt_cache`.
- Selecting and configuring the tools of the LLMClient's plugins, MCPClients and extensions.
- Preparing and sending requests to the OpenAI API (or compatible provider).
- Handling tool calls and plugin responses.
- Managing billing, logging, and signal dispatch.
- Returning a formatted HTTP response with the LLM's output and relevant metadata.
:param user_profile: The LLMClient owner's profile, whose provider, plugins and secrets the
prompt runs with. The session's own profile, ``prompt.user_profile``, replaces it.
:type user_profile: UserProfile
:param prompt: The prompt session instance associated with this request.
:type prompt: Prompt
:param data: The request payload, typically containing a session key and a list of message dictionaries.
Only the latest user message is used: the conversation's history is the session's stored
history, or for a new session, the LLMClient's system role and introduction. See
:meth:`get_message_thread`.
:type data: Union[SmarterDictType, list]
Example::
{
'session_key': '6f3bdd1981e0cac2de5fdc7afc2fb4e565826473a124153220e9f6bf49bca67b',
'messages': [
{'role': 'system', 'content': "You are a helpful assistant."},
{'role': 'assistant', 'content': "Welcome to Smarter! ..."},
{'role': 'smarter', 'content': "Tool call: smarter_plugin_0002({\"inquiry_type\":\"about\"})"},
{'role': 'user_profile', 'content': 'Hello, World!'}
]
}
:param plugins: A list of plugin instances to be considered for selection and presentation to the LLM.
:type plugins: Optional[list[PluginBase]]
:param prompting_user_profile: The profile of the person who prompts from the web console's
workbench, who is charged for it and whose budgets it must respect. None for any other
prompt, which is charged to the LLMClient's owner. See :attr:`billed_user_profile`.
:type prompting_user_profile: Optional[UserProfile]
:returns: An HTTP response dictionary (or list) containing the LLM's output, tool call results, and metadata.
:rtype: SmarterChatCompletionResponseType
:raises SmarterValueError: If required parameters are missing or invalid.
:raises SmarterConfigurationError: If there are configuration issues with the provider or plugins.
:raises SmarterIlligalInvocationError: If the method is invoked in an invalid state.
.. note::
This method manages both the initial and any required follow-up LLM requests (e.g., for tool calls).
It also handles plugin selection logic and ensures that all required signals and billing events are triggered.
.. seealso::
:class:`_InternalKeys`
:class:`OpenAIMessageKeys`
:class:`PluginBase`
:class:`ChatCompletion`
:class:`ChatCompletionMessageToolCall`
Example usage::
response = provider.handler(
prompt=chat_instance,
data=request_data,
plugins=[plugin1, plugin2],
user_profile=current_user
)
"""
plugins_list = [plugin.name for plugin in plugins] if plugins else []
logger.debug(
"called with user_profile=%s, prompt=%s, plugins=%s",
user_profile,
prompt,
plugins_list,
)
self._chat = prompt
self.user_profile = user_profile
if prompt and prompt.user_profile:
self._user_profile = prompt.user_profile
self._account = prompt.user_profile.account
self._user = prompt.user_profile.user
logger.debug(
"reinitialized user_profile from prompt: %s, user_profile: %s",
prompt,
self._user_profile,
)
# the owner pays, except for a prompt from the workbench, whose user pays.
self.prompting_user_profile = prompting_user_profile
self.data = data # type: ignore[assignment]
self.plugins = plugins
self.prompt_cache_key = None
self.prompt_cacheable = False
prompt_started.send(sender=self.handler, prompt=self.prompt, data=self.data)
# the status and the message of an error, e.g. a 400 from the LLM provider, if any.
error_status: Optional[int] = None
error_message: Optional[str] = None
self.iteration = 1
openai.api_key = self.api_key
openai.base_url = self.base_url
if not isinstance(self.prompt, Prompt):
raise SmarterValueError(
f"{self.formatted_class_name}: prompt must be an instance of Prompt, got {type(self.prompt)}"
)
try:
self.validate()
self.authorize_budgets()
self.model_warnings = set()
self.model = self.prompt.llmclient.default_model or self.default_model
self.temperature = self.prompt.llmclient.default_temperature or self.default_temperature
self.reasoning_effort = self.prompt.llmclient.default_reasoning_effort or None
self.max_completion_tokens = self.prompt.llmclient.default_max_tokens or self.default_max_tokens
if not self.data:
raise SmarterValueError(f"{self.formatted_class_name}: data is required")
self.input_text = self.get_input_text_prompt(data=self.data)
self.request_meta_data = self.request_meta_data_factory()
# initialize the message history from the persisted
# message history in the database, if it exists,
# and append the user_profile's message.
#
# using the persisted message history ensures that the prompt
# provider has a consistent view of the conversation history
# and that system and meta messages are preserved in their
# original form and order.
self.messages = self.db_message_history # type: ignore[assignment]
if self.messages:
self.append_message(role=OpenAIMessageKeys.USER_MESSAGE_KEY, content=self.input_text)
else:
# new thread with no history, so we initialize it with the
# llmclient's system role and introduction, and the client's
# latest user message. A system message, or earlier turns, that
# the client sent are dropped: the guardrails scan only the
# latest user message. See get_message_thread().
self.messages = self.get_message_thread(data=self.data)
# run the llmclient's input guardrails on the user's message. A block raises
# GuardrailBlockedError, which is answered with the guardrail's message below.
self.handle_input_guardrails()
# the answer to the first message of a conversation may be cached. A hit raises
# PromptCacheHit, which is answered with the cached answer below.
self.handle_prompt_cache_lookup()
# add plugins to the prompt if any are selected
if self.plugins:
for plugin in self.plugins:
if plugin.selected(user=self.user_profile.user, input_text=self.input_text, messages=self.messages):
self.handle_plugin_selected(plugin=plugin)
# add the tools and instructions of the llmclient's MCP servers
self.handle_mcp_clients()
# add the tools of the llmclient's extensions
self.handle_extensions()
# add a search tool for each of the llmclient's vectorsearches
self.handle_vectorsearches()
self.prep_first_request()
completions_kwargs = {
_InternalKeys.MODEL_KEY: self.model,
_InternalKeys.MESSAGES_KEY: self.openai_messages,
_InternalKeys.TEMPERATURE_KEY: self.temperature,
_InternalKeys.MAX_COMPLETION_TOKENS_KEY: self.max_completion_tokens,
}
if self.reasoning_effort:
completions_kwargs[_InternalKeys.REASONING_EFFORT_KEY] = self.reasoning_effort
if self.tools:
# new rule: tool_choice should only be provided if there are
# actual tools included in the request, otherwise OpenAI's
# API returns a 400 error: 'Invalid value 'tool_choice'
# is only allowed when 'tools' are specified.'
completions_kwargs[_InternalKeys.TOOLS_KEY] = self.tools
completions_kwargs[_InternalKeys.TOOL_CHOICE] = OPENAI_TOOL_CHOICE
completions_kwargs = self.prune_empty_values(completions_kwargs)
logger.debug(
"openai.chat.completions.create() completions_kwargs: %s",
completions_kwargs,
)
first_response = self.create_first_completion(completions_kwargs)
if not isinstance(first_response, ChatCompletion):
raise SmarterValueError(
f"{self.formatted_class_name}: first_response must be a ChatCompletion, got {type(first_response)}"
)
if first_response.choices and first_response.choices[0].message.tool_calls is None:
# this is the final response, so the output guardrails run on it
first_response = self.handle_output_guardrails(first_response)
self.first_response = first_response
self.handle_response()
self.append_openai_response(first_response)
response_message = first_response.choices[0].message
if not isinstance(response_message, ChatCompletionMessage):
raise SmarterValueError(
f"{self.formatted_class_name}: response_message must be a ChatCompletionMessage, got {type(response_message)}"
)
if response_message.tool_calls is not None:
tool_calls: list[ChatCompletionMessageToolCallUnion] = response_message.tool_calls
logger.debug(
"%s tool calls detected, preparing second request",
len(tool_calls),
)
self.iteration = 2
self.serialized_tool_calls = []
tool_rounds = 1
while True:
for tool_call in tool_calls or []:
self.process_tool_call(tool_call)
self.prep_second_request()
if not isinstance(self.model, str):
raise SmarterConfigurationError(
f"{self.formatted_class_name}: model must be a string, got {type(self.model)}"
)
if not isinstance(self.openai_messages, list):
raise SmarterConfigurationError(
f"{self.formatted_class_name}: openai_messages must be a list, got {type(self.openai_messages)}"
)
if not isinstance(self.temperature, (float, int)):
raise SmarterConfigurationError(
f"{self.formatted_class_name}: temperature must be a float or int, got {type(self.temperature)}"
)
if not isinstance(self.max_completion_tokens, int):
raise SmarterConfigurationError(
f"{self.formatted_class_name}: max_completion_tokens must be an int, got {type(self.max_completion_tokens)}"
)
# the LLM may call more tools, e.g. an image search with the place that a
# forecast named, until smarter_settings.max_tool_rounds requests have offered them.
offer_tools = bool(self.tools) and tool_rounds < smarter_settings.max_tool_rounds
completions_kwargs = {
_InternalKeys.MODEL_KEY: self.model,
_InternalKeys.MESSAGES_KEY: self.openai_messages,
_InternalKeys.TEMPERATURE_KEY: self.temperature,
_InternalKeys.MAX_COMPLETION_TOKENS_KEY: self.max_completion_tokens,
}
reasoning_effort = getattr(self, "reasoning_effort", None)
if reasoning_effort:
completions_kwargs[_InternalKeys.REASONING_EFFORT_KEY] = reasoning_effort
if offer_tools:
completions_kwargs[_InternalKeys.TOOLS_KEY] = self.tools
completions_kwargs[_InternalKeys.TOOL_CHOICE] = OPENAI_TOOL_CHOICE
response = self.create_first_completion(completions_kwargs)
else:
response = self.create_completion(completions_kwargs)
if not isinstance(response, ChatCompletion):
raise SmarterValueError(
f"{self.formatted_class_name}: second_response must be a ChatCompletion, got {type(response)}"
)
self.second_response = response
message = response.choices[0].message if response.choices else None
if offer_tools and message is not None and message.tool_calls:
# another round: charge and record this response, then answer its tool calls.
self.handle_response()
self.append_openai_response(response)
tool_calls = message.tool_calls
tool_rounds += 1
self.iteration += 1
logger.debug(
"%s more tool calls in round %s",
len(tool_calls),
tool_rounds,
)
continue
response = self.handle_output_guardrails(response)
self.second_response = response
self.append_openai_response(response)
self.handle_response()
break
self.handle_prompt_cache_store(self.second_response if self.iteration >= 2 else self.first_response)
# the answer to the first message of the conversation is cached, so the LLM is not called
except PromptCacheHit as hit:
self.iteration = 1
self.first_response = hit.response
self.handle_response()
self.append_openai_response(self.first_response)
# an input guardrail blocked the user's message, so the LLM is not called
except GuardrailBlockedError as blocked:
created_time = int(time.time())
self.iteration = 1
self.first_response = ChatCompletion(
id="guardrail_blocked",
model=self.model or "unknown",
choices=[
Choice(
message=ChatCompletionMessage(
role=OpenAIMessageKeys.ASSISTANT_MESSAGE_KEY, content=blocked.message
),
finish_reason="content_filter",
index=0,
)
],
usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
system_fingerprint="guardrail_blocked_" + str(created_time),
created=created_time,
object="chat.completion",
)
self.handle_response()
self.append_openai_response(self.first_response)
# a budget forbids more charges, so the LLM is not called, and the person is told why.
except SmarterBudgetExceeded as exceeded:
created_time = int(time.time())
self.iteration = 1
self.first_response = ChatCompletion(
id="budget_exceeded",
model=self.model or "unknown",
choices=[
Choice(
message=ChatCompletionMessage(
role=OpenAIMessageKeys.ASSISTANT_MESSAGE_KEY, content=exceeded.message
),
finish_reason="stop",
index=0,
)
],
usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
system_fingerprint="budget_exceeded_" + str(created_time),
created=created_time,
object="chat.completion",
)
self.handle_response()
self.append_openai_response(self.first_response)
# handle anything that went wrong
# pylint: disable=broad-exception-caught
except Exception as e:
stack_trace = traceback.format_exc()
chat_response_failure.send(
sender=self.handler,
iteration=self.iteration,
prompt=self.prompt,
request_meta_data=self.request_meta_data,
exception=e,
first_iteration=self.first_iteration,
second_iteration=self.second_iteration,
messages=self.messages,
stack_trace=stack_trace,
)
error_status, error_message = exception_status_and_message(e)
created_time = int(time.time())
self.first_response = ChatCompletion(
id="error_response",
model=self.model or "unknown",
choices=[
Choice(
message=ChatCompletionMessage(
role=OpenAIMessageKeys.ASSISTANT_MESSAGE_KEY, content=error_message
),
finish_reason="stop",
index=0,
)
],
usage=CompletionUsage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
system_fingerprint="error_response_" + str(created_time),
created=created_time,
object="chat.completion",
)
self.handle_response()
self.append_openai_error_response(self.first_response, e)
# done! for better or worse. An error is kept in the message history, so that the
# prompt engineers workbench can display it, and is returned with its own status,
# e.g. the status of the LLM provider's error response, and its message.
completion = self.handle_completion()
prompt_finished.send(
sender=self.handler,
prompt=self.prompt,
request=self.first_iteration.get(_InternalKeys.REQUEST_KEY),
response=completion,
messages=self.messages,
)
if error_status is not None and error_status != HTTPStatus.OK.value:
retval = http_response_factory(
status=error_status,
body={"error": {"status": error_status, "message": error_message}, "response": completion},
)
else:
retval = http_response_factory(status=HTTPStatus.OK, body=completion)
if not isinstance(retval, dict):
raise SmarterValueError(
f"{self.formatted_class_name}: http_response_factory() should have returned a dictionary, but instead returned {type(retval)}"
)
return retval