# pylint: disable=W0613,C0115,R0913,W0718
"""
Verification functions for provider models in the Smarter app.
These functions are responsible for verifying various capabilities of provider models,
such as streaming, tools, text input, image input, audio input, fine-tuning, search, code interpreter,
text to image, text to audio, text to text, translation, and summarization.
Each verification function checks if the capability is already verified and valid.
If not, it performs a test to verify the capability and updates the verification status accordingly.
"""
import io
import wave
from typing import Callable, Optional
import openai
from openai import APIConnectionError, APIStatusError
from smarter.apps.provider.models import ProviderModel, ProviderModelVerificationTypes
from smarter.apps.provider.signals import (
model_verification_failure,
model_verification_success,
)
from smarter.apps.provider.utils import (
get_model_verification_for_type,
set_model_verification,
)
from smarter.common.exceptions import SmarterValueError
from smarter.lib import logging
from smarter.lib.django import waffle
from smarter.lib.django.waffle import SmarterWaffleSwitches
[docs]
def should_log(level):
"""Check if logging should be done based on the waffle switch."""
return waffle.switch_is_active(SmarterWaffleSwitches.PROVIDER_LOGGING) or waffle.switch_is_active(
SmarterWaffleSwitches.PLUGIN_LOGGING
)
logger = logging.getSmarterLogger(__name__, condition_func=should_log)
VERIFICATION_MAX_COMPLETION_TOKENS = 1024
"""
The completion budget of the checks that read the model's answer.
Reasoning models spend their budget on reasoning tokens first, and return no text at all when it
runs out, so a budget of a few tokens fails them.
"""
INCONCLUSIVE_STATUS_CODES = (401, 402, 408, 429)
"""Provider http status codes, besides 5xx, that describe the account or the provider rather than the model."""
BILLING_ERROR_MARKERS = ("credit balance", "billing", "insufficient_quota", "exceeded your current quota")
"""Text of a provider error that blames the account's credit or quota, whatever its status code."""
ACCOUNT_POLICY_ERROR_MARKERS = ("third_party_data_sharing_blocked",)
"""
Error codes of a provider error that blames a setting of the account, not the model, whatever its status code.
Together AI, for example, answers a 403 ``third_party_data_sharing_blocked`` for a model that it serves through
a third party until the organization enables third-party data sharing. The model works once the setting is on.
"""
[docs]
class ProviderModelVerificationInconclusive(Exception):
"""
Raised by a check when its provider's error says nothing about the model.
An invalid api key, an account without credit, a rate limit, a provider outage or a network error
makes every model of the provider fail, working or not. :func:`verify_provider_model` catches it,
and leaves the model's verifications and its ``is_active`` as they were.
"""
[docs]
def raise_if_inconclusive(error: Exception) -> None:
"""
Raise :class:`ProviderModelVerificationInconclusive` if ``error`` is about the account or the provider, not the model.
Anthropic, for example, reports an account without credit as a 400 ``invalid_request_error``,
so the error's text is checked as well as its status code.
:param error: The exception that a check's call to the provider raised.
:raises ProviderModelVerificationInconclusive: if the error does not show that the model fails the check.
"""
if isinstance(error, APIConnectionError):
raise ProviderModelVerificationInconclusive(str(error)) from error
if isinstance(error, APIStatusError):
message = str(error).lower()
if (
error.status_code in INCONCLUSIVE_STATUS_CODES
or error.status_code >= 500
or any(marker in message for marker in BILLING_ERROR_MARKERS)
or any(marker in message for marker in ACCOUNT_POLICY_ERROR_MARKERS)
):
raise ProviderModelVerificationInconclusive(str(error)) from error
[docs]
def log_check_failure(check: Callable, provider_model: ProviderModel, error: Exception) -> None:
"""
Log that one of a provider model's checks failed.
A provider's http error (an :class:`~openai.APIStatusError`, such as a 404 for a retired model) is an
expected answer, so it is logged with its message and without a traceback. Any other exception gets
the traceback, since it may be a bug in the check itself.
:param check: The check that failed, e.g. :func:`verify_model_text_input`.
:param provider_model: The model that failed the check.
:param error: The exception that the check's call to the provider raised.
"""
check_name = check.__name__ + "()"
if isinstance(error, APIStatusError):
logger.error("provider model %s failed %s. The provider said: %s", provider_model.name, check_name, error)
return
logger.error("error during %s for provider model %s", check_name, provider_model.name, exc_info=True)
[docs]
def provider_api_key(provider_model: ProviderModel) -> Optional[str]:
"""
Return the api key of a model's Provider, for a check's call to the provider.
:param provider_model: The model that is checked.
:returns: The decrypted api key, or None if its Secret has no value.
:raises SmarterValueError: if the Provider has no api key Secret, which the check's
``except`` handles as a failed check.
"""
api_key = provider_model.provider.api_key
if api_key is None:
raise SmarterValueError(f"Provider {provider_model.provider.name} has no api key.")
return api_key.get_secret(update_last_accessed=False)
[docs]
def content_part_text(part) -> str:
"""
Return the text of one part of a message's content, or an empty string if it is not a text part.
Some providers, e.g. Mistral, return a message's content as a list of typed parts, such as
``{"type": "thinking", ...}`` and ``{"type": "text", "text": "..."}``. The openai client
passes them on as dicts, or as objects with attributes.
:param part: One part of the content, a dict or an object.
:returns: The part's text, if its type is ``text``, and otherwise an empty string.
"""
if isinstance(part, dict):
part_type = part.get("type")
text = part.get("text")
else:
part_type = getattr(part, "type", None)
text = getattr(part, "text", None)
if part_type != "text":
return ""
if not isinstance(text, str):
return ""
return text
[docs]
def completion_text(response) -> str:
"""
Return the stripped text of a chat completion's first choice.
The content is usually a string. Some providers return a list of typed parts instead, whose
text parts are joined (see :func:`content_part_text`).
:param response: A chat completion.
:returns: The text, or an empty string when the message has none, as when a reasoning model runs out of tokens.
"""
content = response.choices[0].message.content
if content is None:
return ""
if isinstance(content, str):
return content.strip()
texts = []
for part in content:
texts.append(content_part_text(part))
text = "".join(texts)
return text.strip()
[docs]
def verify_model_streaming(provider_model: ProviderModel, **kwargs) -> bool:
"""Verify streaming capabilities of the provider model."""
success = False
logger.debug("for provider model: %s", provider_model)
provider_model_verification = get_model_verification_for_type(
provider_model=provider_model, verification_type=ProviderModelVerificationTypes.STREAMING
)
if provider_model_verification.is_valid:
return True
try:
openai.base_url = provider_model.provider.base_url
openai.api_key = provider_api_key(provider_model)
response = openai.chat.completions.create(
model=provider_model.name,
messages=[{"role": "user", "content": "Hello"}],
stream=True,
max_completion_tokens=10,
)
# Try to get the first chunk from the stream
first_chunk = next(iter(response), None)
success = first_chunk is not None
except Exception as e:
raise_if_inconclusive(e)
log_check_failure(verify_model_streaming, provider_model, e)
success = False
set_model_verification(provider_model_verification=provider_model_verification, is_successful=success)
return success
[docs]
def verify_model_text_input(provider_model: ProviderModel, **kwargs) -> bool:
"""Verify text input capabilities of the provider model."""
logger.debug("for provider model: %s", provider_model)
provider_model_verification = get_model_verification_for_type(
provider_model=provider_model, verification_type=ProviderModelVerificationTypes.TEXT_INPUT
)
if provider_model_verification.is_valid:
return True
try:
openai.base_url = provider_model.provider.base_url
openai.api_key = provider_api_key(provider_model)
openai.chat.completions.create(
model=provider_model.name,
messages=[{"role": "user", "content": "Hello"}],
max_completion_tokens=5,
)
success = True
except Exception as e:
raise_if_inconclusive(e)
log_check_failure(verify_model_text_input, provider_model, e)
success = False
set_model_verification(provider_model_verification=provider_model_verification, is_successful=success)
return success
[docs]
def verify_model_fine_tuning(provider_model: ProviderModel, **kwargs) -> bool:
"""Verify fine-tuning capabilities of the provider model."""
success = False
logger.debug("for provider model: %s", provider_model)
provider_model_verification = get_model_verification_for_type(
provider_model=provider_model, verification_type=ProviderModelVerificationTypes.FINE_TUNING
)
if provider_model_verification.is_valid:
return True
try:
openai.api_key = provider_api_key(provider_model)
openai.base_url = provider_model.provider.base_url
# Attempt to create a fine-tuning job with minimal dummy data
# This will likely fail due to missing training file, but if the model is unsupported,
# OpenAI will return a specific error about model support.
openai.fine_tuning.jobs.create(
model=provider_model.name, training_file="file-xxxxxxxxxxxxxxxxxxxxxxx" # Dummy file ID
)
success = True
except Exception as e:
raise_if_inconclusive(e)
log_check_failure(verify_model_fine_tuning, provider_model, e)
success = False
set_model_verification(provider_model_verification=provider_model_verification, is_successful=success)
return success
[docs]
def verify_model_search(provider_model: ProviderModel, **kwargs) -> bool:
"""
Verify search capabilities of the provider model.
DEPRECATED: OpenAI has deprecated the search endpoint.
"""
success = False
logger.debug("for provider model: %s", provider_model)
provider_model_verification = get_model_verification_for_type(
provider_model=provider_model, verification_type=ProviderModelVerificationTypes.SEARCH
)
set_model_verification(provider_model_verification=provider_model_verification, is_successful=success)
return success
[docs]
def verify_model_code_interpreter(provider_model: ProviderModel, **kwargs) -> bool:
"""Verify code interpreter capabilities of the provider model."""
success = False
logger.debug("for provider model: %s", provider_model)
provider_model_verification = get_model_verification_for_type(
provider_model=provider_model, verification_type=ProviderModelVerificationTypes.CODE_INTERPRETER
)
if provider_model_verification.is_valid:
return True
# List of known models that support code interpreter as of June-2025
code_interpreter_models = [
"gpt-4o",
"gpt-4-turbo",
]
success = provider_model.name in code_interpreter_models
set_model_verification(provider_model_verification=provider_model_verification, is_successful=success)
if not success:
logger.error(
"Provider model %s does not support code interpreter. Known supported models: %s",
provider_model.name,
code_interpreter_models,
)
return success
[docs]
def verify_model_text_to_image(provider_model: ProviderModel, **kwargs) -> bool:
"""Verify text to image capabilities of the provider model."""
success = False
logger.debug("for provider model: %s", provider_model)
provider_model_verification = get_model_verification_for_type(
provider_model=provider_model, verification_type=ProviderModelVerificationTypes.TEXT_TO_IMAGE
)
if provider_model_verification.is_valid:
return True
try:
openai.api_key = provider_api_key(provider_model)
openai.base_url = provider_model.provider.base_url
# Attempt to generate an image with a simple prompt
openai.images.generate(model=provider_model.name, prompt="A red apple on a table", n=1, size="256x256")
success = True
except Exception as e:
raise_if_inconclusive(e)
log_check_failure(verify_model_text_to_image, provider_model, e)
success = False
set_model_verification(provider_model_verification=provider_model_verification, is_successful=success)
return success
[docs]
def verify_model_text_to_audio(provider_model: ProviderModel, **kwargs) -> bool:
"""Verify text to audio capabilities of the provider model."""
success = False
logger.debug("for provider model: %s", provider_model)
provider_model_verification = get_model_verification_for_type(
provider_model=provider_model, verification_type=ProviderModelVerificationTypes.TEXT_TO_AUDIO
)
if provider_model_verification.is_valid:
return True
try:
openai.api_key = provider_api_key(provider_model)
openai.base_url = provider_model.provider.base_url
# Attempt to generate audio from text
openai.audio.speech.create(
model=provider_model.name, input="Hello, this is a test.", voice="alloy" # Use a default voice
)
success = True
except Exception as e:
raise_if_inconclusive(e)
log_check_failure(verify_model_text_to_audio, provider_model, e)
success = False
set_model_verification(provider_model_verification=provider_model_verification, is_successful=success)
return success
[docs]
def verify_model_text_to_text(provider_model: ProviderModel, **kwargs) -> bool:
"""Verify text to text capabilities of the provider model."""
success = False
logger.debug("for provider model: %s", provider_model)
provider_model_verification = get_model_verification_for_type(
provider_model=provider_model, verification_type=ProviderModelVerificationTypes.TEXT_TO_TEXT
)
if provider_model_verification.is_valid:
return True
success = verify_model_text_input(provider_model=provider_model)
set_model_verification(provider_model_verification=provider_model_verification, is_successful=success)
if not success:
logger.error(
"Provider model %s does not support text to text. Ensure it supports text input.",
provider_model.name,
)
return success
[docs]
def verify_model_translation(provider_model: ProviderModel, **kwargs) -> bool:
"""Verify translation capabilities of the provider model."""
success = False
logger.debug("for provider model: %s", provider_model)
provider_model_verification = get_model_verification_for_type(
provider_model=provider_model, verification_type=ProviderModelVerificationTypes.TRANSLATION
)
if provider_model_verification.is_valid:
return True
try:
openai.api_key = provider_api_key(provider_model)
openai.base_url = provider_model.provider.base_url
response = openai.chat.completions.create(
model=provider_model.name,
messages=[{"role": "user", "content": "Translate this to Spanish: Hello"}],
max_completion_tokens=VERIFICATION_MAX_COMPLETION_TOKENS,
)
content = completion_text(response).lower()
success = "hola" in content
if not success:
logger.error(
"provider model %s did not translate 'Hello' to Spanish. finish_reason: %s, response: %s",
provider_model.name,
response.choices[0].finish_reason,
content[:200],
)
except Exception as e:
raise_if_inconclusive(e)
log_check_failure(verify_model_translation, provider_model, e)
success = False
set_model_verification(provider_model_verification=provider_model_verification, is_successful=success)
return success
[docs]
def verify_model_summarization(provider_model: ProviderModel, **kwargs) -> bool:
"""Verify summarization capabilities of the provider model."""
success = False
logger.debug("for provider model: %s", provider_model)
provider_model_verification = get_model_verification_for_type(
provider_model=provider_model, verification_type=ProviderModelVerificationTypes.SUMMARIZATION
)
if provider_model_verification.is_valid:
return True
try:
openai.api_key = provider_api_key(provider_model)
openai.base_url = provider_model.provider.base_url
long_text = (
"OpenAI is an AI research and deployment company. "
"Our mission is to ensure that artificial general intelligence benefits all of humanity. "
"We are committed to ensuring that artificial general intelligence—AI systems that are generally smarter than humans—"
"benefits all of humanity. We will build safe and beneficial AGI, or help others achieve this goal."
)
response = openai.chat.completions.create(
model=provider_model.name,
messages=[{"role": "user", "content": f"Summarize this into 10 words or less: {long_text}"}],
max_completion_tokens=VERIFICATION_MAX_COMPLETION_TOKENS,
)
summary = completion_text(response)
success = 0 < len(summary.split()) <= 10
if not success:
logger.error(
"provider model %s did not summarize the text in 10 words or less. finish_reason: %s, response: %s",
provider_model.name,
response.choices[0].finish_reason,
summary[:200],
)
except Exception as e:
raise_if_inconclusive(e)
log_check_failure(verify_model_summarization, provider_model, e)
success = False
set_model_verification(provider_model_verification=provider_model_verification, is_successful=success)
return success
[docs]
def verify_provider_model(provider_model_id, **kwargs):
"""
Run every check that the provider model's ``supports_*`` fields call for, then activate or deactivate it.
A model that passes every check is activated, and one that fails any is deactivated. When a check's
provider error is about the account or the provider rather than the model (see :func:`raise_if_inconclusive`),
the run stops and the model is left as it was.
:param provider_model_id: The id of the :class:`~smarter.apps.provider.models.ProviderModel` to verify.
"""
try:
provider_model = ProviderModel.objects.get(id=provider_model_id)
except ProviderModel.DoesNotExist:
logger.error(
"Provider model with id %s does not exist",
provider_model_id,
)
return
if provider_model.provider.api_key is None:
# a built-in Provider is created without a key when its environment variable is not set. Its
# models cannot be verified, and must not be deactivated, until it has one: see initialize_providers.
logger.warning(
"skipped provider model %s: its provider %s has no API key.",
provider_model.name,
provider_model.provider.name,
)
return
# blackball method
success: bool = True
try:
if provider_model.supports_streaming:
success = success and verify_model_streaming(provider_model=provider_model)
if provider_model.supports_tools:
success = success and verify_model_tools(provider_model=provider_model)
if provider_model.supports_text_input:
success = success and verify_model_text_input(provider_model=provider_model)
if provider_model.supports_image_input:
success = success and verify_model_image_input(provider_model=provider_model)
if provider_model.supports_audio_input:
success = success and verify_model_audio_input(provider_model=provider_model)
if provider_model.supports_fine_tuning:
success = success and verify_model_fine_tuning(provider_model=provider_model)
if provider_model.supports_search:
success = success and verify_model_search(provider_model=provider_model)
if provider_model.supports_code_interpreter:
success = success and verify_model_code_interpreter(provider_model=provider_model)
if provider_model.supports_image_generation:
success = success and verify_model_text_to_image(provider_model=provider_model)
if provider_model.supports_audio_generation:
success = success and verify_model_text_to_audio(provider_model=provider_model)
if provider_model.supports_text_generation:
success = success and verify_model_text_to_text(provider_model=provider_model)
if provider_model.supports_translation:
success = success and verify_model_translation(provider_model=provider_model)
if provider_model.supports_summarization:
success = success and verify_model_summarization(provider_model=provider_model)
except ProviderModelVerificationInconclusive as e:
logger.warning(
"verification of provider model %s is inconclusive, so it remains %s. The provider said: %s",
provider_model.name,
"active" if provider_model.is_active else "inactive",
e,
)
return
if success:
provider_model.is_active = True
provider_model.save(update_fields=["is_active"])
model_verification_success.send(sender=ProviderModel, provider_model=provider_model)
else:
provider_model.is_active = False
provider_model.save(update_fields=["is_active"])
model_verification_failure.send(sender=ProviderModel, provider_model=provider_model)