Django ORM

This module contains the Prompt models.

class smarter.apps.prompt.models.Prompt(*args, **kwargs)[source]

Bases: MetaDataWithOwnershipModel

Prompt model.

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

  • created_at (Unknown) – Created at

  • updated_at (Unknown) – Updated at

  • name (Unknown) – Name. Name in camelCase, e.g., ‘apiKey’, no special characters.

  • description (Unknown) – Description. A brief description of this resource. Be verbose, but not too verbose.

  • version (Unknown) – Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.

  • annotations (Unknown) – Annotations. Key-value pairs for annotating this resource.

  • session_key (Unknown) – Session key

  • ip_address (Unknown) – Ip address

  • user_agent (Unknown) – User agent

  • url (Unknown) – Url

Relationship fields:

Parameters:
  • user_profile (Unknown) – User profile (related name: prompt)

  • llm_client (Unknown) – Llm client (related name: prompt)

  • tags (Unknown) – Tags. Tags for categorizing and organizing this resource. (related name: prompt)

  • tagged_items (Unknown) – Tagged items (related name: +)

Reverse relationships:

Parameters:
  • prompthistory (Unknown) – All Prompt History of this prompt (related name of prompt)

  • promptpluginusage (Unknown) – All Prompt Plugin Usage of this prompt (related name of prompt)

  • prompttoolcall (Unknown) – All Prompt Tool Call History of this prompt (related name of prompt)

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

exception NotUpdated

Bases: ObjectNotUpdated, DatabaseError

annotations

JSONField

Annotations. Key-value pairs for annotating this resource.

Type:

Type

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

delete(*args, **kwargs)[source]
description

TextField

Description. A brief description of this resource. Be verbose, but not too verbose.

Type:

Type

id

BigAutoField

Primary key: ID

Type:

Type

ip_address

GenericIPAddressField

Ip address

Type:

Type

llm_client

ForeignKey to LLMClient

Llm client (related name: prompt)

Type:

Type

llm_client_id

Internal field, use llm_client instead.

name

CharField

Name. Name in camelCase, e.g., ‘apiKey’, no special characters.

Type:

Type

objects: MetaDataWithOwnershipModelManager = <smarter.apps.account.models.metadata_with_ownership.MetaDataWithOwnershipModelManager object>
prompthistory_set

Reverse ForeignKey from PromptHistory

All Prompt History of this prompt (related name of prompt)

Type:

Type

promptpluginusage_set

Reverse ForeignKey from PromptPluginUsage

All Prompt Plugin Usage of this prompt (related name of prompt)

Type:

Type

prompttoolcall_set

Reverse ForeignKey from PromptToolCall

All Prompt Tool Call History of this prompt (related name of prompt)

Type:

Type

session_key

CharField

Session key

Type:

Type

tagged_items

Reverse GenericRelation from Prompt

All + of this tagged item (related name of tagged_items)

Type:

Type

tags = <taggit.managers._TaggableManager object>
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

url

URLField

Url

Type:

Type

user_agent

CharField

User agent

Type:

Type

user_profile

ForeignKey to UserProfile

User profile (related name: prompt)

Type:

Type

user_profile_id

Internal field, use user_profile instead.

version

CharField

Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.

Type:

Type

class smarter.apps.prompt.models.PromptHelper(request, session_key, *args, llm_client=None, **kwargs)[source]

Bases: SmarterRequestMixin

Helper class for working with Prompt objects.

This class provides methods for creating and retrieving Prompt objects, as well as managing the cache for prompt sessions. It is designed to simplify the process of interacting with prompt-related data and to ensure consistent handling of prompt sessions, llm_clients, and associated metadata.

Features

  • Abstracts the logic for creating and retrieving prompt sessions.

  • Manages caching of prompt objects to improve performance and reduce database queries.

  • Provides access to related prompt history, tool calls, and plugin usage.

  • Integrates with Django’s request and session handling.

  • Ensures that prompt sessions are always associated with a valid LLMClient and Account.

Usage

Typically, this class is instantiated with a Django HttpRequest object and a session key. Optionally, a LLMClient instance can be provided to associate the prompt session with a specific llm_client.

Example

helper = PromptHelper(request, session_key)
if helper.ready:
    prompt = helper.prompt
    llm_client = helper.llm_client
    history = helper.history
Parameters:
  • request (HttpRequest) – The Django HttpRequest object for the current session.

  • session_key (Optional[str]) – The session key identifying the prompt session.

  • llm_client (Optional[LLMClient]) – An optional LLMClient instance to associate with the prompt session.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Raises:
  • SmarterValueError – If neither a session key nor a LLMClient instance is provided.

  • SmarterConfigurationError – If there is an error creating a new Prompt object.

Note

This class is intended for internal use within the Smarter platform and should not be used directly in user-facing code without proper validation.

Todo

  • Remove the session_key parameter and rely solely on the LLMClient instance for prompt session management.

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

Initialize the PromptHelper instance.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object for the current session.

  • session_key (Optional[str]) – The session key identifying the prompt session.

  • llm_client (Optional[LLMClient]) – An optional LLMClient instance to associate with the prompt session.

  • args – Additional positional arguments.

  • kwargs – Additional keyword arguments.

Raises:
  • SmarterValueError – If neither a session key nor a LLMClient instance is provided.

  • SmarterConfigurationError – If there is an error creating a new Prompt object.

property formatted_class_name: str[source]

Returns the formatted class name for the PromptHelper.

This property returns a string representation of the class name, formatted to include the parent class’s formatted name and the PromptHelper class. This is useful for logging and debugging purposes, as it provides a clear and consistent identifier for instances of this helper class.

Example

helper = PromptHelper(request, session_key)
helper.formatted_class_name
# 'SmarterRequestMixin.PromptHelper()'
Returns:

The formatted class name as a string, including the parent class name.

Return type:

str

get_cached_chat()[source]

Get the prompt instance for the current request.

This method retrieves the Prompt instance associated with the current session key from the cache. If the Prompt instance is not found in the cache, it attempts to retrieve it from the database. If it still cannot be found, a new Prompt instance is created using the provided LLMClient and request metadata.

Returns:

The Prompt instance associated with the current session, or None if not found.

Return type:

Optional[Prompt]

property history: dict

Serialize the most recent logged history output for the prompt session.

Returns:

A dictionary containing serialized prompt, prompt history, tool calls, and plugin usage.

Return type:

dict

property llm_client

Returns a lazy instance of the LLMClient.

Examples

  • https://hr.3141-5926-5359.alpha.api.example.com/llm-client/ returns LLMClient(name='hr', account=Account(...))

Returns:

The LLMClient instance.

Return type:

LLMClient

property prompt

Get the prompt instance for the current request.

Returns:

The Prompt instance associated with the current session.

Return type:

Prompt

property prompt_history: QuerySet | list

Get the most recent prompt history for the current prompt session.

Returns:

The most recent PromptHistory instance’s prompt_history field, or an empty list if none found.

Return type:

Union[models.QuerySet, list]

property prompt_plugin_usage: QuerySet | list

Get the most recent prompt plugin usage history for the current prompt session.

Returns:

A queryset of PromptPluginUsage instances for the current prompt session, ordered by creation date.

Return type:

Union[models.QuerySet, list]

property prompt_tool_call: QuerySet | list

Get the most recent prompt tool call history for the current prompt session.

Returns:

A queryset of PromptToolCall instances for the current prompt session, ordered by creation date.

Return type:

Union[models.QuerySet, list]

property ready: bool

Check if the PromptHelper is ready to use.

This property returns True if the prompt instance is available and all required attributes are set, otherwise returns False. It is useful for determining whether the PromptHelper is fully initialized and ready for prompt operations.

Returns:

True if the PromptHelper is ready to use, otherwise False.

Return type:

bool

to_json()[source]

Convert the PromptHelper instance to a JSON serializable dictionary.

This method returns a dictionary representation of the PromptHelper instance, including key metadata and related objects such as the prompt, llm_client, prompt history, and a unique client string.

Returns:

A dictionary containing the serialized state of the PromptHelper.

Return type:

dict[str, Any]

class smarter.apps.prompt.models.PromptHistory(*args, **kwargs)[source]

Bases: TimestampedModel

Prompt history model.

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

  • created_at (Unknown) – Created at

  • updated_at (Unknown) – Updated at

  • request (Unknown) – Request

  • response (Unknown) – Response

  • messages (Unknown) – Messages

Relationship fields:

Parameters:

prompt (Unknown) – Prompt (related name: prompthistory)

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

exception NotUpdated

Bases: ObjectNotUpdated, DatabaseError

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

id

BigAutoField

Primary key: ID

Type:

Type

messages

JSONField

Messages

Type:

Type

objects = <django.db.models.Manager object>
prompt

ForeignKey to Prompt

Prompt (related name: prompthistory)

Type:

Type

property prompt_history: list[dict]

Used by the Reactapp (via PromptConfigView) to display the prompt history.

prompt_id

Internal field, use prompt instead.

request

JSONField

Request

Type:

Type

response

JSONField

Response

Type:

Type

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

class smarter.apps.prompt.models.PromptPluginUsage(*args, **kwargs)[source]

Bases: TimestampedModel

Plugin selection history model.

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

  • created_at (Unknown) – Created at

  • updated_at (Unknown) – Updated at

  • input_text (Unknown) – Input text

Relationship fields:

Parameters:
  • prompt (Unknown) – Prompt (related name: promptpluginusage)

  • plugin (Unknown) – Plugin (related name: promptpluginusage)

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

exception NotUpdated

Bases: ObjectNotUpdated, DatabaseError

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

id

BigAutoField

Primary key: ID

Type:

Type

input_text

TextField

Input text

Type:

Type

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

ForeignKey to PluginMeta

Plugin (related name: promptpluginusage)

Type:

Type

plugin_id

Internal field, use plugin instead.

prompt

ForeignKey to Prompt

Prompt (related name: promptpluginusage)

Type:

Type

prompt_id

Internal field, use prompt instead.

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

class smarter.apps.prompt.models.PromptToolCall(*args, **kwargs)[source]

Bases: TimestampedModel

Prompt tool call history model.

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

  • created_at (Unknown) – Created at

  • updated_at (Unknown) – Updated at

  • function_name (Unknown) – Function name

  • function_args (Unknown) – Function args

  • request (Unknown) – Request

  • response (Unknown) – Response

Relationship fields:

Parameters:
  • prompt (Unknown) – Prompt (related name: prompttoolcall)

  • plugin (Unknown) – Plugin (related name: prompttoolcall)

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

exception NotUpdated

Bases: ObjectNotUpdated, DatabaseError

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

function_args

CharField

Function args

Type:

Type

function_name

CharField

Function name

Type:

Type

classmethod get_cached_object(*args, invalidate=False, pk=None, **kwargs)[source]

Get the PromptToolCall instance for the given primary key from the cache.

This method retrieves the PromptToolCall instance associated with the given primary key from the cache. If the instance is not found in the cache, it attempts to retrieve it from the database. If it still cannot be found, it returns None.

Parameters:
  • invalidate (Optional[bool]) – Whether to invalidate the cache before retrieving the object.

  • pk (Optional[int]) – The primary key of the PromptToolCall instance to retrieve.

Returns:

The PromptToolCall instance associated with the given primary key, or None if not found.

Return type:

Optional[PromptToolCall]

id

BigAutoField

Primary key: ID

Type:

Type

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

ForeignKey to PluginMeta

Plugin (related name: prompttoolcall)

Type:

Type

plugin_id

Internal field, use plugin instead.

prompt

ForeignKey to Prompt

Prompt (related name: prompttoolcall)

Type:

Type

prompt_id

Internal field, use prompt instead.

request

JSONField

Request

Type:

Type

response

JSONField

Response

Type:

Type

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