# pylint: disable=W0718,W0613
"""LLMClient api/v1/llmclients CRUD views."""
from http import HTTPStatus
from typing import Optional
from django.db.models import QuerySet
from django.http import (
HttpRequest,
HttpResponseNotFound,
HttpResponseRedirect,
JsonResponse,
)
from django.shortcuts import get_object_or_404
from rest_framework.exceptions import NotFound
from rest_framework.request import Request
from rest_framework.response import Response
from smarter.apps.llmclient.contract.models import (
LLMClientApiCustomDomain,
LLMClientApiExtension,
LLMClientApiKey,
LLMClientApiLLMClient,
LLMClientApiPlugin,
)
from smarter.apps.llmclient.models import (
LLMClient,
LLMClientAPIKey,
LLMClientCustomDomain,
LLMClientExtensions,
LLMClientPlugin,
)
from smarter.apps.llmclient.serializers import (
LLMClientAPIKeySerializer,
LLMClientCustomDomainSerializer,
LLMClientExtensionsSerializer,
LLMClientPluginSerializer,
LLMClientSerializer,
)
from smarter.apps.llmclient.tasks.deploy_custom_api import deploy_custom_api
from smarter.apps.llmtool.manifest.controller import SAMPluginControllerError
from smarter.lib import json, logging
from smarter.lib.django.http.client_errors import (
CLIENT_ERROR_TYPES,
REQUEST_DATA_ERROR_TYPES,
client_error_message,
)
from smarter.lib.django.waffle import SmarterWaffleSwitches
from smarter.lib.drf.models import SmarterAuthToken
from smarter.lib.drf.views.contract import ContractListMixin
from smarter.lib.drf.views.token_authentication_helpers import (
SmarterAdminAPIView,
SmarterAdminListAPIView,
)
from smarter.lib.typing import required
logger = logging.getSmarterLogger(__name__, any_switches=[SmarterWaffleSwitches.LLM_CLIENT_LOGGING])
###############################################################################
# base views
###############################################################################
[docs]
class ViewBase(SmarterAdminAPIView):
"""
Base class for all llmclient detail views.
Their GET responses are built from the models of :mod:`smarter.apps.llmclient.contract.models`,
which the Smarter api's OpenAPI document publishes.
"""
# SmarterRequestMixin sets user, user_profile and account from the request,
# which are immutable once set.
[docs]
class ListViewBase(ContractListMixin, SmarterAdminListAPIView):
"""
Base class for all llmclient list views.
A subclass sets ``contract_model``, the model of :mod:`smarter.apps.llmclient.contract.models`
that each row of its response is built with.
"""
# SmarterRequestMixin sets user, user_profile and account from the request,
# which are immutable once set.
###############################################################################
# LLMClient views
###############################################################################
[docs]
class LLMClientView(ViewBase):
"""LLMClient view for smarter api."""
serializer_class = LLMClientSerializer
llmclient: Optional[LLMClient] = None
hashed_id: Optional[str] = None
llmclient_id: Optional[int] = None
[docs]
def get_queryset(self, *args, **kwargs):
"""
Return a queryset of the view's LLMClient.
:returns: The LLMClient found by :meth:`initial`, as a one-row queryset.
"""
llmclient = required(self.llmclient, "llmclient")
return LLMClient.objects.filter(id=llmclient.id)
[docs]
def dispatch(self, request: HttpRequest, *args, **kwargs):
"""
Pop ``hashed_id`` from the url kwargs, then dispatch the request.
:param request: The request.
:returns: The response.
"""
self.hashed_id = kwargs.pop("hashed_id", None)
return super().dispatch(request, *args, **kwargs)
[docs]
def initial(self, request: Request, *args, **kwargs):
"""Find the LLMClient, after DRF has authenticated the request and before the handler runs."""
super().initial(request, *args, **kwargs)
if self.hashed_id:
self.llmclient_id = LLMClient.id_from_hashed_id(self.hashed_id)
if not self.llmclient_id:
raise NotFound(f"No LLMClient has the hashed id {self.hashed_id}.")
else:
self.llmclient_id = kwargs.get("llmclient_id")
if self.llmclient_id:
self.llmclient = get_object_or_404(LLMClient, pk=self.llmclient_id)
if self.llmclient.user_profile and self._user_profile != self.llmclient.user_profile:
self._user_profile = self.llmclient.user_profile
self._account = self.llmclient.user_profile.account
self._user = self.llmclient.user_profile.user
logger.debug(
"reinitializing user, account, and user_profile from llmclient.user_profile: %s",
self.llmclient.user_profile,
)
logger.debug("%s %s", self.llmclient, self.user_profile)
[docs]
def get(self, request: Request, llmclient_id: Optional[int] = None):
"""
Return the LLMClient as an :class:`~smarter.apps.llmclient.contract.models.LLMClientApiLLMClient`.
:param request: The request.
:param llmclient_id: The id of the LLMClient. Unused: :meth:`initial` has already found it.
:returns: The LLMClient's json.
:raises NotFound: when the url identifies no LLMClient.
"""
if not self.llmclient:
raise NotFound("LLMClient not found.")
return Response(
LLMClientApiLLMClient.from_model(self.llmclient, request.user).model_dump(mode="json"),
status=HTTPStatus.OK,
)
[docs]
def post(self, request: Request, *args, **kwargs):
"""
Create an LLMClient from the request's data, and redirect to its detail url.
:param request: The request, whose data are the LLMClient's field values.
:returns: A redirect to the new LLMClient, or a 400 response if it could not be created.
"""
try:
data = request.data
if not isinstance(data, dict):
raise TypeError(f"Expected a JSON dict in request body but received {type(data)}")
llmclient = LLMClient.objects.create(**data)
except REQUEST_DATA_ERROR_TYPES as e:
message = client_error_message(e, "The request data is not valid.")
return JsonResponse({"error": "Invalid request data", "exception": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while creating the LLMClient."},
status=HTTPStatus.INTERNAL_SERVER_ERROR,
)
return HttpResponseRedirect(request.path_info + str(llmclient.id) + "/") # type: ignore[return-value]
[docs]
def patch(self, request: Request, *args, llmclient_id: Optional[int] = None, **kwargs):
"""
Set the request's fields on the LLMClient, save it, and redirect to its detail url.
Keys that are not attributes of the LLMClient are ignored.
:param request: The request, whose data is a json dict of field values.
:param llmclient_id: The id of the LLMClient. Unused: :meth:`initial` has already found it.
:returns: A redirect to the LLMClient; 404 if there is none; 400 if the data is not a dict or
fails validation; 500 if the save fails.
"""
llmclient: Optional[LLMClient] = None
llmclient = self.llmclient
if not llmclient:
return HttpResponseNotFound("LLMClient not found")
# parsing the body, and saving its values, both handle the client's data.
try:
request_data = request.data
if not isinstance(request_data, dict):
return JsonResponse(
{
"error": f"Invalid request data. Expected a JSON dict in request body but received {type(request_data)}"
},
status=HTTPStatus.BAD_REQUEST,
)
for key, value in request_data.items():
if hasattr(llmclient, key):
setattr(llmclient, key, value)
llmclient.save()
except REQUEST_DATA_ERROR_TYPES as e:
message = client_error_message(e, "The request data is not valid.")
return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while updating the LLMClient."},
status=HTTPStatus.INTERNAL_SERVER_ERROR,
)
return HttpResponseRedirect(request.path_info)
[docs]
def delete(self, request: Request, *args, llmclient_id: Optional[int] = None, **kwargs):
"""
Delete the LLMClient, and redirect to the list url.
A superuser can delete any LLMClient by ``llmclient_id``; anyone else deletes the view's LLMClient.
:param request: The request.
:param llmclient_id: The id of the LLMClient.
:returns: A redirect to the list url, or a 500 response if the delete fails.
"""
llmclient: Optional[LLMClient]
if llmclient_id and self.is_superuser():
llmclient = get_object_or_404(LLMClient, pk=llmclient_id)
else:
llmclient = self.llmclient
try:
if llmclient:
llmclient.delete()
except CLIENT_ERROR_TYPES as e:
logger.warning("refused: %s", e)
message = client_error_message(e, "The resource could not be deleted.")
return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while deleting the LLMClient."},
status=HTTPStatus.INTERNAL_SERVER_ERROR,
)
plugins_path = request.path_info.rsplit("/", 2)[0]
return HttpResponseRedirect(plugins_path)
[docs]
class LLMClientListView(ListViewBase):
"""LLMClient list view for smarter api."""
serializer_class = LLMClientSerializer
llmclients: Optional[QuerySet[LLMClient]]
[docs]
def dispatch(self, request: HttpRequest, *args, **kwargs):
"""
Dispatch the request, then, if it succeeded, set ``llmclients`` to those the user can read.
:param request: The request.
:returns: The response.
"""
response = super().dispatch(request, *args, **kwargs)
if response.status_code > 299:
return response
self.llmclients = LLMClient.objects.with_read_permission_for(user=request.user) # type: ignore[assignment]
return response
[docs]
def get_queryset(self, *args, **kwargs):
"""
Return the LLMClients that the user has read permission for.
:returns: The LLMClients.
"""
return LLMClient.objects.with_read_permission_for(user=self.user) # type: ignore[return-value]
[docs]
def item(self, row):
"""An LLMClient of the response, whose ``canDelete`` is the requesting user's."""
return LLMClientApiLLMClient.from_model(row, self.request.user).model_dump(mode="json")
[docs]
class LLMClientDeployView(ViewBase):
"""LLMClient deployment view for smarter api."""
serializer_class = LLMClientSerializer
[docs]
def post(self, request: Request, llmclient_id: int):
"""
Mark the account's LLMClient deployed, and save it.
Saving it sends the LLMClient's signals, whose receivers deploy it.
:param request: The request.
:param llmclient_id: The id of the LLMClient.
:returns: An empty 200 response, or 400 if the save fails.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
try:
llmclient.deployed = True
llmclient.save()
except REQUEST_DATA_ERROR_TYPES as e:
message = client_error_message(e, "The request data is not valid.")
return JsonResponse({"error": "Invalid request data", "exception": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while deploying the LLMClient."},
status=HTTPStatus.INTERNAL_SERVER_ERROR,
)
return JsonResponse({}, status=HTTPStatus.OK)
###############################################################################
# LLMClientPlugin views
###############################################################################
[docs]
class LLMClientPluginView(ViewBase):
"""LLMClientPlugin view for smarter api."""
serializer_class = LLMClientPluginSerializer
[docs]
def get(self, request: Request, llmclient_id: int, plugin_id: int):
"""
Return a plugin of the account's LLMClient as an :class:`~smarter.apps.llmclient.contract.models.LLMClientApiPlugin`.
:param request: The request.
:param llmclient_id: The id of the LLMClient.
:param plugin_id: The id of the LLMClientPlugin.
:returns: The plugin's json, or 404 if the LLMClient or plugin is not found.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
plugin = get_object_or_404(LLMClientPlugin, pk=plugin_id, llmclient=llmclient)
return Response(
LLMClientApiPlugin.from_model(plugin, request.user).model_dump(mode="json"), status=HTTPStatus.OK
)
[docs]
def post(self, request: Request, llmclient_id: int):
"""
Add a plugin to the account's LLMClient, from the request's data, and redirect to it.
:param request: The request, whose data is passed to :meth:`LLMClientPlugin.load`.
:param llmclient_id: The id of the LLMClient.
:returns: A redirect to the new LLMClientPlugin, or a 400 response if it could not be loaded.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
try:
data = request.data
llmclient_plugin = LLMClientPlugin.load(llmclient, data)
except REQUEST_DATA_ERROR_TYPES + (SAMPluginControllerError,) as e:
message = client_error_message(e, "The request data is not valid.")
return JsonResponse({"error": "Invalid request data", "exception": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while creating the LLMClientPlugin."},
status=HTTPStatus.INTERNAL_SERVER_ERROR,
)
return HttpResponseRedirect(request.path_info + str(llmclient_plugin.id) + "/") # type: ignore[return-value]
[docs]
def patch(self, request: Request, llmclient_id: int, plugin_id: int):
"""
Reload a plugin of the account's LLMClient from the request's json body, and redirect to it.
:param request: The request, whose body is json.
:param llmclient_id: The id of the LLMClient.
:param plugin_id: The id of the LLMClientPlugin.
:returns: A redirect to the plugin, or a 400 response if the body is invalid.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
llmclient_plugin = get_object_or_404(LLMClientPlugin, pk=plugin_id, llmclient=llmclient)
try:
data = json.loads(request.body.decode("utf-8"))
llmclient_plugin.load(llmclient, data)
except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON data"}, status=HTTPStatus.BAD_REQUEST)
except REQUEST_DATA_ERROR_TYPES + (SAMPluginControllerError,) as e:
message = client_error_message(e, "The request data is not valid.")
return JsonResponse({"error": "Invalid request data", "exception": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while updating the LLMClientPlugin."},
status=HTTPStatus.INTERNAL_SERVER_ERROR,
)
return HttpResponseRedirect(request.path_info)
[docs]
def delete(self, request: Request, llmclient_id: int, plugin_id: int):
"""
Remove a plugin from the account's LLMClient, and redirect to the list url.
:param request: The request.
:param llmclient_id: The id of the LLMClient.
:param plugin_id: The id of the LLMClientPlugin.
:returns: A redirect to the list url, or a 500 response if the delete fails.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
llmclient_plugin = get_object_or_404(LLMClientPlugin, pk=plugin_id, llmclient=llmclient)
try:
llmclient_plugin.delete()
except CLIENT_ERROR_TYPES as e:
logger.warning("refused: %s", e)
message = client_error_message(e, "The resource could not be deleted.")
return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while deleting the LLMClientPlugin."},
status=HTTPStatus.INTERNAL_SERVER_ERROR,
)
return HttpResponseRedirect(request.path_info.rsplit("/", 2)[0])
[docs]
class LLMClientPluginListView(ListViewBase):
"""LLMClientPlugin list view for smarter api."""
serializer_class = LLMClientPluginSerializer
[docs]
def get_queryset(self, *args, **kwargs):
"""
Return the plugins of the account's LLMClient named by the url's ``llmclient_id``.
:returns: The LLMClientPlugin rows.
:raises Http404: when the account has no such LLMClient.
"""
llmclient_id = self.kwargs.get("llmclient_id")
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
return LLMClientPlugin.objects.filter(llmclient=llmclient)
[docs]
def item(self, row):
"""A plugin of the response, whose ``canDelete`` is the requesting user's."""
return LLMClientApiPlugin.from_model(row, self.request.user).model_dump(mode="json")
###############################################################################
# LLMClientAPIKey views
###############################################################################
[docs]
class LLMClientAPIKeyView(ViewBase):
"""LLMClientAPIKey view for smarter api."""
serializer_class = LLMClientAPIKeySerializer
[docs]
def get(self, request: Request, llmclient_id: int, apikey_id: int):
"""
Return an api key of the account's LLMClient as an :class:`~smarter.apps.llmclient.contract.models.LLMClientApiKey`.
:param request: The request.
:param llmclient_id: The id of the LLMClient.
:param apikey_id: The id of the LLMClientAPIKey.
:returns: The api key's json, or 404 if the LLMClient or api key is not found.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
api_key = get_object_or_404(LLMClientAPIKey, pk=apikey_id, llmclient=llmclient)
return Response(LLMClientApiKey.from_model(api_key).model_dump(mode="json"), status=HTTPStatus.OK)
[docs]
def post(self, request: Request, llmclient_id: int, apikey_id: Optional[int] = None):
"""
Link a SmarterAuthToken to the account's LLMClient, and redirect to the new link.
:param request: The request.
:param llmclient_id: The id of the LLMClient.
:param apikey_id: The primary key of the SmarterAuthToken.
:returns: A redirect to the new LLMClientAPIKey; 404 if the LLMClient or token is not found;
400 if the link could not be created.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
api_key = get_object_or_404(SmarterAuthToken, pk=apikey_id)
try:
llmclient_api_key = LLMClientAPIKey.objects.create(llmclient=llmclient, api_key=api_key)
except REQUEST_DATA_ERROR_TYPES as e:
message = client_error_message(e, "The request data is not valid.")
return JsonResponse({"error": "Invalid request data", "exception": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while creating the LLMClientAPIKey."},
status=HTTPStatus.INTERNAL_SERVER_ERROR,
)
return HttpResponseRedirect(request.path_info + str(llmclient_api_key.id) + "/") # type: ignore[return-value]
[docs]
def delete(self, request: Request, llmclient_id: int, apikey_id: int):
"""
Unlink an api key from the account's LLMClient, and redirect to the list url.
:param request: The request.
:param llmclient_id: The id of the LLMClient.
:param apikey_id: The id of the LLMClientAPIKey.
:returns: A redirect to the list url, or a 500 response if the delete fails.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
llmclient_api_key = get_object_or_404(LLMClientAPIKey, pk=apikey_id, llmclient=llmclient)
try:
llmclient_api_key.delete()
except CLIENT_ERROR_TYPES as e:
logger.warning("refused: %s", e)
message = client_error_message(e, "The resource could not be deleted.")
return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while deleting the LLMClientAPIKey."},
status=HTTPStatus.INTERNAL_SERVER_ERROR,
)
return HttpResponseRedirect(request.path_info.rsplit("/", 2)[0])
[docs]
class LLMClientAPIKeyListView(ListViewBase):
"""LLMClientAPIKey list view for smarter api."""
serializer_class = LLMClientAPIKeySerializer
contract_model = LLMClientApiKey
[docs]
def get_queryset(self, *args, **kwargs):
"""
Return the api keys of the account's LLMClient named by the url's ``llmclient_id``.
:returns: The LLMClientAPIKey rows, with their tokens.
:raises Http404: when the account has no such LLMClient.
"""
llmclient_id = self.kwargs.get("llmclient_id")
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
return LLMClientAPIKey.objects.filter(llmclient=llmclient).select_related("api_key")
###############################################################################
# LLMClientCustomDomain views
###############################################################################
[docs]
class LLMClientCustomDomainView(ViewBase):
"""LLMClientCustomDomain view for smarter api."""
serializer_class = LLMClientCustomDomainSerializer
[docs]
def get(self, request: Request, llmclient_id: int, customdomain_id: int):
"""
Return the account LLMClient's custom domain as an :class:`~smarter.apps.llmclient.contract.models.LLMClientApiCustomDomain`.
:param request: The request.
:param llmclient_id: The id of the LLMClient.
:param customdomain_id: The id of the LLMClientCustomDomain.
:returns: The custom domain's json, or 404 if the LLMClient does not use that domain.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
custom_domain = get_object_or_404(LLMClientCustomDomain, pk=customdomain_id, llmclient=llmclient)
return Response(
LLMClientApiCustomDomain.from_model(custom_domain).model_dump(mode="json"), status=HTTPStatus.OK
)
[docs]
def post(self, request: Request, llmclient_id: int, customdomain_id: int):
"""
Attach the custom domain to the LLMClient, through LLMClient.custom_domain.
If the LLMClient is deployed and the domain is verified, queues
:func:`~smarter.apps.llmclient.tasks.deploy_custom_api` to serve it on its custom host.
:param request: The request.
:param llmclient_id: The id of the LLMClient, which must belong to the user's account.
:param customdomain_id: The id of the LLMClientCustomDomain.
:returns: A redirect to the request's url, or a 409 response if another LLMClient uses the domain.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
custom_domain = get_object_or_404(LLMClientCustomDomain, pk=customdomain_id)
# LLMClient.custom_domain is one-to-one, so a domain belongs to at most one LLMClient.
if LLMClient.objects.filter(custom_domain=custom_domain).exclude(pk=llmclient.pk).exists():
return JsonResponse(
{"error": f"Custom domain {custom_domain.domain_name} is already used by another LLMClient."},
status=HTTPStatus.CONFLICT,
)
llmclient.custom_domain = custom_domain
llmclient.save(update_fields=["custom_domain"])
# a deployed llmclient is served on its custom host once its custom domain is verified.
if llmclient.deployed and custom_domain.is_verified:
deploy_custom_api.delay(llmclient_id=llmclient.id)
return HttpResponseRedirect(request.path_info)
[docs]
def delete(self, request: Request, llmclient_id: int, customdomain_id: int):
"""
Detach the custom domain from the LLMClient.
The domain itself is kept: LLMClient.custom_domain is on_delete=CASCADE, so deleting
the domain would delete the LLMClient too.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
if llmclient.custom_domain_id != customdomain_id: # type: ignore[attr-defined]
return HttpResponseNotFound("Custom domain not found for this LLMClient")
llmclient.custom_domain = None
llmclient.save(update_fields=["custom_domain"])
# these urls have no trailing slash, so the list url is the parent path.
return HttpResponseRedirect(request.path_info.rsplit("/", 1)[0])
[docs]
class LLMClientCustomDomainListView(ListViewBase):
"""LLMClientCustomDomain list view for smarter api."""
serializer_class = LLMClientCustomDomainSerializer
contract_model = LLMClientApiCustomDomain
[docs]
def get_queryset(self, *args, **kwargs):
"""
Return the custom domain of the account's LLMClient named by the url's ``llmclient_id``.
:returns: The LLMClientCustomDomain rows, zero or one.
:raises Http404: when the account has no such LLMClient.
"""
llmclient_id = self.kwargs.get("llmclient_id")
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
return LLMClientCustomDomain.objects.filter(llmclient=llmclient)
###############################################################################
# LLMClientExtensions views
###############################################################################
[docs]
class LLMClientExtensionsView(ViewBase):
"""LLMClientExtensions view for smarter api."""
serializer_class = LLMClientExtensionsSerializer
[docs]
def get(self, request: Request, llmclient_id: int, extension_id: int):
"""
Return an extension of the account's LLMClient as an :class:`~smarter.apps.llmclient.contract.models.LLMClientApiExtension`.
:param request: The request.
:param llmclient_id: The id of the LLMClient.
:param extension_id: The id of the LLMClientExtensions link row.
:returns: The extension's json, or 404 if the LLMClient or link is not found.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
link = get_object_or_404(
LLMClientExtensions.objects.select_related("extension"), pk=extension_id, llmclient=llmclient
)
return Response(LLMClientApiExtension.from_model(link).model_dump(mode="json"), status=HTTPStatus.OK)
[docs]
def delete(self, request: Request, llmclient_id: int, extension_id: int):
"""
Remove an extension from the account's LLMClient, and redirect to the list url.
:param request: The request.
:param llmclient_id: The id of the LLMClient.
:param extension_id: The id of the LLMClientExtensions link row.
:returns: A redirect to the list url, or a 500 response if the delete fails.
"""
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
link = get_object_or_404(LLMClientExtensions, pk=extension_id, llmclient=llmclient)
try:
link.delete()
except CLIENT_ERROR_TYPES as e:
logger.warning("refused: %s", e)
message = client_error_message(e, "The resource could not be deleted.")
return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while deleting the LLMClientExtensions."},
status=HTTPStatus.INTERNAL_SERVER_ERROR,
)
return HttpResponseRedirect(request.path_info.rsplit("/", 2)[0])
[docs]
class LLMClientExtensionsListView(ListViewBase):
"""LLMClientExtensions list view for smarter api."""
serializer_class = LLMClientExtensionsSerializer
contract_model = LLMClientApiExtension
[docs]
def get_queryset(self, *args, **kwargs):
"""
Return the extensions of the account's LLMClient named by the url's ``llmclient_id``, sorted by slug.
:returns: The LLMClientExtensions rows, with their Extensions.
:raises Http404: when the account has no such LLMClient.
"""
llmclient_id = self.kwargs.get("llmclient_id")
llmclient = get_object_or_404(LLMClient, pk=llmclient_id, user_profile__account=self.account)
return (
LLMClientExtensions.objects.filter(llmclient=llmclient)
.select_related("extension")
.order_by("extension__slug")
)