Skip to content

Django Chain Models

django_chain.models

Models for django-chain: LLM prompts, workflows, chat sessions, messages, logs, and user interactions.

This module defines the core database models for prompt management, workflow orchestration, chat memory, LLM interaction logging, and user interaction tracking in Django Chain.

Typical usage example

prompt = Prompt.objects.create(...) session = ChatSession.objects.create(...) message = ChatMessage.objects.create(session=session, ...)

Raises:

  • ValidationError

    If model constraints are violated.

AIRequestStatus

Bases: TextChoices

Enum for chat message roles.

RoleChoices

Bases: TextChoices

Enum for chat message roles.

VersionedManager

Bases: Manager

get_active(name)

Returns the active object for a given name.

deactivate_all_for_name(name, exclude_pk=None)

Deactivates all active objects for a given name, optionally excluding a specific primary key.

VersionedModel

Bases: Model

create_new_version(name, activate=True, **model_specific_data) classmethod

Creates a new version of a VersionedModel instance.

Parameters:

  • name (str) –

    The name of the versioned object.

  • activate (bool, default: True ) –

    Whether this new version should be set as active. If True, all other active versions with the same name will be deactivated.

  • **model_specific_data

    Keyword arguments for fields specific to the concrete model (e.g., 'template_string', 'description' for PromptTemplate).

Returns:

  • The newly created concrete model instance.

AbstractPrompt

Bases: VersionedModel

to_langchain_prompt()

Converts the stored JSON prompt_template into an actual LangChain prompt object.

Prompt

Bases: AuditModel, AbstractPrompt

to_dict()

Returns a dictionary representation of the Workflow instance for API responses.

Returns:

  • dict ( dict ) –

    Dictionary with workflow fields.

AbstractWorkflow

Bases: VersionedModel

Represents an AI workflow, defined as a sequence of LangChain components.

Attributes:

  • id (UUID) –

    Unique identifier for the workflow.

  • name (str) –

    Name of the workflow (unique).

  • description (str) –

    Description of the workflow.

  • workflow_definition (list) –

    List of steps (dicts) defining the workflow. is_active (bool): Whether this workflow is active.

to_langchain_chain(*args, **kwargs)

Convert this workflow instance to a LangChain chain.

Parameters:

  • *args

    Additional positional arguments

  • **kwargs

    Additional keyword arguments including: - log: Whether to enable logging ("true"/"false") - session_id: Session ID for chat history - llm_config: LLM configuration dictionary - chat_input: Chat input key for message history - history: History key for message history

Returns:

  • Any

    LangChain chain object ready for execution

Workflow

Bases: AuditModel, AbstractWorkflow

to_dict()

Returns a dictionary representation of the Workflow instance for API responses.

Returns:

  • dict ( dict ) –

    Dictionary with workflow fields.

ChatSessionManager

Bases: Manager

Manager for ChatSession model, providing helper methods for active/inactive sessions.

active()

Return queryset of active chat sessions.

archived()

Return queryset of archived (inactive) chat sessions.

for_user(user)

Return queryset of sessions for a specific user.

active_for_user(user)

Return queryset of active sessions for a specific user.

ChatHistoryManager

Bases: Manager

Manager for ChatHistory model, providing helper methods for non-deleted messages.

active()

Return queryset of non-deleted chat messages.

deleted()

Return queryset of soft-deleted chat messages.

for_session(session)

Return queryset of messages for a specific session (non-deleted only).

all_for_session(session)

Return queryset of all messages for a specific session (including deleted).

AbstractChatSession

Bases: TimeStampedModel

Stores chat session information, including user, session ID, and LLM config.

Attributes:

  • user (User) –

    Associated user (nullable).

  • session_id (UUID) –

    Unique session identifier (auto-generated UUID).

  • title (str) –

    Optional title for the chat session.

  • workflow (Workflow) –

    Associated workflow for this session.

  • is_active (bool) –

    Whether the session is currently active.

  • created_at (datetime) –

    Creation timestamp.

  • updated_at (datetime) –

    Last update timestamp.

archive()

Archive this chat session by setting is_active to False.

activate()

Activate this chat session by setting is_active to True.

ChatSession

Bases: AbstractChatSession

get_memory(memory_type='buffer', k=None)

Get a LangChain memory object for this session.

Parameters:

  • memory_type (str, default: 'buffer' ) –

    Type of memory ('buffer' or 'buffer_window')

  • k (Optional[int], default: None ) –

    Number of messages to keep for window memory

Returns:

  • Configured LangChain memory object

get_chat_history()

Get a LangChain-compatible chat history for this session.

Returns:

  • Chat message history instance

add_message(content, role='USER', **kwargs)

Add a message to this chat session.

Parameters:

  • content (str) –

    Message content

  • role (str, default: 'USER' ) –

    Message role (USER, ASSISTANT, SYSTEM)

  • **kwargs

    Additional fields for the ChatHistory model

Returns:

  • Created ChatHistory instance

clear_messages(hard_delete=False)

Clear all messages from this session.

Parameters:

  • hard_delete (bool, default: False ) –

    If True, permanently delete messages. If False, soft delete (set is_deleted=True)

get_message_count(include_deleted=False)

Get the number of messages in this session.

Parameters:

  • include_deleted (bool, default: False ) –

    Whether to include soft-deleted messages

Returns:

  • Number of messages

ChatHistory

Bases: Model

Stores individual chat messages within a session.

Attributes:

  • session (ChatSession) –

    Related chat session.

  • content (str) –

    Message content.

  • role (str) –

    Message role (user, assistant, system).

  • timestamp (datetime) –

    Message creation time.

  • token_count (int) –

    Optional token count.

  • order (int) –

    Order for sorting messages.

  • is_deleted (bool) –

    Whether the message has been soft deleted.

__str__()

Return a string representation of the chat message.

soft_delete()

Soft delete this message by setting is_deleted to True.

restore()

Restore this message by setting is_deleted to False.

to_langchain_message()

Convert this ChatHistory instance to a LangChain message.

Returns:

  • Appropriate LangChain message object (HumanMessage, AIMessage, SystemMessage)

from_langchain_message(session, message, order=None, **kwargs) classmethod

Create a ChatHistory instance from a LangChain message.

Parameters:

  • session

    The ChatSession instance

  • message

    LangChain message object

  • order (Optional[int], default: None ) –

    Message order (auto-calculated if not provided)

  • **kwargs

    Additional fields for the ChatHistory model

Returns:

  • Created ChatHistory instance

update_content(new_content)

Update the content of this message.

Parameters:

  • new_content (str) –

    New message content

get_context_window(window_size=5)

Get a context window of messages around this message.

Parameters:

  • window_size (int, default: 5 ) –

    Number of messages before and after this message

Returns:

  • QuerySet of ChatHistory messages in the context window

InteractionManager

Bases: Manager

Manager for Interaction model, providing helper methods for creation and filtering.

completed_interactions()

Return queryset of completed (successful) interactions.

for_session(session_id)

Return queryset of interactions for a given session ID.

AbstractInteractionLog

Bases: TimeStampedModel

Logs LLM interactions for auditing, cost analysis, and debugging.

Attributes:

  • user (User) –

    User who initiated the interaction.

  • workflow (Workflow) –

    The associated workflow

  • prompt_text (str) –

    Prompt sent to the LLM.

  • response_text (str) –

    LLM response.

  • model_name (str) –

    Name of the LLM model used.

  • provider (str) –

    LLM provider.

  • input_tokens (int) –

    Number of input tokens.

  • output_tokens (int) –

    Number of output tokens.

  • total_cost (Decimal) –

    Estimated cost in USD.

  • latency_ms (int) –

    Latency in milliseconds.

  • status (str) –

    Success or error.

  • error_message (str) –

    Error message if failed.

  • created_at (datetime) –

    Creation timestamp.

  • metadata (dict) –

    Additional metadata.

__str__()

Return a string representation of the LLM interaction log.

InteractionLog

Bases: AbstractInteractionLog

to_dict()

Returns a dictionary representation of the InteractionLog instance for API responses. Sanitizes sensitive data to prevent API key leakage.

Returns:

  • dict ( dict ) –

    Dictionary with sanitized interaction log fields.