Skip to content

django_ai_assistant.models

Thread

Bases: Model

Thread model. A thread is a collection of messages between a user and the AI assistant. Also called conversation or session.

Source code in django_ai_assistant/models.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
class Thread(models.Model):
    """Thread model. A thread is a collection of messages between a user and the AI assistant.
    Also called conversation or session."""

    id: Any  # noqa: A003
    messages: Manager["Message"]
    name = models.CharField(max_length=255, blank=True)
    """Name of the thread. Can be blank."""
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        related_name="ai_assistant_threads",
        null=True,
    )
    """User who created the thread. Can be null. Set to null/None when user is deleted."""
    assistant_id = models.CharField(max_length=255, blank=True)
    """Associated assistant ID. Can be empty."""
    created_at = models.DateTimeField(auto_now_add=True)
    """Date and time when the thread was created.
    Automatically set when the thread is created."""
    updated_at = models.DateTimeField(auto_now=True)
    """Date and time when the thread was last updated.
    Automatically set when the thread is updated."""

    class Meta:
        verbose_name = "Thread"
        verbose_name_plural = "Threads"
        ordering = ("-created_at",)
        indexes = (Index(F("created_at").desc(), name="thread_created_at_desc"),)

    def __str__(self) -> str:
        """Return the name of the thread as the string representation of the thread."""
        return self.name

    def __repr__(self) -> str:
        """Return the string representation of the thread like '<Thread name>'"""
        return f"<Thread {self.name}>"

    def get_messages(self, include_extra_messages: bool = False) -> list[BaseMessage]:
        """
        Get LangChain messages objects from the thread.

        Args:
            include_extra_messages (bool): Whether to include non-chat messages (like tool calls).

        Returns:
            list[BaseMessage]: List of messages
        """

        messages = messages_from_dict(
            cast(
                Sequence[dict[str, BaseMessage]],
                Message.objects.filter(thread=self)
                .order_by("created_at")
                .values_list("message", flat=True),
            )
        )
        if not include_extra_messages:
            messages = [
                m
                for m in messages
                if isinstance(m, HumanMessage | ChatMessage)
                or (isinstance(m, AIMessage) and not m.tool_calls)
            ]
        return cast(list[BaseMessage], messages)

name = models.CharField(max_length=255, blank=True) class-attribute instance-attribute

Name of the thread. Can be blank.

created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='ai_assistant_threads', null=True) class-attribute instance-attribute

User who created the thread. Can be null. Set to null/None when user is deleted.

assistant_id = models.CharField(max_length=255, blank=True) class-attribute instance-attribute

Associated assistant ID. Can be empty.

created_at = models.DateTimeField(auto_now_add=True) class-attribute instance-attribute

Date and time when the thread was created. Automatically set when the thread is created.

updated_at = models.DateTimeField(auto_now=True) class-attribute instance-attribute

Date and time when the thread was last updated. Automatically set when the thread is updated.

__str__()

Return the name of the thread as the string representation of the thread.

Source code in django_ai_assistant/models.py
47
48
49
def __str__(self) -> str:
    """Return the name of the thread as the string representation of the thread."""
    return self.name

__repr__()

Return the string representation of the thread like ''

Source code in django_ai_assistant/models.py
51
52
53
def __repr__(self) -> str:
    """Return the string representation of the thread like '<Thread name>'"""
    return f"<Thread {self.name}>"

get_messages(include_extra_messages=False)

Get LangChain messages objects from the thread.

Parameters:

Name Type Description Default
include_extra_messages bool

Whether to include non-chat messages (like tool calls).

False

Returns:

Type Description
list[BaseMessage]

list[BaseMessage]: List of messages

Source code in django_ai_assistant/models.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def get_messages(self, include_extra_messages: bool = False) -> list[BaseMessage]:
    """
    Get LangChain messages objects from the thread.

    Args:
        include_extra_messages (bool): Whether to include non-chat messages (like tool calls).

    Returns:
        list[BaseMessage]: List of messages
    """

    messages = messages_from_dict(
        cast(
            Sequence[dict[str, BaseMessage]],
            Message.objects.filter(thread=self)
            .order_by("created_at")
            .values_list("message", flat=True),
        )
    )
    if not include_extra_messages:
        messages = [
            m
            for m in messages
            if isinstance(m, HumanMessage | ChatMessage)
            or (isinstance(m, AIMessage) and not m.tool_calls)
        ]
    return cast(list[BaseMessage], messages)

Message

Bases: Model

Message model. A message is a text that is part of a thread. A message can be sent by a user or the AI assistant.

The message data is stored as a JSON field called message.

Source code in django_ai_assistant/models.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
class Message(models.Model):
    """Message model. A message is a text that is part of a thread.
    A message can be sent by a user or the AI assistant.\n
    The message data is stored as a JSON field called `message`."""

    id: Any  # noqa: A003
    thread = models.ForeignKey(Thread, on_delete=models.CASCADE, related_name="messages")
    """Thread to which the message belongs."""
    thread_id: Any
    message = models.JSONField()
    """Message content. This is a serialized LangChain `BaseMessage` that was serialized
    with `message_to_dict` and can be deserialized with `messages_from_dict`."""
    created_at = models.DateTimeField(auto_now_add=True)
    """Date and time when the message was created.
    Automatically set when the message is created."""

    class Meta:
        verbose_name = "Message"
        verbose_name_plural = "Messages"
        ordering = ("created_at",)
        indexes = (Index(F("created_at"), name="message_created_at"),)

    def __str__(self) -> str:
        """Return internal message data from `message` attribute
        as the string representation of the message."""
        return json.dumps(self.message)

    def __repr__(self) -> str:
        """Return the string representation of the message like '<Message id at thread_id>'"""
        return f"<Message {self.id} at {self.thread_id}>"

thread = models.ForeignKey(Thread, on_delete=models.CASCADE, related_name='messages') class-attribute instance-attribute

Thread to which the message belongs.

message = models.JSONField() class-attribute instance-attribute

Message content. This is a serialized LangChain BaseMessage that was serialized with message_to_dict and can be deserialized with messages_from_dict.

created_at = models.DateTimeField(auto_now_add=True) class-attribute instance-attribute

Date and time when the message was created. Automatically set when the message is created.

__str__()

Return internal message data from message attribute as the string representation of the message.

Source code in django_ai_assistant/models.py
106
107
108
109
def __str__(self) -> str:
    """Return internal message data from `message` attribute
    as the string representation of the message."""
    return json.dumps(self.message)

__repr__()

Return the string representation of the message like ''

Source code in django_ai_assistant/models.py
111
112
113
def __repr__(self) -> str:
    """Return the string representation of the message like '<Message id at thread_id>'"""
    return f"<Message {self.id} at {self.thread_id}>"