From fb35e925bf577dc390f41941b36fe6a6714837fe Mon Sep 17 00:00:00 2001 From: Julien Veyssier Date: Wed, 26 Aug 2026 13:45:56 +0200 Subject: [PATCH] fix: correctly order messages when getting the system prompt one, improve the query by applying a role filter Signed-off-by: Julien Veyssier --- lib/Db/ChattyLLM/MessageMapper.php | 9 +++++++-- lib/Service/ChatService.php | 8 +++----- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/lib/Db/ChattyLLM/MessageMapper.php b/lib/Db/ChattyLLM/MessageMapper.php index 3254ca7a..86204fc2 100644 --- a/lib/Db/ChattyLLM/MessageMapper.php +++ b/lib/Db/ChattyLLM/MessageMapper.php @@ -27,17 +27,22 @@ public function __construct(IDBConnection $db) { /** * @param integer $sessionId * @param integer $n + * @param string|null $role * @return Message * @throws \OCP\DB\Exception * @throws \RuntimeException * @throws \OCP\AppFramework\Db\DoesNotExistException * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException */ - public function getFirstNMessages(int $sessionId, int $n = 1): Message { + public function getFirstNMessages(int $sessionId, int $n = 1, ?string $role = null): Message { $qb = $this->db->getQueryBuilder(); $qb->select(Message::$columns) ->from($this->getTableName()) - ->where($qb->expr()->eq('session_id', $qb->createPositionalParameter($sessionId, IQueryBuilder::PARAM_INT))) + ->where($qb->expr()->eq('session_id', $qb->createPositionalParameter($sessionId, IQueryBuilder::PARAM_INT))); + if ($role !== null) { + $qb->andWhere($qb->expr()->eq('role', $qb->createPositionalParameter($role, IQueryBuilder::PARAM_STR))); + } + $qb->orderBy('timestamp', 'ASC') ->setMaxResults($n); return $this->findEntity($qb); diff --git a/lib/Service/ChatService.php b/lib/Service/ChatService.php index e93394dd..18adfc6c 100644 --- a/lib/Service/ChatService.php +++ b/lib/Service/ChatService.php @@ -415,15 +415,13 @@ public function scheduleMessageGeneration(?string $userId, int $sessionId, int $ // classic chat $systemPrompt = ''; try { - $firstMessage = $this->messageMapper->getFirstNMessages($sessionId, 1); + $firstMessage = $this->messageMapper->getFirstNMessages($sessionId, 1, Message::ROLE_SYSTEM); + $systemPrompt = $firstMessage->getContent(); } catch (DoesNotExistException $e) { - throw new NotFoundException($this->l10n->t('No message found in this session'), previous: $e); + $this->logger->info('No system message found in the session', ['exception' => $e, 'sessionId' => $sessionId]); } catch (MultipleObjectsReturnedException|Exception $e) { throw new InternalException(previous: $e); } - if ($firstMessage->getRole() === Message::ROLE_SYSTEM) { - $systemPrompt = $firstMessage->getContent(); - } try { $history = $this->getRawLastMessages($sessionId); } catch (Exception|AppConfigTypeConflictException $e) {