Prompt (Chat) URLS

URL configuration for Smarter deployed LLMClients.

Endpoints

Endpoint

Description

/

Named llmclient configuration view

/config/

Named llmclient configuration view

/prompt/

Default llmclient API view

/jsi18n/

The message catalog of the page that a browser sees at the endpoints, in the browser’s language

The api views answer POST. While the llmclient_enable_endpoints_page waffle switch is active, a GET or HEAD of any of them, e.g. from a browser, receives a page with the curl commands that call them.

smarter.urls.llmclients.handler400(request, exception, template_name='400.html')

django.views.defaults.bad_request(), closing the current thread’s database connections when it returns.

smarter.urls.llmclients.handler403(request, exception, template_name='403.html')

django.views.defaults.permission_denied(), closing the current thread’s database connections when it returns.

smarter.urls.llmclients.handler404(request, exception, template_name='404.html')

django.views.defaults.page_not_found(), closing the current thread’s database connections when it returns.

smarter.urls.llmclients.handler500(request, template_name='500.html')

django.views.defaults.server_error(), closing the current thread’s database connections when it returns.

URL Patterns

 1from django.urls import path
 2from django.views.i18n import JavaScriptCatalog
 3
 4from smarter.apps.llmclient.api.v1.views.default import DefaultLLMClientApiView
 5from smarter.apps.llmclient.views.endpoints import browser_friendly
 6from smarter.apps.prompt.views.detailviews import PromptConfigView
 7from smarter.common.conf import smarter_settings
 8from smarter.lib.django.http import error_handlers
 9from smarter.lib.manifest.sam_apps import get_sam_app
10
11config_view = browser_friendly(PromptConfigView.as_view())
12
13
14def llmclients_disabled(request: HttpRequest) -> HttpResponse:
15    """
16    Answer 404: the llmclient app is disabled, with ``SMARTER_APP_LLMCLIENT_ENABLE=false``, and serves no LLMClients.
17
18    :param request: The request.
19    :raises Http404: Always.
20    """
21    raise Http404("LLMClients are disabled on this platform.")
22
23
24llmclients_enabled = get_sam_app("app_llmclient_enable").is_enabled(smarter_settings)
25
26if llmclients_enabled:
27    urlpatterns = [
28        path("", config_view, name="llmclient_config"),
29        # Alias for 'console_home' so that templates shared with the web console
30        # (e.g. error pages) can resolve this name regardless of which
31        # django-hosts urlconf is active for the current request.
32        path("", config_view, name="console_home"),
33        path("config/", config_view, name="llmclient_named_config"),
34        path("prompt/", browser_friendly(DefaultLLMClientApiView.as_view()), name="llmclient_named_chat"),
35    ]
36else:
37    # a disabled llmclient app serves no LLMClients. See smarter.lib.manifest.sam_apps. The error pages
38    # still reverse 'console_home'.
39    urlpatterns = [
40        path("", llmclients_disabled, name="console_home"),
41    ]
42
43# the endpoints page is a React app, whose text is in the djangojs catalog. See smarter.urls.console.
44urlpatterns += [
45    path("jsi18n/", JavaScriptCatalog.as_view(domain="djangojs"), name="javascript-catalog"),
46]
47
48# Error pages that close their database connections. See smarter.lib.django.http.error_handlers.
49handler400 = error_handlers.bad_request
50handler403 = error_handlers.permission_denied
51handler404 = error_handlers.page_not_found
52handler500 = error_handlers.server_error
53
54__all__ = ["urlpatterns", "handler400", "handler403", "handler404", "handler500"]

PromptConfigView Class Reference

PromptConfigView is a Django class-based view responsible for providing configuration data to the ReactJS prompt UI component in the Smarter web application.

class smarter.apps.prompt.views.detailviews.prompt_config_view.PromptConfigView(**kwargs)[source]

Bases: SmarterOptionallyAuthenticatedApiView

Prompt configuration view for the Smarter web application.

This view is responsible for providing all configuration information required by the ReactJS prompt UI component. It is designed to be performant and efficient, as it is invoked on every user-facing browser load and refresh.

Key Features:

  • Django Template-Based: This view uses Django’s template system for rendering and does not rely on Django REST Framework (DRF) serializers for its main response. The configuration data is returned as a JSON response, but the view itself is structured as a Django class-based view.

  • CSRF Exempt: The view is decorated with @csrf_exempt because it is read-only and does not modify server-side data. This exemption is safe in this context and avoids unnecessary CSRF validation for GET and POST requests that only retrieve configuration data.

  • ReactJS UI Integration: The endpoint provides all necessary configuration and context information for the ReactJS prompt component. This includes llmclient metadata, plugin information, session keys, and historical data relevant to the prompt session. The React app consumes this configuration to initialize and render the prompt UI in the user’s browser.

  • Session-Based Architecture: Each prompt session is uniquely identified and managed by a globally unique 64-character session key. The session key is generated by RequestHelper.generate_session_key() and is persisted by the browser in a domain and path-specific cookie, meaning that this design supports an unlimited number of concurrent sessions per user, one per device per llmclient.

  • Performance Considerations: Since this endpoint is called on every browser load and refresh, performance is a primary concern. The view is optimized to minimize database queries and serialization overhead. Only a limited number of plugins (as defined by MAX_RETURNED_PLUGINS) are returned to avoid excessive payload sizes. Caching and efficient queryset usage are employed where possible to ensure fast response times for end users.

Example Usage:

Returns:
JSON response containing:
  • session_key: Unique identifier for the prompt session.

  • sandbox_mode: Boolean indicating if the llmclient is running in sandbox mode.

  • debug_mode: Boolean indicating if debug mode is enabled.

  • llmclient: Serialized llmclient configuration.

  • history: The session’s messages, and, with ?verbose=true, its tool calls.

  • meta_data: The llmclient’s state, and, with ?verbose=true, the complete LLMClientHelper.

  • plugins and extensions: Their counts, and, with ?verbose=true, a limited list of each.

See verbose.

Security:
  • The view is protected and requires the user to be authenticated, unless the llmclient is configured to allow unauthenticated access.

  • If authentication is required and the user is not authenticated, a 403 Forbidden response is returned.

See Also:
  • SmarterPromptSession: Helper class for managing prompt sessions.

  • LLMClientConfigSerializer: Serializer for the llmclient’s data.

  • LLMClientHelper: Helper for llmclient-related operations.

authentication_classes = None
chat_config()[source]

Assemble the configuration required by the ReactJS prompt UI component, as the contract’s model.

This method gathers all relevant context and configuration data for the prompt session and llmclient, and returns it as a PromptChatApiConfig, the Pydantic model of version 2 of the Smarter Chat api contract. config() derives the response from it: the complete or public configuration, in version 2 or 1 of the contract.

Performance:

Since this endpoint is called on every browser load and refresh, the logic is optimized to minimize database queries and serialization overhead. The diagnostic parts, which the workbench’s Console displays, are built only for a client that asks for them (see verbose), and only a limited number of plugins (see MAX_RETURNED_PLUGINS) are returned.

Returns:

The configuration, or None if the session or the LLMClient helper is not set. Its fields: session_key, sandbox_mode, debug_mode, llmclient (serialized by LLMClientConfigSerializer, with url_llmclient from prompt_url()), history (chat_history()), meta_data (meta_data()), plugins and extensions.

Return type:

PromptChatApiConfig | None

Raises:

pydantic.ValidationError – If the data breaks the contract.

See also

SmarterPromptSession

Helper class for managing prompt sessions.

LLMClientConfigSerializer

Serializer for the llmclient’s data.

LLMClientHelper

Helper for llmclient-related operations.

chat_history()[source]

The chat session’s history, from its rows.

  • chat_history, the session’s messages, which restore the chat thread, always.

  • prompt_tool_call_history, the session’s tool calls, if verbose.

  • prompt_plugin_usage_history, plugin_selector_history and llmclient_request_history for the cli only (include_diagnostics). Smarter Chat doesn’t display them, and the requests, each of which holds the whole thread, grow with the square of the session’s length.

Returns:

The history, empty without a session.

Return type:

PromptChatApiHistory

chat_history_row: PromptHistory | None = None

The PromptHistory row that chat_history() read the thread from, which the journal reads again.

clean_url(url)[source]

Clean the url of any query strings and trailing ‘/config/’ strings.

Return type:

str

command: SmarterJournalCliCommands | None = None
config()[source]

The configuration api’s response body: chat_config(), in the form that the client receives.

Returns:

{"data": <the configuration>}, or {} without a session or LLMClient helper.

Return type:

dict[str, Any]

Raises:

pydantic.ValidationError – If the configuration breaks the contract.

config_response(request)[source]

The configuration, as the response to the client.

Parameters:

request (HttpRequest) – The request.

Returns:

The configuration, or an error response if it breaks the contract.

Return type:

SmarterJournaledJsonResponse | SmarterJournaledJsonErrorResponse

contract: int = 1

The version of the contract that the client asked for.

See requested_contract().

dispatch(request, *args, **kwargs)[source]

Handles incoming HTTP requests for the prompt configuration endpoint.

This method is responsible for orchestrating the retrieval and assembly of all configuration data required by the ReactJS prompt UI component. It is invoked on every user-facing browser load and refresh, making performance a critical concern.

Key Details:

  • Django Template-Based: This view uses Django’s class-based view and template system, not Django REST Framework (DRF). The response is a JSON object, but the view logic is not DRF-based.

  • CSRF Exempt: The view is decorated with @csrf_exempt because it is strictly read-only and does not modify server-side data. This avoids unnecessary CSRF validation for GET and POST requests that only retrieve configuration data.

  • ReactJS UI Integration: The endpoint provides all configuration and context information needed by the ReactJS prompt component, including llmclient metadata, plugin information, session keys, and prompt history.

  • Session-Based: Sessions are managed by the SmarterPromptSession helper, which uniquely defines a prompt session using a combination of the user’s IP address and device-identifying information. This ensures each device/browser instance receives a unique session key, which is used to track prompt history and plugin usage.

  • Performance: Since this endpoint is called on every browser load and refresh, it is optimized to minimize database queries and serialization overhead. Only a limited number of plugins are returned (see MAX_RETURNED_PLUGINS) to keep payloads small and response times fast.

Parameters:
  • request (HttpRequest) – The incoming HTTP request object.

  • llmclient_id (Optional[int], default=None) – The ID of the llmclient to retrieve configuration for, if specified.

  • *args – Additional positional arguments.

  • **kwargs – Additional keyword arguments.

Returns:

A JSON response containing all configuration data required by the ReactJS prompt UI component, or an error response if the request is invalid or unauthorized.

Return type:

JsonResponse | HttpResponse | SmarterJournaledJsonErrorResponse

See also

SmarterPromptSession

Helper class for managing prompt sessions.

LLMClientConfigSerializer

Serializer for the llmclient’s data.

LLMClientHelper

Helper for llmclient-related operations.

dispatch_config(request, *args, **kwargs)[source]

Handle the request, for dispatch(), which scopes the chat session key of its log records to it.

Parameters:

request (HttpRequest) – The incoming HTTP request.

Return type:

JsonResponse | HttpResponse | SmarterJournaledJsonErrorResponse

Returns:

The configuration, or an error response.

error_response(request, error)[source]

The configuration api’s error response, the same shape for every error.

See chat_error_response().

Parameters:
Returns:

The error response, without a stack trace.

Return type:

SmarterJournaledJsonErrorResponse

property formatted_class_name: str

Returns a formatted string of the class name for logging purposes.

property full_config: bool

Whether the client receives the complete configuration.

The complete configuration includes the LLMClient’s every field, e.g. its owner’s profile, the session’s diagnostic histories, and the lists of plugins and extensions. It is returned when the LLMClient was found by its id or hashed id, i.e. by a workbench or platform api url, which checks that the user may read it, and to the cli. A deployed LLMClient’s own host, which pages that embed Smarter Chat call, receives public_config().

Returns:

True for the complete configuration.

Return type:

bool

get(request, *args, **kwargs)[source]

Get the llmclient configuration.

Return type:

SmarterJournaledJsonResponse | SmarterJournaledJsonErrorResponse | HttpResponseNotAllowed

include_diagnostics: bool = False

Return the complete configuration, whatever url resolved the LLMClient.

The cli passes as_view(include_diagnostics=True). See full_config().

legacy_keys: bool = True

Rename keys for older versions of the React app (‘llmclient’ to ‘chatbot’), in version 1 of the contract.

The cli passes as_view(legacy_keys=False).

property llmclient: LLMClient | None

The LLMClient of this config request, set by the llmclient_helper setter.

property llmclient_helper: LLMClientHelper | None

The LLMClientHelper of this request, created on first access and cached.

Built from the LLMClient when one is set, else from the LLMClient name of the view or the request.

llmclient_name: str | None = None
meta_data()[source]

The LLMClient’s state.

It is the complete LLMClientHelper.to_json() if verbose, and otherwise only the fields of PUBLIC_META_DATA_FIELDS that the helper has, which are what Smarter Chat reads. to_json() serializes the LLMClient a second time, with its tools, and the request.

Returns:

The meta data, empty without an LLMClient helper.

Return type:

PromptChatApiMetaData

permission_classes = (<class 'smarter.lib.drf.views.helpers.UnauthenticatedPermissionClass'>,)
post(request, *args, **kwargs)[source]

Get the llmclient configuration.

Return type:

SmarterJournaledJsonResponse | SmarterJournaledJsonErrorResponse

prompt_url(url_llmclient)[source]

The url of the LLMClient’s prompt api, on the host that served the configuration.

A deployed LLMClient’s host, or its custom domain, also serves its prompt api, at /prompt/, so that a page that embeds Smarter Chat needs access to one host only. A workbench or platform api url keeps the platform’s prompt api url.

Parameters:

url_llmclient (str | None) – The LLMClient’s prompt api url on the platform, LLMClient.url_llmclient.

Returns:

The prompt api url to return to the client.

Return type:

str | None

resolved_by_id: bool = False

True if the LLMClient was found by its id or hashed id, which also checks that the user may read it.

session: SmarterPromptSession | None = None
thing: SmarterJournalThings | None = None
property verbose: bool

Whether the configuration includes its diagnostic parts, which the workbench’s Console displays.

They are the session’s tool calls, the complete meta_data (LLMClientHelper.to_json()), and the lists of the LLMClient’s plugins and extensions. They cost database queries and serialization, and the tool calls grow with the session, so a client asks for them with ?verbose=true (VERBOSE_PARAMETER) only when it displays them. Only a client that receives the complete configuration (full_config) may ask for them, and the cli always receives them.

Returns:

True for the diagnostic parts.

Return type:

bool

verbose_requested: bool = False

True if the request’s query string has ?verbose=true.

See verbose.

smarter.apps.prompt.views.detailviews.prompt_config_view.should_log(level)[source]

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

smarter.apps.prompt.views.detailviews.prompt_config_view.should_log_verbose(level)[source]

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

PromptProviderRequestView Class Reference

The provider request api: a chat session’s conversation, as the request body that Smarter sends to the LLM provider.

The Prompt Engineer’s Workbench downloads it, in sandbox mode, as a JSON file that can be sent with curl to the LLM provider’s v1/chat/completions api, or pasted into the Prompt Passthrough page. See PromptChatApiProviderRequest.

smarter.apps.prompt.views.detailviews.prompt_provider_request_view.PROVIDER_REQUEST_FIELDS = ('model', 'temperature', 'max_completion_tokens', 'tools', 'tool_choice', 'reasoning_effort')

The fields of a saved request that are sent to the LLM provider.

The saved request also has Smarter’s api_url and masked api_key, which are not part of the body, and the messages of its first iteration only, which provider_request_messages() replaces with the whole conversation.

(
    'model',
    'temperature',
    'max_completion_tokens',
    'tools',
    'tool_choice',
    'reasoning_effort',
)
class smarter.apps.prompt.views.detailviews.prompt_provider_request_view.PromptProviderRequestView(**kwargs)[source]

Bases: PromptConfigView

The provider request api, /api/v1/llm-clients/<hashed_id>/provider-request/.

It returns a chat session’s conversation as the request body that Smarter sends to the LLM provider, without Smarter’s own content: see PromptChatApiProviderRequest. Smarter Chat downloads it, in sandbox mode, as a JSON file.

It finds the LLMClient and the chat session as PromptConfigView does, and answers only the requests that receive the complete configuration (see PromptConfigView.full_config): the workbench’s and the platform api’s urls, whose user may read the LLMClient. It is 404 on a deployed LLMClient’s own host, because the request holds the LLMClient’s system prompt and tool definitions.

config_response(request)[source]

The provider request, as the response to the client.

Parameters:

request (HttpRequest) – The request.

Returns:

{"data": <the request body>}, or an error response.

Return type:

SmarterJournaledJsonResponse | SmarterJournaledJsonErrorResponse

property formatted_class_name: str

Returns a formatted string of the class name for logging purposes.

provider_request()[source]

The session’s conversation, as the request body that Smarter sends to the LLM provider.

Returns:

The request body, or None without a session or an LLMClient.

Return type:

PromptChatApiProviderRequest | None

Raises:

pydantic.ValidationError – If the saved request breaks the contract.

smarter.apps.prompt.views.detailviews.prompt_provider_request_view.llmclient_request_settings(llmclient)[source]

Return the model, temperature, token limit and reasoning effort that the LLMClient’s next prompt is sent with.

They are the LLMClient’s own, or else its provider’s default model and the platform’s defaults, as handler() chooses them.

Parameters:

llmclient (LLMClient) – The LLMClient.

Returns:

The settings, by request field.

Return type:

dict[str, Any]

smarter.apps.prompt.views.detailviews.prompt_provider_request_view.provider_request(history, llmclient)[source]

Return a chat session’s conversation, as the request body that Smarter sends to the LLM provider.

The model, temperature, token limit and tools are those of the session’s latest prompt, or else the LLMClient’s, which has no tools until a prompt selects them. The model’s quirks apply, as they do to every request that Smarter sends: see apply_model_quirks().

Parameters:
  • history (PromptHistory | None) – The session’s latest PromptHistory, or None before its first prompt.

  • llmclient (LLMClient) – The session’s LLMClient.

Returns:

The request body.

Return type:

PromptChatApiProviderRequest

Raises:

pydantic.ValidationError – If the saved request breaks the contract.

smarter.apps.prompt.views.detailviews.prompt_provider_request_view.provider_request_messages(history, llmclient)[source]

Return the conversation’s messages, as they are sent to the LLM provider.

Parameters:
  • history (PromptHistory | None) – The session’s latest PromptHistory, or None before its first prompt.

  • llmclient (LLMClient) – The LLMClient, whose introduction starts a session that has sent no prompt.

Returns:

The messages, without Smarter’s own. See provider_messages().

Return type:

list[dict[str, Any]]

DefaultLLMClientApiView Class Reference

Smarter Customer API view.

class smarter.apps.llmclient.api.v1.views.default.DefaultLLMClientApiView(**kwargs)[source]

Bases: LLMClientApiBaseViewSet

Main view for Smarter LLMClient API prompts.

The top-level viewset for customer-deployed Plugin-based Prompt APIs.

dispatch(request, *args, **kwargs)[source]

Smarter API LLMClient dispatch method.

Parameters:
  • request – Django HttpRequest object

  • args – Additional positional arguments

  • name – LLMClient name (str, optional)

  • kwargs – Additional keyword arguments

Example request payload:

{
    "session_key": "dde3dde5e3b97134f5bce5edf26ec05134da71d8485a86dfc9231149aaf0b0af",
    "messages": [
        {
            "role": "assistant",
            "content": "Welcome to Smarter!.  how can I assist you today?"
        },
        {
            "role": "user",
            "content": "Hello, World!"
        }
    ]
}