56 lines
1.6 KiB
Python
56 lines
1.6 KiB
Python
from core.util import logs
|
|
from core.models import Message, ChatSession, QueuedMessage
|
|
from asgiref.sync import sync_to_async
|
|
from core.messaging.utils import messages_to_string
|
|
|
|
log = logs.get_logger("history")
|
|
|
|
async def get_chat_history(session):
|
|
stored_messages = await sync_to_async(list)(
|
|
Message.objects.filter(session=session, user=session.user).order_by("ts")
|
|
)
|
|
recent_chat_history = messages_to_string(stored_messages)
|
|
chat_history = f"Chat Summary:\n{session.summary}\n\nRecent Messages:\n{recent_chat_history}" if session.summary else f"Recent Messages:\n{recent_chat_history}"
|
|
|
|
return chat_history
|
|
|
|
async def get_chat_session(user, identifier):
|
|
chat_session, _ = await sync_to_async(ChatSession.objects.get_or_create)(
|
|
identifier=identifier,
|
|
user=user,
|
|
)
|
|
return chat_session
|
|
|
|
async def store_message(session, sender, text, ts, outgoing=False):
|
|
log.info(f"STORE MESSAGE {text}")
|
|
msg = await sync_to_async(Message.objects.create)(
|
|
user=session.user,
|
|
session=session,
|
|
sender_uuid=sender,
|
|
text=text,
|
|
ts=ts,
|
|
custom_author="USER" if outgoing else None
|
|
)
|
|
|
|
return msg
|
|
|
|
async def store_own_message(session, text, ts, manip=None, queue=False):
|
|
log.info(f"STORE OWN MESSAGE {text}")
|
|
cast = {
|
|
"user": session.user,
|
|
"session": session,
|
|
"custom_author": "BOT",
|
|
"text": text,
|
|
"ts": ts,
|
|
}
|
|
if queue:
|
|
msg_object = QueuedMessage
|
|
cast["manipulation"] = manip
|
|
else:
|
|
msg_object = Message
|
|
|
|
msg = await sync_to_async(msg_object.objects.create)(
|
|
**cast,
|
|
)
|
|
|
|
return msg |