PluginPrompt Model

PluginPrompt model for storing LLM prompt configuration for Smarter plugins.

class smarter.apps.llmtool.models.plugin_prompt.PluginPrompt(*args, **kwargs)[source]

Bases: TimestampedModel

Stores LLM prompt model configuration for a Smarter plugin.

The PluginPrompt model defines the prompt settings and LLM interaction parameters for a plugin. Each instance is linked to a PluginMeta object, allowing prompt customization on a per-plugin basis. This includes specifying the LLM provider (such as OpenAI), the system role (which sets the context or persona for the LLM), the model to use, temperature for response creativity, and the maximum number of completion tokens.

By encapsulating these settings, PluginPrompt enables fine-grained control over how each plugin interacts with the LLM, supporting use cases such as tailoring the assistant’s tone, optimizing for cost or accuracy, and enforcing token limits. This model works in conjunction with PluginSelector (which determines when a plugin is invoked) and PluginMeta (which provides the core plugin metadata).

Typical scenarios include customizing the system prompt for different plugins, selecting different LLM models for specific tasks, or adjusting temperature and token limits to balance creativity and resource usage.

See also:

  • PluginMeta

Parameters:
  • id (Unknown) – Primary key: ID

  • created_at (Unknown) – Created at

  • updated_at (Unknown) – Updated at

  • provider (Unknown) – Provider. The name of the LLM provider for the plugin. Example: ‘openai’.

  • system_role (Unknown) – System role. The role of the system in the conversation.

  • model (Unknown) – Model. The model to use for the completion.

  • temperature (Unknown) – Temperature. The higher the temperature, the more creative the result.

  • max_completion_tokens (Unknown) – Max completion tokens. The maximum number of tokens for both input and output.

Relationship fields:

Parameters:

plugin (Unknown) – Plugin (related name: plugin_prompt_plugin)

exception DoesNotExist

Bases: ObjectDoesNotExist

__init__(*args, **kwargs)
add_note(note, /)

Add a note to the exception

args
silent_variable_failure = True
with_traceback(tb, /)

Set self.__traceback__ to tb and return self.

HASH_FLOOR = 1000000
HASH_PREFIX = 'r'
HASH_SUFFIX = 'x'
exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

__init__(*args, **kwargs)
add_note(note, /)

Add a note to the exception

args
with_traceback(tb, /)

Set self.__traceback__ to tb and return self.

exception NotUpdated

Bases: ObjectNotUpdated, DatabaseError

__init__(*args, **kwargs)
add_note(note, /)

Add a note to the exception

args
with_traceback(tb, /)

Set self.__traceback__ to tb and return self.

__init__(*args, **kwargs)
async adelete(using=None, keep_parents=False)
property amnesty_urls: list[str]

Returns a list of URLs that are exempt from certain checks.

Returns:

List of URL path strings that are exempt.

Return type:

list[str]

async arefresh_from_db(using=None, fields=None, from_queryset=None)
async asave(*, force_insert=False, force_update=False, using=None, update_fields=None)
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.

Parameters:
  • var_name (str) – The name of the environment variable to check.

  • default (bool) – The default boolean value to return if the environment variable is not set or invalid.

Returns:

The boolean value of the environment variable or the default.

Return type:

bool

cache_expiration: ClassVar[int] = 60

Seconds that get_cached_object() caches a row, from smarter_settings.subsystem_cache_expiration.

classmethod check(**kwargs)
clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

clean_fields(exclude=None)

Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.

created_at

DateTimeField

Created at

Timestamp indicating when the model instance was created.

This field is automatically set to the current date and time when the instance is first created. It is indexed in the database for efficient querying.

Type:

Type

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.

Parameters:

data (dict[str, Any] | str) – The data to convert, either a dict or a JSON/YAML string.

Returns:

The data as a dictionary.

Return type:

dict[str, Any]

Raises:

SmarterValueError – If the data cannot be converted to a dictionary.

date_error_message(lookup_type, field_name, unique_for)
delete(using=None, keep_parents=False)
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.

Parameters:

slug (str) – The URL path to check.

Returns:

True if the URL deserves amnesty, False otherwise.

Return type:

bool

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.

Parameters:
  • dict1 (dict[str, Any]) – The dictionary to check for containment.

  • dict2 (dict[str, Any]) – The dictionary to check against for containment.

Returns:

True if dict1 is contained in dict2, False otherwise.

Return type:

bool

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.

Parameters:
  • small (dict[str, Any]) – The dictionary to check as a subset.

  • big (dict[str, Any]) – The dictionary to check against as a superset.

Returns:

True if the small dictionary is a subset of the big dictionary, False otherwise.

Return type:

bool

property elapsed_updated: int | None

The number of whole seconds since the model’s updated_at timestamp.

It is a property, so it always compares updated_at with the current time: the dt parameter can’t be passed, and is always None. A naive updated_at is compared with the naive current time, and an aware one with the current UTC time.

Example

obj = MyModel.objects.get(pk=1)
seconds = obj.elapsed_updated
print(f"Seconds since last update: {seconds}")
Returns:

The absolute difference in seconds between updated_at and now, or None if updated_at is not set, e.g. because the object has not been saved.

classmethod find_hash(value)

Finds and returns the first url path segment in the given value that is a hashed ID.

A segment counts only if it matches hash_regex() and also decodes to an id, so a path segment that merely looks like one, e.g. rex, is skipped. Pass a url’s path, not the whole url: a host name is never a hashed ID.

Example:

MyModel.find_hash("/workbench/llm-clients/rMTAwMDAyNwx/prompt/")  # "rMTAwMDAyNwx"
MyModel.find_hash("/api/v1/llm-clients/repo-ex/prompt/")  # None
Parameters:

value (str) – The string to search for a hashed ID, usually a url path.

Return type:

str | None

Returns:

The first hashed ID found, otherwise None.

formatted_class_name = '\x1b[1;31mPluginPrompt\x1b[0m'
formatted_json(json_obj)

Formats a JSON object as a pretty-printed string with ANSI color codes for logging.

Parameters:

json_obj (dict[str, Any] | list) – The JSON object (dict or list) to format.

Returns:

A string representation of the JSON object with ANSI color codes.

Return type:

str

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:

str

property formatted_state_ready: str

Returns the readiness state formatted for logging.

Returns:

The formatted readiness state as a string.

Return type:

str

formatted_text(text, color_code='\x1b[1;31m')

Formats text with ANSI color codes for logging.

Parameters:
  • text (str) – The text to format.

  • color_code (str) – The ANSI color code to apply.

Returns:

The formatted text with ANSI color codes.

Return type:

str

formatted_text_blue(text)

Formats text in bold dark blue for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in bold dark blue.

Return type:

str

formatted_text_green(text)

Formats text in bright green for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in bright green.

Return type:

str

formatted_text_red(text)

Formats text in dark red for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in dark red.

Return type:

str

classmethod from_db(db, field_names, values)
full_clean(exclude=None, validate_unique=True, validate_constraints=True)

Call clean_fields(), clean(), validate_unique(), and validate_constraints() on the model. Raise a ValidationError for any errors that occur.

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:

str

classmethod get_cached_object(invalidate=False, pk=None, **kwargs)

Retrieve a model instance by primary key, using caching to optimize performance.

This method is selectively overridden in models that inherit from TimestampedModel to provide class-specific function parameters.

Example

# Retrieve by primary key
instance = MyModel.get_cached_object(pk=1)
Parameters:
  • invalidate (bool | None) – Whether to drop the cached row, and read it again from the database.

  • pk (int | None) – The primary key of the model instance to retrieve.

  • kwargs – Ignored here; subclasses that override this method use them.

Return type:

Model | None

Returns:

The model instance.

Raises:
classmethod get_cached_objects(invalidate=False, **kwargs)

Return every row of the model.

Subclasses override it with filters, e.g. a user profile, and cache those results. The unfiltered list is not cached: a queryset is lazy, so returning it costs nothing, while caching it would store the whole table in Redis, and refill it after every save.

Example

# Retrieve all instances
instances = MyModel.get_cached_objects()
Parameters:
  • invalidate (bool | None) – Accepted for the subclasses’ signature. Nothing is cached here.

  • kwargs – Ignored here; subclasses that override this method use them.

Return type:

QuerySet[TimestampedModel]

Returns:

A queryset of all model instances.

Raises:

NotImplementedError – if called on an abstract model class.

classmethod get_cached_prompt_by_plugin(plugin, invalidate=False)[source]

Return a single instance of PluginPrompt by plugin.

This method caches the results to improve performance.

Parameters:

plugin (PluginMeta) – The plugin whose prompt should be retrieved.

Returns:

A PluginPrompt instance if found, otherwise None.

Return type:

PluginPrompt | None

get_constraints()
get_deferred_fields()

Return a set containing names of deferred fields for this instance.

classmethod get_object_by_locator(locator)

Retrieves an object based on its record locator.

Example:

obj = MyModel.objects.create()
print(obj.id)  # e.g., 123
locator = obj.record_locator # e.g., "mymodel-rc2x"

retrieved_obj = MyModel.get_object_by_locator(locator)
print(type(retrieved_obj))  # Should be <class 'MyModel'>
print(retrieved_obj)  # Should be the same as obj
Parameters:

locator (str) – The record locator string to decode and search for.

Return type:

TimestampedModel | None

Returns:

The model instance if found, otherwise None. A failure to decode or find the object is logged, and returns None. A locator comes from the client, so a locator that doesn’t decode, or whose row doesn’t exist, is a WARNING, not an ERROR.

get_readonly_csv_file(file_path)

Reads a CSV file and returns its contents as a list of dictionaries, one per row.

The file is opened read-only, so reading it never modifies it.

Parameters:

file_path (str) – The path to the CSV file to read.

Returns:

The rows of the CSV file, one dictionary per row, keyed by the column headers.

Return type:

list[dict]

get_readonly_yaml_file(file_path)

Reads a YAML file and returns its contents as a dictionary.

The file is opened read-only, so reading it never modifies it.

Parameters:

file_path (str) – The path to the YAML file to read.

Returns:

The contents of the YAML file, parsed into a dictionary.

Return type:

dict

classmethod hash_regex()

Returns a regex pattern that matches a hashed ID that is a whole url path segment.

The hashed ID format is defined by the HASH_PREFIX and HASH_SUFFIX class attributes, with a base64-encoded string in between. A match must start at the beginning of the string or after a /, and end at the end of the string or before a /. Without these boundaries, the pattern would match inside ordinary words, e.g. repo-ex in the host name repo-explorer.

Example:

pattern = MyModel.hash_regex()
pattern.search("/workbench/llm-clients/rMTAwMDAyNwx/prompt/")  # matches rMTAwMDAyNwx
pattern.search("http://repo-explorer.example.com/")  # None
Return type:

Pattern

Returns:

A regex pattern for matching hashed IDs.

property hashed_id: str

Returns a URL-friendly hashed version of the object’s ID for use in URLs and other contexts where an obscured, non-identifying, non-sequential identifier is preferred.

Encoding scheme:

  1. Take the object’s ID and add a large constant (HASH_FLOOR) to ensure it’s not easily guessable.

  2. Convert the resulting number to a string and encode it using URL-safe base64 encoding.

  3. Remove any padding characters from the encoded string.

  4. Add a prefix and suffix to the encoded string to create a recognizable format.

Example:

obj = MyModel.objects.create()
print(obj.id)  # e.g., 123
print(obj.hashed_id)  # e.g., "rc2x"
Returns:

Hashed ID string (URL-safe, no padding).

property health_check_urls: list[str]

Returns a list of URL paths that are considered health check endpoints.

Returns:

List of health check URL path strings.

Return type:

list[str]

id: int

BigAutoField

Primary key: ID

The row’s primary key, which Django adds to every concrete model. Declared, without a value, only so that type checkers know it: Django ignores a bare annotation.

Type:

Type

classmethod id_from_hashed_id(hashed_id)

Decodes a hashed ID back to the original object ID.

Decoding scheme:

  1. Validate that the hashed ID starts with the expected prefix and ends with the expected suffix.

  2. Remove the prefix and suffix to isolate the base64-encoded string.

  3. Add padding if necessary to make the length of the encoded string a multiple of 4.

  4. Decode the base64 string to get the original number as a string.

  5. Convert the decoded string to an integer and subtract the HASH_FLOOR to get the original ID.

Example:

my_record = MyModel.objects.create()
print(my_record.id)  # e.g., 123
hashed_id = my_record.hashed_id  # e.g., "rc2x"

original_id = MyModel.id_from_hashed_id(hashed_id)
print(original_id)  # Should print the original ID (e.g., 123)
Parameters:

hashed_id (str) – The hashed ID string to decode (URL-safe, no padding).

Return type:

int | None

Returns:

The original object ID if decoding is successful, otherwise None.

property is_billable_resource: bool

Indicates whether the model instance is considered a billable resource.

This property can be overridden in subclasses to specify which models are billable. By default, it returns False, indicating that the base TimestampedModel is not billable.

Returns:

True if the instance is billable, False otherwise.

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.

Parameters:
  • string (str | None) – The string to be masked.

  • mask_char (str) – The character used for masking.

  • mask_length (int) – The number of characters to mask.

  • string_length (int) – The length of the string to consider for masking.

Returns:

The masked string.

Return type:

str

max_completion_tokens

IntegerField

Max completion tokens. The maximum number of tokens for both input and output.

Type:

Type

model

CharField

Model. The model to use for the completion.

Type:

Type

objects = <django.db.models.Manager object>
property pk
plugin

OneToOneField to PluginMeta

Plugin (related name: plugin_prompt_plugin)

Type:

Type

plugin_id

Internal field, use plugin instead.

prepare_database_save(field)
provider

TextField

Provider. The name of the LLM provider for the plugin. Example: ‘openai’.

Type:

Type

property ready: bool

Check if the model instance is ready for use.

Returns:

True if the instance is ready, False otherwise.

property record_locator: str

Returns a short, URL-friendly record locator derived from the object’s ID.

Example:

obj = MyModel.objects.create(name="Example")
print(obj.id)  # e.g., 123
print(obj.record_locator)  # e.g., "llmclient-rc2x"
Returns:

Record locator string (URL-safe, no padding).

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.

Parameters:

data (dict[str, Any]) – The dictionary to sort.

Returns:

A new dictionary with all keys sorted.

Return type:

dict[str, Any]

refresh_from_db(using=None, fields=None, from_queryset=None)

Reload field values from the database.

By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn’t loaded from any database. The using parameter will override the default.

Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded.

When accessing deferred fields of an instance, the deferred loading of the field will call this method.

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.

Parameters:

name (str) – The string to convert to RFC 1034 compliant format.

Returns:

The converted string in RFC 1034 compliant format.

Return type:

str

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.

Parameters:

name (str) – The RFC 1034 compliant string to convert.

Returns:

The converted string in snake_case.

Return type:

str

save(*args, **kwargs)[source]

Save the PluginPrompt, and replace its cached copy with the saved row.

A plugin reads its PluginPrompt from the cache. A copy cached before the save would otherwise be read back, e.g. by PluginBase.save() after an update, and written over the row, reverting what the manifest just applied.

save_base(raw=False, force_insert=False, force_update=False, using=None, update_fields=None)

Handle the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.

The ‘raw’ argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading.

serializable_value(field_name)

Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object. If there’s no Field object with this name on the model, return the model attribute’s value.

Used to serialize a field’s value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method.

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 implement build_absolute_uri().

Parameters:

request (HttpRequest) – The request object.

Returns:

The absolute request URL.

Return type:

str | None

Raises:

SmarterValueError – If the URI cannot be built from the request.

sorted_dict(data)

Returns a new dictionary with keys sorted.

Parameters:

data (dict[str, Any]) – The dictionary to sort.

Returns:

A new dictionary with sorted keys.

Return type:

dict[str, Any]

system_role

TextField

System role. The role of the system in the conversation.

Type:

Type

temperature

FloatField

Temperature. The higher the temperature, the more creative the result.

Type:

Type

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.

Parameters:
  • data (ConvertibleCaseT) – The snake_case string to convert.

  • convert_values (bool) – Whether to convert the values of dictionaries and lists recursively.

Returns:

The converted string in camelCase.

Return type:

ConvertibleCaseT

to_json()

Serialize the model instance to a JSON-compatible dictionary.

This method uses the custom SmarterJSONEncoder to ensure that all fields, including timestamps and any complex data types, are properly serialized.

Return type:

dict[str, Any]

Returns:

A dictionary representation of the model instance suitable for JSON serialization.

Raises:

SmarterValueError – if the instance can’t be serialized.

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.

Parameters:
  • data (ConvertibleCaseT) – The camelCase or PascalCase string to convert.

  • convert_values (bool) – Whether to convert the values of dictionaries and lists recursively.

Returns:

The converted string in snake_case.

Return type:

ConvertibleCaseT

property unformatted_class_name: str

Returns the raw class name without formatting.

Returns:

The unformatted class name as a string.

Return type:

str

This is useful for logging or serialization where the plain class name is needed.

unique_error_message(model_class, unique_check)
updated_at

DateTimeField

Updated at

Timestamp indicating when the model instance was last updated.

This field is automatically updated to the current date and time whenever the instance is saved. It is indexed in the database for efficient querying.

Type:

Type

validate()

Validate the model.

Attention

Intended to be overridden in subclasses to provide custom validation logic.

validate_constraints(exclude=None)
validate_unique(exclude=None)

Check unique constraints on the model and raise ValidationError if any failed.