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.
Prompt
¶
Workflow
¶
Bases: Model
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_dict()
¶
Returns a dictionary representation of the Workflow instance for API responses.
Returns:
-
dict
(dict
) –Dictionary with workflow fields.
__str__()
¶
Return a string representation of the workflow.
clean()
¶
Custom validation for workflow definition and active status.
Raises:
-
ValidationError
–If constraints are violated.
save(*args, **kwargs)
¶
Save the workflow instance after full validation.
activate()
¶
Activates this workflow, deactivating any other active workflow with the same name.
deactivate()
¶
Deactivates this workflow.
to_langchain_chain(*args, **kwargs)
¶
Constructs and returns a LangChain RunnableSequence from the workflow definition.
Returns:
-
Any
(Any
) –LangChain RunnableSequence instance.
Raises:
-
ImportError
–If LangChain is not installed.
-
ValueError
–If the workflow definition is invalid.
ChatSession
¶
Bases: Model
Stores chat session information, including user, session ID, and LLM config.
Attributes:
-
user
(User
) –Associated user (nullable).
-
session_id
(str
) –Unique session identifier.
-
title
(str
) –Optional title for the chat session.
-
llm_config
(dict
) –LLM configuration for this session.
-
created_at
(datetime
) –Creation timestamp.
-
updated_at
(datetime
) –Last update timestamp.
__str__()
¶
Return a string representation of the chat session.
RoleChoices
¶
Bases: TextChoices
Enum for chat message roles.
ChatMessage
¶
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.
__str__()
¶
Return a string representation of the chat message.
InteractionLog
¶
Bases: Model
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.
UserInteractionManager
¶
Bases: Manager
Manager for UserInteraction model, providing helper methods for creation and filtering.
create_for_workflow(workflow, input_data, user_identifier, session_id)
¶
Create a new UserInteraction for a workflow.
Parameters:
-
workflow
(Workflow
) –The workflow instance.
-
input_data
(dict
) –Input data for the interaction.
-
user_identifier
(str
) –User/session identifier.
-
session_id
(UUID
) –Session ID.
Returns:
-
UserInteraction
–The created interaction.
completed_interactions()
¶
Return queryset of completed (successful) interactions.
for_session(session_id)
¶
Return queryset of interactions for a given session ID.
UserInteraction
¶
Bases: Model
Records a single overall user query and the final LLM response.
Attributes:
-
id
(UUID
) –Unique identifier.
-
workflow
(Workflow
) –Related workflow.
-
user_identifier
(str
) –User/session identifier.
-
session_id
(UUID
) –Session grouping ID.
-
input_data
(dict
) –Input JSON from the user.
-
llm_output
(dict
) –Output from the LLM workflow.
-
total_cost_estimate
(Decimal
) –Estimated cost.
-
total_duration_ms
(int
) –Execution time in ms.
-
status
(str
) –Status of the interaction.
-
error_message
(str
) –Error message if failed.
__str__()
¶
Return a string representation of the user interaction.
update_status_and_metrics(status, llm_output=None, total_cost_estimate=None, total_duration_ms=None, error_message=None)
¶
Update the status and metrics for this interaction.
Parameters:
-
status
(str
) –New status.
-
llm_output
(dict
, default:None
) –LLM output.
-
total_cost_estimate
(float
, default:None
) –Cost estimate.
-
total_duration_ms
(int
, default:None
) –Duration in ms.
-
error_message
(str
, default:None
) –Error message.