API Connection Broker
- class smarter.apps.connection.manifest.brokers.api_connection.SAMApiConnectionBroker(*args, **kwargs)[source]
Smarter API ApiConnection Manifest Broker.
This class is responsible for loading, validating, and parsing Smarter API YAML ApiConnection manifests, and initializing the corresponding Pydantic model. It provides generic services for ApiConnection objects, including instantiation, creation, update, and deletion.
- Parameters:
loader (Optional[ManifestLoader]) – Manifest loader providing manifest data.
account (Account) – The account context for the connection.
user_profile (UserProfile) – The user profile associated with the connection.
See also
smarter.apps.connection.manifest.models.api_connection.model.SAMApiConnectionsmarter.apps.connection.models.ApiConnectionsmarter.apps.connection.serializers.ApiConnectionSerializersmarter.apps.connection.manifest.brokers.SAMConnectionBrokerErrorExample usage:
broker = SAMApiConnectionBroker(loader=my_loader, account=my_account, user_profile=my_profile) manifest = broker.manifest orm_data = broker.manifest_to_django_orm()
- property ORMMetaModelClass: Type[ApiConnection]
Return the Django ORM meta model class for the broker.
- Returns:
The Django ORM meta model class definition for the broker.
- Return type:
Type[ApiConnection]
- property ORMModelClass: Type[ApiConnection]
Return the Django ORM model class for ApiConnection.
This property provides the class object used for persistent storage and manipulation of API connection data in the database. It is useful for type checking, introspection, and for creating or querying ApiConnection instances.
- Returns:
The Django ORM model class for API connections.
- Return type:
Type[smarter.apps.connection.models.ApiConnection]
See also
smarter.apps.connection.manifest.models.api_connection.spec.ApiConnectionSAMApiConnectionBroker.SerializerClass()SAMApiConnectionBroker.manifest()Example usage:
model_cls = broker.ORMModelClass all_connections = model_cls.objects.all()
- property SAMModelClass: Type[SAMApiConnection]
Return the Pydantic model class for the broker.
- Returns:
The Pydantic model class definition for the broker.
- Return type:
Type[SAMApiConnection]
- property SerializerClass: Type[ApiConnectionSerializer]
Return the SerializerClass class for the broker.
This property provides the SerializerClass used to convert ApiConnection model instances to and from native Python datatypes, enabling validation and serialization for API responses and internal processing.
- Returns:
The SerializerClass class for ApiConnection objects.
- Return type:
Type[ApiConnectionSerializer]
See also
ApiConnectionSerializerApiConnectionSAMApiConnectionBroker.manifest()SAMApiConnectionBroker.manifest_to_django_orm()Example usage:
serializer_cls = broker.SerializerClass SerializerClass = serializer_cls(api_connection_instance) data = SerializerClass.data
- property abstract_broker_logger_cache_invalidation_prefix: str
Return the logger prefix for the AbstractBroker cache invalidation.
- Returns:
The logger prefix for the AbstractBroker.
- Return type:
- property abstract_broker_logger_prefix: str
Return the logger prefix for the AbstractBroker.
- Returns:
The logger prefix for the AbstractBroker.
- Return type:
- property abstract_broker_ready_state: str
Return a string representation of the AbstractBroker’s ready state.
- Returns:
“READY” if the AbstractBroker is ready, otherwise “NOT_READY”.
- Return type:
- property account: Account | None
Returns the account for the current user.
Handle lazy instantiation from user or user_profile.
- Returns:
The account for the current user.
- Return type:
Account or None
- property account_number: str | None
A helper function to get the account number from the account.
- Returns:
The account number for the current account.
- Return type:
str or None
- property am_ready: bool
Returns True if the AccountMixin is am_ready to be used.
This is a convenience property that checks if the account and user are initialized. AccountMixin is considered am_ready if: - self.user is an instance of User - self.user_profile is an instance of UserProfile - self.account is an instance of Account
- Returns:
True if the AccountMixin is am_ready to be used.
- Return type:
- property api_key_secret: Secret | None
Return the api_key secret for the ApiConnection.
This property retrieves the Django ORM Secret instance associated with the API key for the current connection. It resolves the secret either from the manifest or from the existing database record, depending on initialization context.
- Returns:
The Secret object representing the API key, or None if not found.
- Return type:
Optional[Secret]
Attention
If the secret cannot be found, a warning is logged and None is returned.
See also
SecretSAMApiConnectionBroker.manifest()SAMApiConnectionBroker.connection()Example usage:
api_key_secret = broker.api_key_secret if api_key_secret: print(api_key_secret.value)
- property api_subdomain: str | None
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
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 api_version: str
The API version of the manifest.
- Returns:
The API version of the manifest.
- Return type:
Optional[str]
- apply(request, *args, **kwargs)[source]
Apply the manifest.
Copy the manifest data to the Django ORM model and save the model to the database.
This method calls
super().apply()to ensure that the manifest is loaded and validated before applying the manifest to the Django ORM model.Note that there are fields included in the manifest that are not editable and are therefore removed from the Django ORM model dict prior to attempting the
save()command. These fields are defined in thereadonly_fieldslist.Note
tags are handled separately because they are of type TaggableManager and require a different method to set them.
Example manifest structure:
{ "apiVersion": "smarter.sh/v1", # read only "kind": "ApiConnection", # read only "metadata": { # updated in super().apply() "name": "testf232a0619cb19da0", "description": "new description", "version": "1.0.0" }, "spec": { # updated here. "connection": { "kind": "ApiConnection", "version": "1.0.0", "account": "2194-1233-0815", "baseUrl": "http://localhost:9357/api/v1/cli/example_manifest/connection/", "apiKey": "testf232a0619cb19da0", "authMethod": "basic", "timeout": 30, "proxyProtocol": "http", "proxyHost": null, "proxyPort": null, "proxyUsername": null, "proxyPassword": null } }, "status": { # read only "connection_string": "http://localhost:9357/api/v1/cli/example_manifest/connection/ (Auth: ******)", "is_valid": false } }
- Parameters:
request (
HttpRequest) – Django HTTP request object.args – Additional positional arguments.
kwargs – Additional keyword arguments.
- Returns:
JSON response indicating success and the updated manifest data.
- Return type:
- Raises:
SAMConnectionBrokerError – If an error occurs during update or save.
- 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.
- bool_environment_variable(var_name, default=False)
Retrieves a boolean value from an environment variable.
This method checks the specified environment variable and returns its value as a boolean. It recognizes common truthy values such as “true”, “1”, “yes”, and “on”. If the variable is not set or cannot be interpreted as a boolean, it returns the provided default value.
- cache_invalidations()[source]
Invalidate any relevant caches when the manifest or connection data changes.
- Return type:
- property cache_key: str | None
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...'
- clean_cli_param(param, param_name='unknown', url=None)
Remove any leading or trailing whitespace from the param.
Ensure that the param is a string.
Return the cleaned param.
- clear_cached_properties()
Clears all cached properties in this mixin.
- property connection: ApiConnection | None
Return the Django ORM ApiConnection instance for this broker.
This property retrieves the current ApiConnection object from the database using the account and name. If the connection does not exist, it attempts to create one from the manifest data. The returned object represents the persistent state of the API connection.
- Returns:
The ApiConnection ORM instance, or None if not found or not created.
- Return type:
Optional[smarter.apps.connection.models.ApiConnection]
Attention
If the connection cannot be found or created, an error is logged and None is returned.
See also
ApiConnectionSAMApiConnectionBroker.manifest()SAMApiConnectionBroker.manifest_to_django_orm()SAMApiConnectionBroker.api_key_secret()SAMApiConnectionBroker.proxy_password_secret()Example usage:
connection = broker.connection if connection: print(connection.base_url) connection.timeout = 60 connection.save()
- connection_init()[source]
Initialize the connection-related properties of the broker.
This method resets the internal state of the broker related to the ApiConnection instance and its associated secrets. It is useful when reloading or refreshing the connection data to ensure that stale references are cleared.
- Returns:
None
- Return type:
See also
SAMApiConnectionBroker.connection()SAMApiConnectionBroker.api_key_secret()SAMApiConnectionBroker.proxy_password_secret()Example usage:
broker.connection_init() connection = broker.connection
- property created: bool
Return True if the broker was created successfully.
- Returns:
True if the broker was created successfully.
- Return type:
- property data: dict | list | str | None
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', ...}
- data_to_dict(data)
Converts data to a dictionary, handling different types of input.
This method accepts either a dictionary or a string. If a string is provided, it will attempt to parse it as JSON first, and if that fails, as YAML. If parsing fails or the data type is unsupported, a SmarterValueError is raised.
- delete(request, *args, **kwargs)[source]
Delete the current API connection and return a JSON response indicating the result.
This method attempts to delete the associated ApiConnection object from the database. If successful, it returns an empty JSON response. If no connection exists, or if an error occurs during deletion, an appropriate exception is raised.
- Parameters:
request (
HttpRequest) – Django HTTP request object.args – Additional positional arguments.
kwargs – Additional keyword arguments.
- Returns:
JSON response indicating deletion success.
- Return type:
- Raises:
SAMBrokerErrorNotReady – If no connection is found to delete.
SAMConnectionBrokerError – If an error occurs during deletion.
Error
Any exception during deletion is wrapped and raised as
SAMConnectionBrokerError.See also
ApiConnectionSmarterJournaledJsonResponseSAMApiConnectionBroker.connection()Example usage:
response = broker.delete(request) print(response.data)
- deploy(request, *args, **kwargs)[source]
Handle deploy operations for the API connection broker.
This is not implemented and will always raise a SAMBrokerErrorNotImplemented exception.
- Parameters:
request (
HttpRequest) – Django HTTP request object.args – Additional positional arguments.
kwargs – Additional keyword arguments.
- Returns:
SAMBrokerErrorNotImplemented. This method always raises an exception.
- Return type:
- describe(request, *args, **kwargs)[source]
Return a JSON response containing the manifest data for the current API connection.
This method serializes the manifest and connection details, including metadata, specification, and status, into a structured JSON response. It validates the connection and includes relevant fields such as connection string and validity status.
- Parameters:
request (
HttpRequest) – Django HTTP request object.args – Additional positional arguments.
kwargs – Additional keyword arguments.
- Returns:
JSON response with manifest data.
- Return type:
- Raises:
SAMBrokerErrorNotReady – If no connection is found
SAMConnectionBrokerError – if serialization or validation fails.
See also
SAMApiConnectionApiConnectionSmarterJournaledJsonResponseSAMApiConnectionBroker.connection()Example usage:
response = broker.describe(request) print(response.data)
- deserves_amnesty(slug)
Determines if a given URL deserves amnesty based on the amnesty URLs list.
This excuses certain endpoints (like health checks) from select middleware checks.
- dict_is_contained_in(dict1, dict2)
Checks if one dictionary is contained within another.
This method determines if all key-value pairs in dict1 are present in dict2.
- dict_is_subset(small, big)
Checks if one dictionary is a subset of another.
This method determines if all key-value pairs in the small dictionary are present in the big dictionary. It returns True if the small dictionary is a subset of the big dictionary, and False otherwise.
- property domain: str | None
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()
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.
- example_manifest(request, *args, **kwargs)[source]
Return an example ApiConnection manifest.
This method generates and returns a sample manifest for an ApiConnection, including all required fields and example values for authentication, connection, and metadata. The manifest is validated using the Pydantic model and returned as a JSON response.
- Parameters:
request (
HttpRequest) – Django HTTP request object.args – Additional positional arguments.
kwargs – Additional keyword arguments.
- Returns:
JSON response containing the example manifest.
- Return type:
See also
SAMApiConnectionApiConnectionApiConnectionSerializerAuthMethodsSAMKeysSAMMetadataKeysSAMApiConnectionSpecConnectionKeysSmarterJournalCliCommandsExample usage:
response = broker.example_manifest(request) print(response.data)
- find_session_key()
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:
URL parameter: http://localhost:9357/workbench/example/config/?session_key=1aeee4c1f183354247f43f80261573da921b0167c7c843b28afd3cb5ebba0d9a
Request JSON body: {‘session_key’: ‘1aeee4c1f183354247f43f80261573da921b0167c7c843b28afd3cb5ebba0d9a’}
Request header: {‘session_key’: ‘1aeee4c1f183354247f43f80261573da921b0167c7c843b28afd3cb5ebba0d9a’}
Cookie
A session_key generator
- property formatted_class_name: str
Returns the formatted class name for logging purposes.
This property generates a human-readable class name string for use in log messages, making it easier to identify the source of log entries. It appends the specific broker class to the parent class name for clarity.
- Returns:
Formatted class name string for logging.
- Return type:
Important
Use this property in log statements to improve traceability and debugging.
See also
SAMApiConnectionBroker.SerializerClass()SAMApiConnectionBroker.manifest()SAMApiConnectionBroker.ORMModelClass()Example usage:
logger.info("%s: operation started", broker.formatted_class_name)
- property formatted_class_name_cache_invalidations: str
Return the logger prefix for the AbstractBroker cache invalidations.
- Returns:
The logger prefix for the AbstractBroker cache invalidations.
- Return type:
- formatted_json(json_obj)
Formats a JSON object as a pretty-printed string with ANSI color codes for logging.
- property formatted_state_not_ready: str
Returns the not-ready state formatted for logging.
- Returns:
The formatted not-ready state as a string.
- Return type:
- property formatted_state_ready: str
Returns the readiness state formatted for logging.
- Returns:
The formatted readiness state as a string.
- Return type:
- formatted_text(text, color_code='\\x1b[1;31m')
Formats text with ANSI color codes for logging.
- formatted_text_blue(text)
Formats text in bold dark blue for logging.
- formatted_text_green(text)
Formats text in bright green for logging.
- formatted_text_red(text)
Formats text in dark red for logging.
- generate_fernet_encryption_key()
Generates a Fernet encryption key.
This method creates a new Fernet encryption key, which can be used for secure encryption and decryption of data. The generated key is returned as a URL-safe base64-encoded string.
- Returns:
A new Fernet encryption key.
- Return type:
- generate_session_key()
Generate a session_key based on a unique string and the current datetime.
- Return type:
- Returns:
A unique session key string.
- get(request, *args, **kwargs)[source]
Retrieve a list of ApiConnection objects as a journaled JSON response.
This method queries the database for ApiConnection instances matching the current account and optional name filter, serializes each result, and returns a structured JSON response including metadata, item count, and model titles.
- Parameters:
request (
HttpRequest) – Django HTTP request object.args – Additional positional arguments.
kwargs (dict) – Optional keyword arguments, such as name to filter connections.
- Returns:
Journaled JSON response containing serialized ApiConnection data.
- Return type:
See also
ApiConnectionApiConnectionSerializerSmarterJournaledJsonResponseSAMApiConnectionBroker.SerializerClass()Example usage:
response = broker.get(request) print(response.data) # Filter by name response = broker.get(request, name="my_connection") print(response.data)
- get_cookie_value(cookie_name)
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
- get_model_titles(serializer)
For tabular output from get() implementations.
Returns a list of field names and types from the Django model serializer.
- get_or_create_secret(user_profile, name, value=None, description=None, expiration=None)
Get or create a Smarter Secret in the database.
This is used to store secrets that are passed in the manifest.
- Parameters:
- Returns:
The created or retrieved Secret object.
- Return type:
- get_readonly_csv_file(file_path)
Retrieves a read-only file object for a CSV file.
This method opens the specified CSV file in read-only mode and returns a file object that can be used to read its contents. It ensures that the file is not modified during the reading process.
- Parameters:
file_path (
str) – The path to the CSV file to open.- Returns:
A read-only file object for the specified CSV file.
- Return type:
file
- get_readonly_yaml_file(file_path)
Retrieves a read-only file object for a YAML file.
This method opens the specified YAML file in read-only mode and returns a file object that can be used to read its contents. It ensures that the file is not modified during the reading process.
- Parameters:
file_path (
str) – The path to the YAML file to open.- Returns:
A read-only file object for the specified YAML file.
- Return type:
file
- property health_check_urls: list[str]
Returns a list of URL paths that are considered health check endpoints.
- init(*args, **kwargs)
An optional method that can be called after initialization to perform any additional setup.
This is separate from __init__ to allow for more flexible initialization patterns.
- Parameters:
args – Positional arguments passed to the init method.
kwargs – Keyword arguments passed to the init method.
- Return type:
- Returns:
None
- invalidate_cached_properties()
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
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_config: bool
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:
- property is_dashboard: bool
Returns True if the URL resolves to a dashboard endpoint.
- Returns:
True if the URL is a dashboard endpoint, otherwise False.
- Return type:
- property is_default_domain: bool
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
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:
- is_internal_api_request(request)
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:
- property is_llm_client: bool
Returns True if the URL resolves to an llm_client endpoint.
Conditions are checked in a lazy sequence to avoid unnecessary processing.
Examples
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 URL is an llm_client endpoint, otherwise False.
- Return type:
- property is_llm_client_cli_api_url: bool
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:
- Type:
Returns True if the URL is of the form http
- Type:
//localhost
- property is_llm_client_named_url: bool
Returns True if the url is of the form:
- Returns:
True if the URL matches the named llm_client pattern, otherwise False.
- Return type:
- property is_llm_client_sandbox_url: bool
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:
- property is_llm_client_smarter_api_url: bool
Returns True if the URL is of the form:
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 llm_client endpoint, otherwise False.
- Return type:
- property is_ready_abstract_broker: bool
Return True if the AbstractBroker is ready for operations.
An AbstractBroker is considered ready if: - The AccountMixin is ready. - The RequestMixin is ready. - either a valid manifest is loaded or a ready SAMLoader is present.
- Returns:
True if the AbstractBroker is ready for operations.
- Return type:
- property is_smarter_api: bool
9357/api/v1/.
Examples
path_parts: [‘api’, ‘v1’, ‘llm-clients’, ‘1’, ‘prompt’]
- Returns:
True if the URL matches the smarter API pattern, otherwise False.
- Return type:
- Type:
Returns True if the URL is of the form http
- Type:
//localhost
- property is_workbench: bool
Returns True if the URL resolves to a workbench endpoint.
- Returns:
True if the URL is a workbench endpoint, otherwise False.
- Return type:
- json_response_err(command, e)
Return a structured error response that can be unpacked and rendered.
by the cli in a variety of formats.
- Parameters:
command (
SmarterJournalCliCommands) – The command that was executed.e (
Exception) – The exception that was raised.
- Returns:
A SmarterJournaledJsonResponse containing the error response.
- Return type:
- json_response_err_notfound(command, message=None)
Return a common not found response.
- Parameters:
command (
SmarterJournalCliCommands) – The command that was executed.message (
Optional[str]) – An optional custom message to include in the response.
- Returns:
A SmarterJournaledJsonResponse containing the not found response.
- Return type:
- json_response_err_notimplemented(command)
Return a common not implemented response.
- Parameters:
command (
SmarterJournalCliCommands) – The command that was executed.- Returns:
A SmarterJournaledJsonResponse containing the not implemented response.
- Return type:
- json_response_err_notready(command)
Return a common not ready response.
- Parameters:
command (
SmarterJournalCliCommands) – The command that was executed.- Returns:
A SmarterJournaledJsonResponse containing the not ready response.
- Return type:
- json_response_err_readonly(command)
Return a common read-only response.
- Parameters:
command (
SmarterJournalCliCommands) – The command that was executed.- Returns:
A SmarterJournaledJsonResponse containing the read-only response.
- Return type:
- json_response_ok(command, data=None, message=None)
Return a common success response.
- Parameters:
command (
SmarterJournalCliCommands) – The command that was executed.message (
Optional[str]) – An optional message to include in the response.
- Returns:
A SmarterJournaledJsonResponse containing the success response.
- Return type:
- kind_setter(value)
Set the kind of manifest.
Validates that the kind is a valid SmarterJournalThings value.
- Raises:
SmarterValueError – If the kind is not valid.
- Parameters:
value (
str) – The kind of manifest to set.
- property loader: SAMLoader | None
The SAMLoader instance for this broker.
- Returns:
The SAMLoader instance for this broker.
- Return type:
Optional[SAMLoader]
- log_abstract_broker_state()
Log the current state of the AbstractBroker instance for debugging purposes.
- Returns:
None
- log_ready_status()
Logs the ready status of the view.
- logs(request, *args, **kwargs)[source]
Handle logs operations for the API connection broker.
This is not implemented and will always raise a SAMBrokerErrorNotImplemented exception.
- Parameters:
request (
HttpRequest) – Django HTTP request object.args – Additional positional arguments.
kwargs – Additional keyword arguments.
- Returns:
SAMBrokerErrorNotImplemented. This method always raises an exception.
- Return type:
- property manifest: SAMApiConnection | None
Returns the manifest as a Pydantic model representing the Smarter API ApiConnection manifest.
This property initializes and returns a
SAMApiConnectionPydantic model using data loaded from the manifest loader. The manifest loader provides the manifest’s API version, kind, metadata, spec, and status, which are passed to the model constructor.The top-level manifest model must be explicitly initialized, while child models (such as metadata, spec, and status) are automatically cascade-initialized by Pydantic, passing the relevant data to each child’s constructor.
If the loader’s manifest kind does not match the expected kind, a warning is logged and the manifest is not initialized.
- Returns:
The manifest as a
SAMApiConnectionPydantic model, orNoneif not initialized.- Return type:
Optional[SAMApiConnection]
- manifest_setter(value)
Set the manifest for the broker and override all AbstractBroker.
model properties based on the manifest data.
- Parameters:
value (
Union[AbstractSAMBase,dict[str,Any],None]) – The manifest to set, either as a Pydantic model or a dictionary.
- manifest_to_django_orm()[source]
Transform the Smarter API User manifest into a Django ORM model.
This method converts the validated manifest data into a dictionary suitable for creating or updating a Django ORM ApiConnection instance. It handles field mapping, type conversion, and secret resolution for sensitive fields such as API keys and proxy passwords.
- Returns:
Dictionary of ORM-compatible fields for an ApiConnection model.
- Return type:
Note
The returned dictionary includes all required fields for ORM persistence, with secrets resolved to their database IDs.
The method automatically converts camelCase keys to snake_case for Django compatibility.
- Raises:
SAMConnectionBrokerError – If the manifest or its spec is missing or malformed
See also
ApiConnectionSAMApiConnectionBroker.manifest()SAMApiConnectionBroker.SerializerClass()Example usage:
orm_data = broker.manifest_to_django_orm() connection = ApiConnection(**orm_data) connection.save()
- mask_string(string='', mask_char='*', mask_length=4, string_length=8)
Masks a string for secure logging.
This utility function masks all but the last unmasked_chars characters of the input string, replacing them with asterisks. It is useful for logging sensitive information like API keys or passwords.
- property name: str | None
Retrieve the unique name identifier for the LLMClient instance managed by this broker.
This property accesses the name used to distinguish the LLMClient within the database and across the Smarter platform. The name is first returned from an internal cache if available. If not cached, and if a manifest is present, the name is extracted from the manifest’s metadata and stored for subsequent access.
The name is essential for database queries, model lookups, and for associating related resources such as API keys, plugins, and functions with the correct LLMClient instance.
- Returns:
The name of the LLMClient as a string, or
Noneif the name is not set or cannot be determined.- Return type:
Optional[str]
Note
The name property is a critical identifier used throughout the broker to ensure correct mapping between manifest data and persistent application state.
- name_cached_property_setter(value)
A workaround to the limitation that you cannot use both @cached_property and.
a setter for the same attribute name (name). In Python, you cannot have a property (or cached_property) and a setter with the same name unless you use the @property decorator (not @cached_property).
We need the cached_property so that the lazy evaluation of the name only happens once, and subsequent accesses return the cached value for performance. However, we also need to be able to set the name explicitly in some cases,
- Parameters:
value (
str) – The name to set for the manifest.
- property orm_instance: MetaDataWithOwnershipModel | None
Return the Django ORM model instance for the broker.
There are multiple strategies to retrieve the ORM instance:
If the instance is already cached in self._orm_instance, return it.
If the broker is not ready or the name is not set, log a warning and return None.
Attempt to retrieve the ORM instance using the user_profile and name. If not found, attempt to retrieve using the admin user_profile for the account. If still not found, attempt to retrieve using the Smarter platform admin user_profile.
Cache the retrieved instance for future access.
- Returns:
The Django ORM model instance for the broker.
- Return type:
Optional[MetaDataWithOwnershipModel]
- property orm_meta_instance: MetaDataWithOwnershipModel | None
Return the Django ORM meta model instance for the broker.
This is a cached property that retrieves the ORM meta instance based on the user_profile and kind. For simple relational models, the ORM meta class is the same as the ORM class, and the meta instance is the same as the ORM instance.
This property is used for resolving more complex ORM relationships where the name and user_profile fields are stored in a parent Django model.
- orm_meta_instance_setter()
Initialize the ORM metadata for the broker instance.
This method attempts to initialize the ORM metadata by querying the ORMMetaModelClass using the broker’s name and user_profile. If the ORM metadata is successfully retrieved, it is stored in the orm_meta_instance attribute. If the ORM metadata does not exist or an error occurs, the _orm_instance attribute is set to None.
- Return type:
- Returns:
None
- property params: QueryDict | None
Return the query parameters from the url of the request.
there are two scenarios to consider: 1. the request is a Django HttpRequest object (the expected case) 2. the request is a Python PreparedRequest object (the edge case)
- Returns:
The query parameters from the url of the request.
- Return type:
Optional[QueryDict]
- 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
Extracts the path from the URL.
- Returns:
Optional[str]: The path as a string, or None if not found.
Examples
https://hr.3141-5926-5359.alpha.api.example.com/llm-client/ returns ‘/llm-client/’
- prompt(request, *args, **kwargs)[source]
Handle prompt operations for the API connection broker.
This method is intended to process prompt requests using the manifest broker. Currently, it is not implemented and will always raise a SAMBrokerErrorNotImplemented exception. This method is not implemented. Any invocation will result in an error.
- Parameters:
request (
HttpRequest) – Django HTTP request object.args – Additional positional arguments.
kwargs – Additional keyword arguments.
- Returns:
SAMBrokerErrorNotImplemented. This method always raises an exception.
- Return type:
See also
SAMApiConnectionBrokerSmarterJournalCliCommandsSAMBrokerErrorNotImplementedExample usage:
try: response = broker.prompt(request) except SAMBrokerErrorNotImplemented as e: print("Prompt not implemented:", e)
- property proxy_password_secret: Secret | None
Return the proxy password secret for the ApiConnection.
This property retrieves the Django ORM Secret instance associated with the proxy password for the current connection. It resolves the secret either from the manifest or from the existing database record, depending on initialization context.
- Returns:
The Secret object representing the proxy password, or None if not found.
- Return type:
Optional[Secret]
Attention
If the secret cannot be found, a warning is logged and None is returned.
See also
SecretSAMApiConnectionBroker.manifest()SAMApiConnectionBroker.connection()Example usage:
proxy_secret = broker.proxy_password_secret if proxy_secret: print(proxy_secret.value)
- 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 ready: bool
Check if the broker is ready for operations.
This property determines whether the broker has been properly initialized and is ready to perform its functions. A broker is considered ready if it has a valid manifest loaded, either from raw data, a loader, or existing Django ORM models.
- Returns:
Trueif the broker is ready,Falseotherwise.- Return type:
- property ready_state: str
Return a string representation of the broker’s ready state.
- Returns:
“READY” if the broker is ready, otherwise “NOT_READY”.
- Return type:
- recursive_sort_dict(data)
Recursively sorts a dictionary by its keys.
This method takes a dictionary and returns a new dictionary with all keys sorted in ascending order. If any values are also dictionaries, they will be sorted recursively as well.
- property request: HttpRequest | None
Return the request object.
- Returns:
The request object.
- Return type:
Optional[HttpRequest]
- rfc1034_compliant_str(name)
Converts a string to an RFC 1034 compliant format.
This method takes a string and converts it to a format that complies with RFC 1034, which is commonly used for domain names. It replaces invalid characters with hyphens and ensures the resulting string is lowercase.
- rfc1034_compliant_to_snake(name)
Converts an RFC 1034 compliant string to snake_case.
This method takes a string in RFC 1034 compliant format and converts it to snake_case. It replaces hyphens with underscores and ensures the resulting string is lowercase.
- property root_domain: str | None
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'
- sam_connection_metadata()
Return the common connection metadata from the manifest.
- Returns:
The connection metadata.
- Return type:
- Raises:
NotImplementedError – If the manifest does not have connection metadata.
See also
SAMConnectionCommonMetadataExample usage:
metadata = broker.sam_connection_metadata()
- sam_connection_status()
Return the common connection status from the manifest.
- Return type:
- schema(request, *args, **kwargs)
Return the published JSON schema for the Pydantic model.
- Parameters:
request (
HttpRequest) – The HTTP request object.args – Additional positional arguments.
kwargs – Additional keyword arguments.
- Returns:
A SmarterJournaledJsonResponse containing the JSON schema.
- Return type:
- 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_and_verify_name_param(*args, command=None, **kwargs)
Set self.name from the ‘name’ query string param and then verify that it.
was actually passed.
- Parameters:
command (
Optional[SmarterJournalCliCommands]) – The command being executed, for error reporting purposes.- Raises:
SAMBrokerErrorNotReady – If neither a manifest nor a name param is provided.
- Returns:
None
- set_is_internal_api_request(request, value=True)
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:
- setup(*args, request=None, user=None, **kwargs)
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
- smarter_build_absolute_uri(request)
Attempts to get the absolute URI from a request object.
This utility function tries to retrieve the request URL from any valid child class of
django.http.HttpRequest. It is especially useful in unit tests or scenarios where the request object may not implementbuild_absolute_uri().- Parameters:
request (
HttpRequest) – The request object.- Returns:
The absolute request URL.
- Return type:
- Raises:
SmarterValueError – If the URI cannot be built from the request.
- 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
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.
- sorted_dict(data)
Returns a new dictionary with keys sorted.
- property srm_formatted_class_name: str
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
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 thing: SmarterJournalThings
The Smarter Journal Thing for this broker.
- Returns:
The Smarter Journal Thing for this broker.
- Return type:
SmarterJournalThings, an enumeration of all Smarter AI resource types.
- 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_camel_case(data, convert_values=False)
Converts a snake_case string to camelCase.
This method takes a string in snake_case format and converts it to camelCase. It is useful for standardizing naming conventions across different formats.
- to_json()
Serialize the broker instance to a JSON string.
- to_snake_case(data, convert_values=False)
Converts a camelCase or PascalCase string to snake_case.
This method takes a string in camelCase or PascalCase format and converts it to snake_case. It is useful for standardizing naming conventions across different formats.
- 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'
- undeploy(request, *args, **kwargs)[source]
Handle undeploy operations for the API connection broker.
This is not implemented and will always raise a SAMBrokerErrorNotImplemented exception.
- Parameters:
request (
HttpRequest) – Django HTTP request object.args – Additional positional arguments.
kwargs – Additional keyword arguments.
- Returns:
SAMBrokerErrorNotImplemented. This method always raises an exception.
- Return type:
- property unformatted_class_name: str
Returns the raw class name without formatting.
- Returns:
The unformatted class name as a string.
- Return type:
This is useful for logging or serialization where the plain class name is needed.
- 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:
Example:
request_mixin = SmarterRequestMixin(request) unique_str = request_mixin.unique_client_string print(unique_str)
- property uri: str | None
Return the full uri of the request.
- Returns:
The full uri of the request.
- Return type:
Optional[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]
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: AnonymousUser | User | None
Returns the user.
Handle lazy instantiation from user_profile or account.
- Returns:
The user.
- Return type:
User or None
- 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)...'
- property user_profile: UserProfile | None
Returns the user_profile for the current user.
Handle lazy instantiation from user or account.
- Returns:
The user_profile for the current user.
- Return type:
UserProfile or None