Smarter Request Mixin

class smarter.lib.django.request.SmarterRequestMixin(*args, request=None, **kwargs)[source]

Bases: AccountMixin

Helper class for the Django request object that enforces authentication and.

provides lazy loading of the user, account, user profile, and session_key.

This mixin works with any Django request object and any valid URL, but is designed as a helper class for Smarter LLMClient URLs.

Note

The request object is an optional positional argument due to Django view lifecycles, which do not recognize the request object until after class __init__(). SmarterRequestMixin is included as a mixin in the Smarter base view classes.

Valid endpoints:

  1. Root endpoints for named URLs (public or authenticated chats) (self.is_llm_client_named_url == True)

    • http://example.3141-5926-5359.api.localhost:9357/smarter.apps.llm_client.api.v1.views.default.DefaultLLMClientApiView

    • http://example.3141-5926-5359.api.localhost:9357/configsmarter.apps.prompt.views.PromptConfigView

  2. Authenticated sandbox endpoints (authenticated chats) (self.is_llm_client_sandbox_url == True)

    • http://localhost:9357/workbench/<str:name>/smarter.apps.prompt.views.PromptWorkbenchView

    • http://localhost:9357/workbench/<str:name>/config/smarter.apps.prompt.views.PromptConfigView

  3. smarter.sh/v1 endpoints (public or authenticated chats) (self.is_llm_client_smarter_api_url == True)

    • http://localhost:9357/api/v1/workbench/<int:llm_client_id>/prompt/smarter.apps.llm_client.api.v1.views.default.DefaultLLMClientApiView

    • http://localhost:9357/api/v1/workbench/<int:llm_client_id>/prompt/config/smarter.apps.prompt.views.PromptConfigView

  4. Command-line interface API endpoints (authenticated chats) (self.is_llm_client_cli_api_url == True)

    • http://localhost:9357/api/v1/cli/prompt/<str:name>/smarter.apps.llm_client.api.v1.cli.views.nonbrokered.prompt.ApiV1CliPromptApiView

    • http://localhost:9357/api/v1/cli/prompt/config/<str:name>/smarter.apps.llm_client.api.v1.cli.views.nonbrokered.chat_config.ApiV1CliPromptConfigApiView

  5. Other endpoints (possibly deprecated or unused) - http://localhost:9357/api/v1/prompt/

Example URLs:

  • http://testserver

  • http://localhost:9357/

  • http://localhost:9357/docs/

  • http://localhost:9357/dashboard/

  • https://alpha.platform.smarter.sh/api/v1/workbench/1/llm-client/

  • http://example.com/contact/

  • http://localhost:9357/workbench/example/config/?session_key=...

  • https://hr.3141-5926-5359.alpha.api.example.com/

  • https://hr.3141-5926-5359.alpha.api.example.com/config/?session_key=...

  • http://example.3141-5926-5359.api.localhost:9357/

  • http://example.3141-5926-5359.api.localhost:9357/?session_key=...

  • http://example.3141-5926-5359.api.localhost:9357/config/

  • http://example.3141-5926-5359.api.localhost:9357/config/?session_key=...

  • http://localhost:9357/api/v1/workbench/1/prompt/

  • http://localhost:9357/api/v1/cli/prompt/smarter/?new_session=false&uid=mcdaniel

  • https://hr.smarter.sh/

Variables:

session_key – Unique identifier for a prompt session, generated by generate_session_key().

__init__(*args, request=None, **kwargs)[source]

Note: this needs to exist.

something in the Python MRO requires it, even if it does nothing. If you remove this, you will get a mysterious error about something downstream expecting exactly one object.

property api_subdomain: str | None[source]

Extracts the API subdomain from the URL.

Returns:

The API subdomain or None if not found.

example:

- https://hr.3141-5926-5359.alpha.api.example.com/llm-client/
returns 'hr'
property api_token: bytes | None[source]

Get the API token from the request.

Returns:

The API token as bytes if present in the Authorization header, otherwise None.

Example:

request_mixin = SmarterRequestMixin(request)
token = request_mixin.api_token
Returns:

The API token as bytes, or None if not present.

property auth_header: str | None

Get the Authorization header from the request.

Example:

request_mixin = SmarterRequestMixin(request)
print(request_mixin.auth_header)

This property checks for the “Authorization” header in the request headers or in the Django META dictionary.

Returns:

The value of the “Authorization” header as a string, or None if not present.

authenticate()[source]

Authenticates the request using the provided API token.

Return type:

bool

property cache_key: str | None[source]

Returns a cache key for the request.

This is used to cache the prompt request thread. The key is a combination of: - the class name, - authenticated username, - the prompt name, - and the client UID.

Currently used by the ApiV1CliPromptConfigApiView and ApiV1CliPromptApiView as a means of sharing the session_key.

Parameters:
  • name – A generic object or resource name.

  • uid – UID of the client, assumed to have been created from the machine MAC address and the hostname of the client.

Returns:

A unique cache key string.

Example:

request_mixin = SmarterRequestMixin(request)
key = request_mixin.cache_key
print(key)  # e.g., 'a1b2c3d4e5f6...'
clear_cached_properties()[source]

Clears all cached properties in this mixin.

property data: dict | list | str | None[source]

Get the request body data as a dictionary, list or str.

Used for setting the session_key.

Returns:

The request body data as a dict, list, or str, or None if not available.

Example:

request_mixin = SmarterRequestMixin(request)
data = request_mixin.data
print(data)  # e.g., {'session_key': 'abc123', ...}
property domain: str | None[source]

Extracts the domain from the URL.

Returns:

The domain or None if not found.

examples:

- https://hr.3141-5926-5359.alpha.api.example.com/llm-client/
  returns 'hr.3141-5926-5359.alpha.api.example.com'
eval_llm_client_url()[source]

If we are an llm_client, based on analysis of the URL format.

then we need to make a follow up check of the user and account.

Examples

1.) For named urls, we extract the account number from the url,

then we load the account and admin user for that account.

2.) For smarter api urls, we would extract the llm_client id from the url,

then we would load the llm_client, account, and admin user for that account.

3.) For cli api urls, we would extract the llm_client name from the url,

then we would load the llm_client, account, and admin user for that account.

find_session_key()[source]

Returns the unique prompt session key value for this request.

The session_key is managed by the /config/ endpoint for the llm_client. The React app calls this endpoint at app initialization to get a JSON dict that includes, among other info, this session_key, which uniquely identifies the device and the individual llm_client session for the device.

For subsequent prompt prompt requests, the session_key is intended to be sent in the body of the request as a key-value pair, e.g. {“session_key”: “1234567890”}.

This method will also check the request headers and cookies for the session_key. The session key can be found in one of the following:

Return type:

Optional[str]

Returns:

The session key as a string, or None if not found.

generate_session_key()[source]

Generate a session_key based on a unique string and the current datetime.

Return type:

str

Returns:

A unique session key string.

Retrieve the value of a cookie from the request object.

Parameters:
  • request – Django HttpRequest object

  • cookie_name – Name of the cookie to retrieve

Returns:

Value of the cookie or None if the cookie does not exist

invalidate_cached_properties()[source]

Invalidates all cached properties on the instance to force re-evaluation.

This method removes all attributes cached by @cached_property decorators from the instance’s __dict__. It is useful for testing or when the request object changes and you need to ensure that all dependent properties are recalculated.

Example:

from smarter.lib.django.request import SmarterRequestMixin

class Foo(SmarterRequestMixin):
    pass

foo = Foo(request)
foo.invalidate_cached_properties(request)
Raises:

None

property ip_address: str | None[source]

Get the client’s IP address from the request object.

This property attempts to extract the IP address from the request’s META dictionary, using the “REMOTE_ADDR” key. If the IP address is not available, it returns None.

Returns:

The client’s IP address as a string, or None if not found.

Return type:

Optional[str]

Example:

request_mixin = SmarterRequestMixin(request)
ip = request_mixin.ip_address
print(ip)  # e.g., '192.168.1.100'
property is_authenticated: bool

Returns True if the request is authenticated, False otherwise.

property is_config: bool[source]

Returns True if the URL resolves to a config endpoint.

Examples

http://testserver/api/v1/cli/prompt/config/testc7098865f39202d5/ http://localhost:9357/workbench/example/config/?session_key=1aeee4c1f183354247f43f80261573da921b0167c7c843b28afd3cb5ebba0d9a http://localhost:9357/api/v1/workbench/<int:llm_client_id>/prompt/config/ http://example.api.localhost:9357/config

Returns:

True if the URL is a config endpoint, otherwise False.

Return type:

bool

property is_dashboard: bool[source]

Returns True if the URL resolves to a dashboard endpoint.

Returns:

True if the URL is a dashboard endpoint, otherwise False.

Return type:

bool

property is_default_domain: bool[source]

Returns True if the URL is the default domain for the environment.

Example

api.alpha.platform.smarter.sh

Returns:

bool: True if the URL is the default environment domain, otherwise False.

property is_environment_root_domain: bool[source]

Returns True if the URL resolves to the environment root domain.

Returns:

True if the URL is the environment root domain, otherwise False.

Return type:

bool

is_internal_api_request(request)[source]

Check if the request is an internal API request.

This method checks for a custom attribute on the request object that indicates whether the request is an internal API request. This can be used to bypass certain authentication or permission checks for internal requests.

Parameters:

request (HttpRequest) – The Django request object.

Returns:

True if it’s an internal API request, False otherwise.

Return type:

bool

property is_llm_client: bool[source]

Returns True if the URL resolves to an llm_client endpoint.

Conditions are checked in a lazy sequence to avoid unnecessary processing.

Examples

Returns:

True if the URL is an llm_client endpoint, otherwise False.

Return type:

bool

property is_llm_client_cli_api_url: bool[source]

9357/api/v1/cli/prompt/example/.

The expected path parts are:

[‘api’, ‘v1’, ‘cli’, ‘prompt’, ‘example’]

Returns:

True if the URL matches the CLI llm_client API pattern, otherwise False.

Return type:

bool

Type:

Returns True if the URL is of the form http

Type:

//localhost

property is_llm_client_named_url: bool[source]

Returns True if the url is of the form:

Returns:

True if the URL matches the named llm_client pattern, otherwise False.

Return type:

bool

property is_llm_client_sandbox_url: bool[source]

Example URLs for llm_client sandbox endpoints.

Examples

Web console urls: - http://localhost:9357/workbench/llm-clients/<str:hashed_id>/prompt/ - http://localhost:9357/workbench/llm-clients/<str:hashed_id>/config/ - http://localhost:9357/workbench/llm-clients/<str:hashed_id>/manifest/

Api urls: - http://localhost:9357/api/v1/prompt/1/prompt/ - http://localhost:9357/api/v1/prompt/1/config/

Manifest view urls: https://alpha.platform.smarter.sh/workbench/llm-clients/hashed_id/ https://<environment_domain>/workbench/llm-clients/<str:hashed_id>/ path_parts: [‘workbench’, ‘llm-clients’, ‘rxy123hashedx’]

Returns:

True if the URL matches an llm_client sandbox endpoint, otherwise False.

Return type:

bool

property is_llm_client_smarter_api_url: bool[source]

Returns True if the URL is of the form:

Returns:

True if the URL matches a smarter API llm_client endpoint, otherwise False.

Return type:

bool

property is_smarter_api: bool[source]

9357/api/v1/.

Examples

Returns:

True if the URL matches the smarter API pattern, otherwise False.

Return type:

bool

Type:

Returns True if the URL is of the form http

Type:

//localhost

property is_workbench: bool[source]

Returns True if the URL resolves to a workbench endpoint.

Returns:

True if the URL is a workbench endpoint, otherwise False.

Return type:

bool

log_ready_status()[source]

Logs the ready status of the view.

property params: QueryDict[source]

The query string parameters from the Django request object.

This extracts the query string parameters from the request object and converts them to a dictionary. Used in child views to pass optional command-line parameters to the broker.

Returns:

QueryDict containing the query string parameters.

Example:

request_mixin = SmarterRequestMixin(request)
params = request_mixin.params
print(params)  # e.g., {'session_key': 'abc123', 'uid': 'xyz'}
property parsed_url: ParseResult | None

Expose the private ParseResult URL object as a public property.

Returns:

The parsed URL as a ParseResult object.

Example:

request_mixin = SmarterRequestMixin(request)
parsed = request_mixin.parsed_url
print(parsed.netloc)  # e.g., 'example.com'
property path: str | None[source]

Extracts the path from the URL.

Returns:

Optional[str]: The path as a string, or None if not found.

Examples

property qualified_request: bool

A cursory screening of the WSGI request object to look for.

any disqualifying conditions that confirm this is not a request that we are interested in.

The request is considered “qualified” if all of the following are true:

  • The request object (self._smarter_request) is present.

  • The URL path is present and non-empty.

  • The request does not originate from an internal AWS Kubernetes subnet (netloc starts with 192.168).

  • The path is not in the list of amnesty_urls.

  • The path does not start with /admin/.

  • The path does not start with /docs/.

  • The path does not end with a static file extension (e.g., .css, .js, .png, .jpg, .jpeg, .gif, .svg, .woff, .woff2, .ttf, .eot, .ico).

Returns:

True if the request passes all checks and is of interest, otherwise False.

Example:

# True case: a valid llm_client request
request_mixin = SmarterRequestMixin(request)
if request_mixin.qualified_request:
    print("This is a qualified llm_client request.")

# False case: a static asset or admin/docs request
static_request = SmarterRequestMixin(static_asset_request)
if not static_request.qualified_request:
    print("This request is not of interest.")
property root_domain: str | None[source]

Extracts the root domain from the URL.

Returns:

The root domain or None if not found.

Example:

request_mixin = SmarterRequestMixin(request)
print(request_mixin.root_domain)
# For 'https://hr.3141-5926-5359.alpha.api.example.com/llm-client/' → 'smarter.sh'
# For 'http://localhost:9357/' → 'localhost'
property session_key: str

Getter for the session_key property.

The session_key is a unique identifier for a prompt session. It is used to identify the prompt session across multiple requests. If the session_key is not already set, it attempts to find it in the URL parameters. Barring that, it generates a new one.

Returns:

The session key as a string.

Example:

request_mixin = SmarterRequestMixin(request)
session_key = request_mixin.session_key
print(session_key)  # e.g., '38486326c21ef4bcb7e7bc305bdb062f16ee97ed8d2462dedb4565c860cd8ecc'
set_is_internal_api_request(request, value=True)[source]

Set the internal API request attribute on the request object.

This method allows you to mark a request as an internal API request by setting a custom attribute on the request object. This can be used in middleware or views to indicate that the request should be treated as internal.

Parameters:
  • request (HttpRequest) – The Django request object.

  • value (bool) – The value to set for the internal API request attribute (default is True).

Returns:

The modified Django request object.

Return type:

HttpRequest

setup(*args, request=None, user=None, **kwargs)[source]

Setup method to initialize the SmarterRequestMixin with the request and user.

This method is called during the setup phase of a Django view. It initializes the request and user attributes of the mixin. The request is set using the smarter_request property setter, which also handles URL parsing and user authentication.

Parameters:
  • args – Positional arguments passed to the setup method.

  • request (Optional[HttpRequest]) – The HTTP request object to be associated with this mixin instance.

  • user (Union[AnonymousUser, User, None]) – The user associated with the request, if available.

  • kwargs – Keyword arguments passed to the setup method.

Returns:

None

property smarter_request: Request | HttpRequest | ASGIRequest | MagicMock | None

Returns the current request object.

This property is named to avoid potential name collisions in child classes. This property is preferred over standard Django request types in that it more elegantly resolves idiosyncratic usage like Unit tests, Sphinx docs, and other non-standard request objects.

Example:

request_mixin = SmarterRequestMixin(request)
req = request_mixin.smarter_request
Returns:

The current request object.

property smarter_request_llm_client_id: int | None

Extract the llm_client id from the URL.

Example

http://localhost:9357/workbench/llm-clients/rMTAwMDAyNwx/prompt/

returns the pk id that when decoded from the hashed ID format corresponds to the llm_client id.

Returns:

The llm_client id as an integer, or None if not found.

property smarter_request_llm_client_name: str | None[source]

Extract the llm_client name from the URL.

Example

http://example.3141-5926-5359.api.localhost:9357/config

returns “example”

Returns:

The llm_client name as a string, or None if not found.

property smarter_request_user: AnonymousUser | User | None

Returns the user associated with the request.

This property is named to avoid potential name collisions in child classes. It retrieves the user from the request object if available.

Example:

request_mixin = SmarterRequestMixin(request)
user = request_mixin.smarter_request_user
Returns:

The user associated with the request, or None if not available.

property srm_formatted_class_name: str[source]

Returns the class name in a formatted string.

along with the name of this mixin.

Returns:

Formatted class name string.

property srm_ready: bool

Returns True if the request mixin is srm_ready for processing.

This is a convenience property to check if the request is srm_ready.

Returns:

True if the request mixin is srm_ready, False otherwise.

property subdomain: str | None[source]

Extracts the subdomain from the URL.

Returns:

The subdomain or None if not found.

Example:

request_mixin = SmarterRequestMixin(request)
sub = request_mixin.subdomain
print(sub)  # e.g., 'hr.3141-5926-5359.alpha' for
            # 'https://hr.3141-5926-5359.alpha.api.example.com/llm-client/'
property timestamp

Create a consistent timestamp based on the time that this object was instantiated.

Returns:

The timestamp as a datetime object.

Example:

request_mixin = SmarterRequestMixin(request)
ts = request_mixin.timestamp
print(ts)  # e.g., 2025-12-01 12:34:56.789012
to_json()[source]

Serializes the object.

Return type:

dict[str, Any]

Returns:

A dictionary representation of the object.

property uid: str | None

Unique identifier for the client.

This is assumed to be a combination of the machine MAC address and the hostname.

Returns:

The client UID as a string, or None if not available.

Example:

request_mixin = SmarterRequestMixin(request)
uid = request_mixin.uid
print(uid)  # e.g., '00:1A:2B:3C:4D:5E-myhost'
property unique_client_string: str

Generate a unique string based on several request attributes.

This string is used for generating session_key and client_key.

The unique string is composed of:
  • Account number

  • URL

  • User agent

  • IP address

  • Timestamp

Returns:

A unique string representing the client and request context.

Return type:

str

Example:

request_mixin = SmarterRequestMixin(request)
unique_str = request_mixin.unique_client_string
print(unique_str)
property url: str | None

The string representation of the ParseResult object stored in _parsed_url.

Returns:

The URL as a string.

Example:

request_mixin = SmarterRequestMixin(request)
url_str = request_mixin.url
print(url_str)  # e.g., 'https://example.com/path/'
property url_account_number: str | None

Extract the account number from the URL using the pattern defined in.

SmarterValidator.VALID_ACCOUNT_NUMBER_PATTERN.

Example

http://example.3141-5926-5359.api.localhost:9357/config

returns “3141-5926-5359”

Returns:

The account number as a string, or None if not found.

property url_path_parts: list[str][source]

Extract the path parts from the URL.

Returns:

A list of strings representing each part of the URL path.

Example:

request_mixin = SmarterRequestMixin(request)
parts = request_mixin.url_path_parts
print(parts)  # e.g., ['api', 'v1', 'workbench', '1', 'prompt']
property user_agent: str | None

Get the client’s user agent string from the request object.

This property attempts to extract the user agent from the request’s META dictionary, using the “HTTP_USER_AGENT” key. If the user agent is not available, it returns a default value.

Returns:

The client’s user agent string, or None if not found.

Return type:

Optional[str]

Example:

request_mixin = SmarterRequestMixin(request)
ua = request_mixin.user_agent
print(ua)  # e.g., 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)...'