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_llmclient_named_url == True)

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

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

  2. Authenticated sandbox endpoints (authenticated chats) (self.is_llmclient_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_llmclient_smarter_api_url == True)

    • http://localhost:9357/api/v1/workbench/<int:llmclient_id>/prompt/ → smarter.apps.llmclient.api.v1.views.default.DefaultLLMClientApiView

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

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

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

    • http://localhost:9357/api/v1/cli/prompt/config/<str:name>/ → smarter.apps.llmclient.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.

accepted_session_key(session_key, source)[source]

Return a session key that the request carries, if it is well formed.

The key comes from the client: the url, the request body, a cookie or a get() parameter. A malformed key, e.g. a cookie of the same name that another application set on a parent domain, is ignored rather than raised, so that the request starts a new session instead of failing.

Parameters:
  • session_key (str | None) – The raw value that the request carries, or None.

  • source (str) – Where the value came from, for the log, e.g. "cookie".

Return type:

str | None

Returns:

The session key, stripped of whitespace and of a trailing slash, or None if the value is missing or malformed.

property api_subdomain: str | None[source]

Extract the API subdomain, the first label of the host, from an llmclient URL.

For example, this url returns 'hr':

https://hr.3141-5926-5359.alpha.api.example.com/llm-client/
Returns:

The API subdomain, or None if the url is not an llmclient url.

property api_token: bytes | None[source]

Get the API token from the request’s Authorization header.

The header’s value is Token <key> or Bearer <key>.

Example:

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

The API token as bytes, or None if the header is missing or has neither prefix.

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.

Returns:

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

authenticate(api_token=None, request=None)[source]

Authenticate the request using the API token in its Authorization header.

The request is passed along, so that a token that was already authenticated for it, e.g. by the token middleware or by AccountMixin’s own initialization, is not authenticated again.

Parameters:
  • api_token (bytes | None) – The API token to authenticate with. Defaults to the request’s.

  • request (HttpRequest | None) – The request that carries the token. Defaults to this mixin’s request.

Return type:

bool

Returns:

True if there is an API token and the parent’s authenticate() accepts it, otherwise False.

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 the sha256 hash of:

  • the class name,

  • the request’s user, or "Anonymous",

  • and the client UID (uid), or "unknown_uid".

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

Example:

request_mixin = SmarterRequestMixin(request)
key = request_mixin.cache_key
print(key)  # e.g., 'a1b2c3d4e5f6...'
Returns:

A unique cache key string, or None if there is no request.

clear_cached_properties()[source]

Clear the request, its parsed values, and all cached properties in this mixin.

Return type:

None

Returns:

None.

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

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

Used for setting the session_key.

Example:

request_mixin = SmarterRequestMixin(request)
data = request_mixin.data
print(data)  # e.g., {'session_key': 'abc123', ...}
Returns:

The request body parsed as json or yaml, an empty dict if the body is empty or can’t be parsed, or None if there is no request or the request is not qualified.

property domain: str | None[source]

Extract the domain, the host and port, from the URL.

For example, this url returns 'hr.3141-5926-5359.alpha.api.example.com':

https://hr.3141-5926-5359.alpha.api.example.com/llm-client/
Returns:

The domain, or None if there is no request or url.

eval_llmclient_url()[source]

Resolve the account and user of a request to a deployed LLMClient’s own host.

For a named url, e.g. http://example.3141-5926-5359.api.localhost:9357/, the account is loaded from the url’s account number when account is not already set, and then, when user is not set, the user becomes that account’s admin user.

Other llmclient urls, the smarter api and cli api urls, need no follow up here. A request that is not an llmclient request is left as it is.

Return type:

None

Returns:

None. Sets account and user as a side effect.

find_session_key()[source]

Return the unique prompt session key value for this request.

The session_key is managed by the /config/ endpoint for the llmclient. 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 llmclient session for the device.

For subsequent 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"}.

The session key is looked for in these places, in this order, and the first well formed one (see accepted_session_key()) is returned:

  • The URL, e.g. http://localhost:9357/workbench/example/config/?session_key=1aeee4c1f183354247f43f80261573da921b0167c7c843b28afd3cb5ebba0d9a

  • The request body: {'session_key': '1aeee4c1f183354247f43f80261573da921b0167c7c843b28afd3cb5ebba0d9a'}

  • A cookie

  • The request’s GET parameters

Return type:

str | None

Returns:

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

generate_session_key()[source]

Generate a new, random session_key.

Return type:

str

Returns:

A random 64 character session key.

generate_smarter_request_id()[source]

Generate a unique identifier for the request.

Return type:

str

Returns:

A random uuid4, as 32 hexadecimal characters.

Retrieve the value of a cookie from the request object.

Parameters:

cookie_name (str) – Name of the cookie to retrieve.

Return type:

str | None

Returns:

Value of the cookie, or None if there is no request or 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()
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.

Example:

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

The client’s IP address, the placeholder "ip_address" if REMOTE_ADDR is missing or empty, or None if the request has no META dictionary.

property is_authenticated: bool

Return True if the request’s user is authenticated.

Returns:

The request user’s is_authenticated, or False if there is no request or user, or checking it raises.

property is_config: bool[source]

Return 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:llmclient_id>/prompt/config/
http://example.api.localhost:9357/config
Returns:

True if the URL is an llmclient url whose path includes config, otherwise False.

property is_dashboard: bool[source]

Return True if the URL resolves to a dashboard endpoint.

Returns:

True if the URL’s path ends with /dashboard/, otherwise False.

property is_default_domain: bool[source]

Return True if the URL is on the default api domain for the environment, e.g. api.alpha.platform.smarter.sh.

Returns:

True if the URL contains the environment’s api domain, otherwise False.

property is_environment_root_domain: bool[source]

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

Returns:

True if the URL’s host is the environment’s platform domain and its path is /, otherwise False.

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.

Return type:

bool

Returns:

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

property is_llmclient: bool[source]

Return True if the URL resolves to an llmclient endpoint.

Conditions are checked in a lazy sequence to avoid unnecessary processing. The order matters: is_llmclient_named_url loads the url’s account as a side effect.

Examples:

http://localhost:9357/api/v1/prompt/1/prompt/
http://localhost:9357/api/v1/cli/prompt/example/
http://example.3141-5926-5359.api.localhost:9357/
http://localhost:9357/api/v1/llm-clients/1556/prompt/
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/
Returns:

True if the request is qualified and its URL is a named, sandbox, smarter api or cli api llmclient url, otherwise False.

property is_llmclient_cli_api_url: bool[source]

Return True if the URL is of the form http://localhost:9357/api/v1/cli/prompt/example/.

The expected path parts are:

['api', 'v1', 'cli', 'prompt', 'example']
Returns:

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

property is_llmclient_named_url: bool[source]

Return True if the url is a deployed LLMClient’s own host.

These are the forms of the url:

https://example-username.3141-5926-5359.api.example.com/
http://example-username.3141-5926-5359.api.localhost:9357/
http://example-username.3141-5926-5359.api.localhost:9357/config/
http://example-username.3141-5926-5359.api.localhost:9357/prompt/
http://example-username.3141-5926-5359.api.localhost:9357/jsi18n/

As a side effect, when the url has an account number and account is not set, the account is loaded from the account number.

Returns:

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

property is_llmclient_sandbox_url: bool[source]

Return True if the URL is an llmclient sandbox endpoint.

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/
Returns:

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

property is_llmclient_smarter_api_url: bool[source]

Return True if the URL is a smarter api llmclient endpoint.

These are the forms of the url:

http://localhost:9357/api/v1/llm-clients/32/config/

http://localhost:9357/api/v1/workbench/1/prompt/
path_parts: ['api', 'v1', 'workbench', '<int:pk>', 'prompt']

http://localhost:9357/api/v1/llm-clients/1556/prompt/
path_parts: ['api', 'v1', 'llm-clients', '<int:pk>', 'prompt']

http://localhost:9357/api/v1/llm-clients/rMTAwMDAwNwx/prompt/
path_parts: ['api', 'v1', 'llm-clients', '<str:hashed_id>', 'prompt']
Returns:

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

property is_smarter_api: bool[source]

Return True if the URL is of the form http://localhost:9357/api/v1/.

Examples:

path_parts: ['api', 'v1', 'llm-clients', '1', 'prompt']
http://api.localhost:9357/
Returns:

True if api is a segment of the URL’s path or a label of its host, otherwise False.

property is_workbench: bool[source]

Return True if the URL resolves to a workbench endpoint.

Returns:

True if the URL’s path ends with /workbench/, otherwise False.

log_ready_status()[source]

Log the ready status of the instance, at INFO.

Return type:

None

Returns:

None.

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.

Example:

request_mixin = SmarterRequestMixin(request)
params = request_mixin.params
print(params)  # e.g., {'session_key': 'abc123', 'uid': 'xyz'}
Returns:

QueryDict containing the query string parameters.

property parsed_url: ParseResult | None

Expose the private ParseResult URL object as a public property.

Example:

request_mixin = SmarterRequestMixin(request)
parsed = request_mixin.parsed_url
print(parsed.netloc)  # e.g., 'example.com'
Returns:

The parsed URL, or None if there is no url.

property path: str | None[source]

Extract the path from the URL.

For example, this url returns '/llm-client/':

https://hr.3141-5926-5359.alpha.api.example.com/llm-client/
Returns:

The path, / for an empty path, or None if there is no request or url.

property qualified_request: bool[source]

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 (see STATIC_FILE_EXTENSIONS).

Example:

# True case: a valid llmclient request
request_mixin = SmarterRequestMixin(request)
if request_mixin.qualified_request:
    print("This is a qualified llmclient 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.")
Returns:

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

property required_cache_key: str

Return cache_key, for code that reads or writes the cache with it.

cache_key is None only without a request, which a view always has. Rather than read or write the cache under the key None, which every such caller would share, this raises.

Returns:

The cache key.

Raises:

SmarterValueError – If there is no request, so no cache key.

property root_domain: str | None[source]

Extract the root domain from the URL.

Example:

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

The root domain, or None if not found.

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 request (see find_session_key()). Barring that, it generates a new one.

Example:

request_mixin = SmarterRequestMixin(request)
session_key = request_mixin.session_key
print(session_key)  # e.g., '38486326c21ef4bcb7e7bc305bdb062f16ee97ed8d2462dedb4565c860cd8ecc'
Returns:

The session key as a string.

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, or a DRF request, whose wrapped Django request is flagged too.

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

Return type:

HttpRequest

Returns:

The modified request object.

Raises:

SmarterValueError – If request is not a Django HttpRequest or a DRF Request.

property smarter_capabilities: str | None

Get the smarter capabilities from the request.

This property checks for the “X-Smarter-Capabilities” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
capabilities = request_mixin.smarter_capabilities
Returns:

The value of the “X-Smarter-Capabilities” header as a string, or None if not present.

property smarter_client: str | None

Get the smarter client name from the request.

This property checks for the “X-Smarter-Client” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
client_name = request_mixin.smarter_client
Returns:

The value of the “X-Smarter-Client” header as a string, or None if not present.

property smarter_client_type: str | None

Get the smarter client type from the request.

This property checks for the “X-Smarter-ClientType” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
client_type = request_mixin.smarter_client_type
Returns:

The value of the “X-Smarter-ClientType” header as a string, or None if not present.

property smarter_client_version: str | None

Get the smarter client version from the request.

This property checks for the “X-Smarter-ClientVersion” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
client_version = request_mixin.smarter_client_version
Returns:

The value of the “X-Smarter-ClientVersion” header as a string, or None if not present.

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_id: str | None

Get the smarter request ID from the request.

This property checks for the “X-Smarter-RequestId” header in the request headers.

Example:

request_mixin = SmarterRequestMixin(request)
request_id = request_mixin.smarter_request_id
Returns:

The value of the “X-Smarter-RequestId” header as a string, or None if not present.

property smarter_request_llmclient_id: int | None[source]

Extract the llmclient id from the URL.

For example, for this url the property decodes the hashed id rMTAwMDAyNwx into the llmclient’s id:

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

The llmclient id as an integer, or None if not found. A named url and a sandbox url without a hashed id return None.

property smarter_request_llmclient_name: str | None[source]

Extract the llmclient name from the URL.

For example, this url returns "example":

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

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

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

Initialize the SmarterRequestMixin with the request and user.

A view calls it from its own setup(), after Django’s View.setup(). It isn’t named setup(), because Django’s takes the request positionally, and a view inherits both. 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 (HttpRequest | None) – The HTTP request object to be associated with this mixin instance.

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

  • kwargs – Keyword arguments passed to the setup method.

Return type:

None

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]

Extract the subdomain from the URL.

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/'
Returns:

The subdomain, or None if not found.

property timestamp: datetime

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

Example:

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

The time at which this object was instantiated.

to_json()[source]

Serialize the object.

Return type:

dict[str, Any]

Returns:

A dictionary representation of the object, with the auth header and api token masked.

property uid: str | None

Unique identifier for the client.

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

Example:

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

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

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, when there is an account

  • URL

  • User agent

  • IP address

Example:

request_mixin = SmarterRequestMixin(request)
unique_str = request_mixin.unique_client_string
print(unique_str)
Returns:

A unique string representing the client and request context.

property url: str | None

The string representation of the ParseResult object stored in _parsed_url.

Example:

request_mixin = SmarterRequestMixin(request)
url_str = request_mixin.url
print(url_str)  # e.g., 'https://example.com/path/'
Returns:

The URL as a string.

property url_account_number: str | None

Extract the account number from the URL, using SmarterValidator.VALID_ACCOUNT_NUMBER_PATTERN.

For example, this url returns "3141-5926-5359":

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

The account number as a string, or None if there is no request, the request is not qualified, or the url has no account number.

property url_path_parts: list[str][source]

Extract the path parts from the URL.

Example:

request_mixin = SmarterRequestMixin(request)
parts = request_mixin.url_path_parts
print(parts)  # e.g., ['api', 'v1', 'workbench', '1', 'prompt']
Returns:

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

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.

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)...'
Returns:

The client’s user agent string, the placeholder "user_agent" if the header is missing, or None if the request has no META dictionary.