OpenAI Compatible Chat Provider

Base class for prompt providers.

smarter.apps.provider.services.text_completion.lib.openai_compatible_chat_provider.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.

smarter.apps.provider.services.text_completion.lib.openai_compatible_chat_provider.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, ![description](https://...), 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 OpenAISmarterClient.openai_messages), and is never saved in the conversation’s history, nor displayed in the chat.

smarter.apps.provider.services.text_completion.lib.openai_compatible_chat_provider.MAX_HISTORY_CHARACTERS = 100000

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 cap_message_history().

smarter.apps.provider.services.text_completion.lib.openai_compatible_chat_provider.MAX_REQUEST_ATTEMPTS = 4

The most times that one request is sent while the vendor’s rejections teach Smarter what its model accepts.

class smarter.apps.provider.services.text_completion.lib.openai_compatible_chat_provider.OpenAISmarterClient(provider, provider_name, base_url, api_key, default_model, default_system_role='You are a helpful llmclient. When given the opportunity to utilize function calling, you should always do so. This will allow you to provide the best possible responses to the user. If you are unable to provide a response, you should prompt the user for more information. If you are still unable to provide a response, you should inform the user that you are unable to help them at this time.', default_temperature=1.0, default_max_tokens=2048, valid_chat_completion_models=None, **kwargs)[source]

Bases: 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:

class MyProvider(OpenAISmarterClient):
    pass

provider = MyProvider()
response = provider.handler(user_profile, prompt, data)
static add_markdown_system_prompt(messages)[source]

Tell the LLM that its responses may use Markdown.

See add_markdown_system_prompt().

Parameters:

messages (list[dict[str, Any]]) – The request’s messages.

Returns:

The request’s messages, with the Markdown instructions.

Return type:

list[dict[str, Any]]

append_guardrail_message(stage, result)[source]

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.

Parameters:
  • stage (str) – The guardrail stage, e.g. input or output, used in the message text.

  • result (PipelineResult) – The pipeline result whose disposition, triggered findings and failed outcomes are summarized.

Return type:

None

append_message_reasoning_effort_for_tools(reasoning_effort)[source]

Append a smarter message that says the requests that offer tools reasoned at ‘none’, not at the LLMClient’s effort.

Parameters:

reasoning_effort (str) – The LLMClient’s reasoning effort.

Returns:

None

Return type:

None

append_message_reasoning_effort_unsupported(reasoning_effort)[source]

Append a smarter message that says the model doesn’t support the LLMClient’s defaultReasoningEffort.

Parameters:

reasoning_effort (str) – The LLMClient’s reasoning effort.

Returns:

None

Return type:

None

append_message_temperature_unsupported(temperature, sent_effort)[source]

Append a smarter message that says the model ignored the LLMClient’s defaultTemperature, which it doesn’t accept.

Parameters:
  • temperature (float) – The LLMClient’s temperature.

  • sent_effort (str | None) – The reasoning_effort of the accepted request, if any.

Returns:

None

Return type:

None

append_message_tools_unsupported(offered_tools)[source]

Append a smarter message that says the model answered without the tools that it can’t use.

Parameters:

offered_tools (list[dict[str, Any]]) – The tools that the request left out.

Returns:

None

Return type:

None

append_model_warning(content)[source]

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.

Parameters:

content (str) – The warning.

Returns:

None

Return type:

None

append_openai_error_response(response, e=None)[source]

Append an error message to the internal message list based on the OpenAI response.

Parameters:

response (ChatCompletion) – The OpenAI prompt completion response containing the error.

Returns:

None

Return type:

None

append_openai_response(response)[source]

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.

Parameters:

response (ChatCompletion) – The OpenAI-compatible prompt completion response.

Returns:

None

Return type:

None

authorize_budgets()[source]

Check the budgets of everything that a prompt completion is charged to, before calling the LLM.

The user is 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.

Return type:

None

available_functions: dict[str, Any]
call_vectorsearch_tool(function_name, function_args, serialized_tool_call, extra_resource_locators)[source]

Run a Vectorsearch tool call, and record which Vectorsearch answered it.

Parameters:
  • function_name (str) – The function name that the LLM called, a Vectorsearch tool’s.

  • function_args (dict[str, Any]) – The function’s arguments, with the LLM’s query.

  • serialized_tool_call (dict[str, Any]) – The tool call’s record, to which the Vectorsearch is added.

  • extra_resource_locators (list[str]) – The resources that the tool call used, to which the Vectorsearch’s record locator is added.

Return type:

JsonValue

Returns:

The search’s results, or an error, for the LLM.

completion_tokens: int | None
create_completion(completions_kwargs, none_is_for_tools=False)[source]

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 apply_model_quirks(). When the model rejects the request anyway, what the rejection teaches is remembered, and the request is sent again, at most MAX_REQUEST_ATTEMPTS times in all:

  • a rejected temperature is left out, and, when the request omitted reasoning_effort, the model is added to DEFAULT_TEMPERATURE_ONLY_MODELS.

  • a rejected reasoning_effort value records the values that the model supports, from the vendor’s message, in 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 warn_about_llmclient_settings().

Parameters:
  • completions_kwargs (dict[str, Any]) – The keyword arguments of openai.chat.completions.create(). It is changed in place to what was sent.

  • none_is_for_tools (bool) – Whether the request’s reasoning_effort ‘none’ is there so that the model accepts its tools, as 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.

Return type:

ChatCompletion

Raises:

openai.APIStatusError – When the provider rejects the request for another reason, e.g. its tools, which create_first_completion() handles.

create_first_completion(completions_kwargs)[source]

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 TOOLS_REQUIRE_NO_REASONING_MODELS, and, when the LLMClient sets another effort, for the models in 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 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 create_completion().

Parameters:

completions_kwargs (dict[str, Any]) – The keyword arguments of openai.chat.completions.create().

Returns:

The LLM’s response.

Return type:

ChatCompletion

Raises:

openai.APIStatusError – When the provider rejects the request for another reason.

data: dict[str, Any] | None
extension_toolkit: ExtensionToolkit | None = None

The extension tools of the current prompt.

See handle_extensions().

first_iteration: dict[str, Any]
first_message_cache_key()[source]

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 prompt_cache.

Return type:

PromptCacheKey | None

Returns:

The key, or None if the prompt is not the conversation’s first message, or the cache is disabled.

first_response: ChatCompletion | None
functions: List[str] | None
guardrail_pipeline: GuardrailPipeline | None = None

The MCP tools of the current prompt.

See handle_mcp_clients().

handle_completion()[source]

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.

Return type:

dict[str, Any]

handle_extensions()[source]

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

Return type:

None

handle_input_guardrails()[source]

Run the LLMClient’s input guardrails on the user’s message.

The guardrails are those listed in the LLMClient manifest’s spec.guardrails. If they redact or transform the user’s message, the message is replaced, so that the LLM, the plugins and the persisted history see the changed message.

Raises:

GuardrailBlockedError – If a guardrail blocks the user’s message.

Return type:

None

handle_mcp_clients()[source]

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

Return type:

None

handle_output_guardrails(response)[source]

Run the LLMClient’s output guardrails on the LLM’s final reply.

Parameters:

response (ChatCompletion) – The LLM’s final response.

Return type:

ChatCompletion

Returns:

The response, with its reply redacted or transformed, or replaced with the guardrail’s message if a guardrail blocks it.

handle_plugin_called(plugin)[source]

Handle a plugin tool call.

example: SqlPlugin, ApiPlugin, StaticPlugin etc.

Parameters:

plugin (PluginBase) – The plugin instance that was called.

Returns:

None

Return type:

None

handle_plugin_selected(plugin)[source]

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.

Parameters:

plugin (PluginBase) – The plugin instance that was selected.

Returns:

None

Return type:

None

handle_prompt_cache_lookup()[source]

Answer the first message of a conversation from the cache, if its answer is cached.

Otherwise, remember the prompt’s cache key, so that handle_prompt_cache_store() can cache its answer.

Raises:

PromptCacheHit – If the answer is cached.

Return type:

None

handle_prompt_cache_store(response)[source]

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 tool_call_is_cacheable()), or if the LLM did not finish its answer.

Parameters:

response (ChatCompletion | None) – The LLM’s final answer, after the output guardrails.

Return type:

None

handle_response()[source]

Handle internal billing, and append messages to the response for prompt completion and the billing summary.

Returns:

None

Return type:

None

handle_tool_called(function_name, function_args, extra_resource_locators=None)[source]

Handle a tool call by a function, an MCP server or an extension.

example: ext_weather_get_weather()

Parameters:
  • function_name (str) – The name of the tool function called.

  • function_args (str) – The arguments passed to the tool function.

  • extra_resource_locators (list[str] | None) – The record locators of any other resources that the tool call used, e.g. an MCPClient, to include in the charge.

Returns:

None

Return type:

None

handle_vectorsearches()[source]

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

Return type:

None

handler(user_profile, prompt, data, plugins=None, prompting_user_profile=None)[source]

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 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.

Parameters:
  • user_profile (UserProfile) – The LLMClient owner’s profile, whose provider, plugins and secrets the prompt runs with. The session’s own profile, prompt.user_profile, replaces it.

  • prompt (Prompt) – The prompt session instance associated with this request.

  • 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 get_message_thread().

  • plugins (list[PluginBase] | None) – A list of plugin instances to be considered for selection and presentation to the LLM.

  • prompting_user_profile (UserProfile | None) – 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 billed_user_profile.

Returns:

An HTTP response dictionary (or list) containing the LLM’s output, tool call results, and metadata.

Return type:

dict[str, Any] | SmarterHttpResponseForbidden | SmarterHttpResponseNotFound | SmarterHttpResponseBadRequest | SmarterJournaledJsonErrorResponse | SmarterJournaledJsonResponse

Raises:
  • SmarterValueError – If required parameters are missing or invalid.

  • SmarterConfigurationError – If there are configuration issues with the provider or plugins.

  • 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.

See also

_InternalKeys OpenAIMessageKeys PluginBase ChatCompletion ChatCompletionMessageToolCall

Example usage:

response = provider.handler(
    prompt=chat_instance,
    data=request_data,
    plugins=[plugin1, plugin2],
    user_profile=current_user
)
input_text: str | None
iteration: int
learn_from_rejection(error, completions_kwargs, requested_temperature, none_is_for_tools=False)[source]

Remember what a rejected request teaches about its model, and change the request to be sent again.

Parameters:
  • error (BadRequestError) – The vendor’s rejection.

  • completions_kwargs (dict[str, Any]) – The rejected request, changed in place.

  • requested_temperature (float | None) – The request’s temperature before any was left out.

  • none_is_for_tools (bool) – 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 create_first_completion() handles.

Return type:

bool

llmclient_settings()[source]

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.

Return type:

tuple[float | None, str | None]

max_completion_tokens: int | None
mcp_toolkit: MCPToolkit | None = None

The MCP tools of the current prompt.

See handle_mcp_clients().

model: str | None
model_warnings: set[str]
property new_messages: list[dict[str, Any]]

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.

Return type:

list[SmarterDictType]

property openai_messages: list[dict[str, Any]]

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.

Return type:

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.

plugins: List[PluginBase] | None
prep_first_request()[source]

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

Return type:

None

prep_second_request()[source]

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

Return type:

None

process_tool_call(tool_call)[source]

Process a tool call from the LLM.

This method handles both built-in tool calls and plugin tool calls.

Parameters:

tool_call (ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall) – The tool call data from the LLM.

Returns:

None

Return type:

None

prompt_cache_key: PromptCacheKey | None = None

The cache key of the current prompt, if it is the first message of a conversation.

See 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.

prompt_tokens: int | None
static provider_error_text(error_object)[source]

The message of an LLM provider’s error object, e.g. {'error': {'message': '...'}}.

Parameters:

error_object (dict[str, Any]) – The error object that the provider returned.

Returns:

The error’s message, or None if it has none.

Return type:

str | None

provider_record_locator()[source]

Return the record locator of the Provider that a charge is billed to.

Returns:

The Provider’s record locator.

Return type:

str

Raises:

SmarterValueError – If the Provider is not set.

reasoning_effort: str | None
reference: str | None
request_meta_data: dict[str, Any]
request_meta_data_factory()[source]

Return a dictionary of request meta data.

This includes the model, temperature, max_completion_tokens, and input_text.

Returns:

A dictionary of request meta data.

Return type:

dict

retry_with_no_reasoning(completions_kwargs, offered_tools, rejected_effort)[source]

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 TOOLS_REQUIRE_NO_REASONING_MODELS if it rejected its tools at its default effort, or to 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 retry_without_tools().

Parameters:
  • completions_kwargs (dict[str, Any]) – The rejected request. reasoning_effort is set in it.

  • offered_tools (list[dict[str, Any]]) – The request’s tools.

  • rejected_effort (str | None) – The reasoning_effort that the model rejected tools at, or None for its default.

Returns:

The LLM’s response.

Return type:

ChatCompletion

Raises:

openai.BadRequestError – When the provider rejects the retry for another reason.

retry_without_tools(completions_kwargs, offered_tools)[source]

Send a request again without its tools, after the model rejected them with reasoning_effort ‘none’, or altogether.

Such a model can’t use function tools on v1/chat/completions at any reasoning effort. It is added to TOOLS_UNSUPPORTED_MODELS, so that later requests leave out their tools before they are sent, and a smarter message names the tools that were left out. The request is sent at the LLMClient’s own reasoning effort, if it sets one.

Parameters:
  • completions_kwargs (dict[str, Any]) – The rejected request. Its tools are removed from it.

  • offered_tools (list[dict[str, Any]]) – The request’s tools.

Returns:

The LLM’s response.

Return type:

ChatCompletion

Raises:

openai.BadRequestError – When the provider rejects the request without tools too.

second_iteration: dict[str, Any] | None
second_response: ChatCompletion | None
serialized_tool_calls: list[dict[str, Any]] | None
temperature: float | None
temperature_was_used(temperature)[source]

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.

Parameters:

temperature (float) – The LLMClient’s temperature.

Returns:

True if the model’s default temperature is the LLMClient’s.

Return type:

bool

tool_budget_refusal(function_name)[source]

Check the budget of the plugin or MCP server that a tool call would use.

Return type:

str | None

Returns:

The tool response that tells the LLM why the tool cannot be used, or None if it can.

tool_call_is_cacheable(function_name, function_response, plugin)[source]

Return whether a tool call leaves the prompt’s answer cacheable.

A call is cacheable if its own result is cached, or could be: a cacheable MCP tool or resource read (one that only reads, from anything but the staff-only endpoint of this platform’s MCPServer), an extension tool that sets cache_ttl, or a plugin, whose remote calls are cached, unless it is an ApiPlugin that sends anything but GET. A call that returned nothing, or an error by is_error_result(), such as a budget refusal, is not.

Parameters:
  • function_name (str) – The function that the LLM called.

  • function_response (object) – The function’s result.

  • plugin (PluginBase | None) – The plugin that answered the call, if any.

Return type:

bool

Returns:

True if the prompt’s answer may still be cached.

tool_call_label(tool_name)[source]

Return the label of the tool calls that one of the LLM’s tool calls makes, for the tool worker’s log.

Names and ids only: the chat session’s key is masked, since anyone who holds it can continue the conversation.

Parameters:

tool_name (str) – The tool’s name, as users know it (tool_display_name()).

Return type:

ToolCallLabel

Returns:

The label.

tool_display_name(function_name)[source]

Return the human-readable name of a tool call’s function, for progress messages.

A plugin’s function name is symbolic, e.g. smarter_plugin_0000000016, so its PluginMeta’s name is returned instead. An MCP function’s name is prefixed with its server’s number, so the MCP tool’s own name is returned instead, and likewise an extension tool’s name is returned without its ext_<slug>_ prefix, and a Vectorsearch tool’s Vectorsearch’s name instead of smarter_vectorsearch_<id>. Anything else, e.g. a plugin that can’t be found, is returned as is.

Parameters:

function_name (str) – The function name that the LLM called.

Returns:

The tool’s name, as users know it.

Return type:

str

tools: list[dict[str, Any]] | None
total_tokens: int | None
vectorsearch_toolkit: VectorsearchToolkit | None = None

The Vectorsearch tools of the current prompt.

See handle_vectorsearches().

warn_about_llmclient_settings(sent_kwargs)[source]

Warn, in sandbox mode, about the LLMClient’s settings that an accepted request left out or changed.

Parameters:

sent_kwargs (dict[str, Any]) – The request that the model accepted.

Returns:

None

Return type:

None

smarter.apps.provider.services.text_completion.lib.openai_compatible_chat_provider.add_markdown_system_prompt(messages)[source]

Tell the LLM that its responses may use Markdown.

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.

Parameters:

messages (list[dict[str, Any]]) – The request’s messages.

Returns:

The request’s messages, with the Markdown instructions.

Return type:

list[dict[str, Any]]

smarter.apps.provider.services.text_completion.lib.openai_compatible_chat_provider.provider_messages(messages)[source]

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 PromptProviderRequestView):

  • only the messages whose role is in OpenAIMessageKeys.all are kept, so the smarter and smarter_error messages are left out.

  • the smarter_is_new field is removed.

  • MARKDOWN_SYSTEM_PROMPT is added to the system prompt.

  • the oldest turns are left out of a long conversation (MAX_HISTORY_CHARACTERS).

  • every tool call is paired with its reply.

The messages are copies, so the conversation’s history is unchanged.

Parameters:

messages (list[dict[str, Any]]) – The conversation’s messages, as they are saved in its history.

Returns:

The request’s messages.

Return type:

list[dict[str, Any]]

smarter.apps.provider.services.text_completion.lib.openai_compatible_chat_provider.should_log(level)[source]

Check if logging should be done based on the waffle switch.