Skip to content

Commit ce836de

Browse files
committed
fix(Assignments): Minor fixes to get things to run
Signed-off-by: Marcel Klehr <mklehr@gmx.net>
1 parent 66c47d7 commit ce836de

5 files changed

Lines changed: 75 additions & 7 deletions

File tree

lib/Db/Assignment.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -113,19 +113,20 @@ public function setRecurrence(string $recurrence): void {
113113
public function isDueToRun(\DateTimeImmutable $now): bool {
114114
try {
115115
$startsAt = new \DateTime('@' . $this->getStartsAt());
116+
$lastRunAt = new \DateTime('@' . $this->getLastRunAt());
116117
// Find recurrences after the last run or after the current time if this assignment has never run
117118
$rule = new Rule($this->getRecurrence(), $startsAt);
118119
$transformer = new \Recurr\Transformer\ArrayTransformer();
119-
$constraint = new AfterConstraint($this->getLastRunAt() !== 0 ? new \DateTime('@' . $this->getLastRunAt()) : $startsAt, true);
120+
$constraint = new AfterConstraint($this->getLastRunAt() !== 0 ? $lastRunAt : $startsAt, false);
120121
/** @var RecurrenceCollection $collection */
121122
$collection = $transformer->transform($rule, $constraint);
122123
if ($collection->isEmpty()) {
123124
return false;
124125
}
125126
$nextRecurrence = $collection->first();
126-
if ($nextRecurrence->getStart()->getTimestamp() <= $now->getTimestamp() && $nextRecurrence->getStart()->getTimestamp() > $this->getLastRunAt()) {
127-
return true;
128-
}
127+
$isDue = $nextRecurrence->getStart()->getTimestamp() <= $now->getTimestamp() && $nextRecurrence->getStart()->getTimestamp() > $this->getLastRunAt();
128+
\OCP\Log\logger('assistant')->error('Next recurrence of assignment ' . $this->getId().' of user ' . $this->getUserId() . ': ' . $nextRecurrence->getStart()->format('Y-m-d H:i:s') . ' - isDue: ' . ($isDue ? 'true' : 'false'));
129+
return $isDue;
129130
} catch (InvalidRRule|\Exception|NotFoundExceptionInterface|ContainerExceptionInterface $e) {
130131
// this should not happen, as we validate the rule on setRecurrence, but just in case, we catch the exception and log it
131132
logger('assistant')->error($e->getMessage(), ['exception' => $e]);

lib/Db/ChattyLLM/Message.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
class Message extends Entity implements \JsonSerializable {
3232
public const ROLE_HUMAN = 'human';
3333

34+
public const ROLE_ASSISTANT = 'assistant';
35+
3436
/** @var int */
3537
protected $sessionId;
3638
/** @var string */

lib/Listener/ChattyLLMTaskListener.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ public function handle(Event $event): void {
7070
$message = new Message();
7171
$message->setSessionId($sessionId);
7272
$message->setOcpTaskId($task->getId());
73-
$message->setRole('assistant');
73+
$message->setRole(Message::ROLE_ASSISTANT);
7474
$message->setTimestamp(time());
7575
$sources = json_encode($taskOutput['sources'] ?? []);
7676
$message->setSources($sources ?: '[]');

lib/Service/AssignmentsService.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use OCP\AppFramework\Utility\ITimeFactory;
2020
use OCP\BackgroundJob\IJobList;
2121
use OCP\DB\Exception;
22+
use OCP\IL10N;
2223
use Psr\Log\LoggerInterface;
2324

2425
class AssignmentsService {
@@ -29,6 +30,7 @@ public function __construct(
2930
private ITimeFactory $timeFactory,
3031
private LoggerInterface $logger,
3132
private IJobList $jobList,
33+
private IL10N $l10n,
3234
) {
3335
}
3436

@@ -98,10 +100,25 @@ public function scheduleAssignmentRun(?string $userId, int $assignmentId): void
98100
throw new InternalException(previous: $e);
99101
}
100102
$assignment = $this->assignmentMapper->find($userId, $assignmentId);
103+
$assignment->setLastRunAt($this->timeFactory->now()->getTimestamp());
104+
$this->assignmentMapper->update($assignment);
101105
$this->chatService->createMessage($userId, $session->getId(), Message::ROLE_HUMAN, $assignment->getPrompt(), $this->timeFactory->now()->getTimestamp());
102-
$this->chatService->scheduleMessageGeneration($userId, $session->getId());
106+
$this->chatService->scheduleAssignmentMessageGeneration($userId, $session->getId());
103107
} catch (BadRequestException|InternalException|DoesNotExistException|MultipleObjectsReturnedException|Exception $e) {
104108
$this->logger->error('Error while running assignment ' . $assignment->getId() . ' for user ' . $userId, ['exception' => $e]);
109+
if (isset($session)) {
110+
try {
111+
$this->chatService->createMessage(
112+
$userId,
113+
$session->getId(),
114+
message::ROLE_ASSISTANT,
115+
$this->l10n->t('An error occurred while scheduling this assignment run. Reach out to your system administrator if this issue persists.'),
116+
$this->timeFactory->now()->getTimestamp()
117+
);
118+
} catch (BadRequestException|InternalException|NotFoundException|UnauthorizedException $e) {
119+
$this->logger->error('Error while creating error message for assignment ' . $assignment->getId() . ' for user ' . $userId, ['exception' => $e]);
120+
}
121+
}
105122
} catch (NotFoundException $e) {
106123
try {
107124
$this->assignmentMapper->delete($assignment);

lib/Service/ChatService.php

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,54 @@ public function scheduleMessageGeneration(?string $userId, int $sessionId, int $
421421
return $taskId;
422422
}
423423

424+
/**
425+
* @throws InternalException
426+
* @throws BadRequestException
427+
* @throws NotFoundException
428+
* @throws UnauthorizedException
429+
*/
430+
public function scheduleAssignmentMessageGeneration(?string $userId, int $sessionId): int {
431+
if ($userId === null) {
432+
throw new UnauthorizedException($this->l10n->t('Unauthorized'));
433+
}
434+
try {
435+
$sessionExists = $this->sessionMapper->exists($userId, $sessionId);
436+
} catch (Exception $e) {
437+
throw new InternalException(previous: $e);
438+
}
439+
if (!$sessionExists) {
440+
throw new NotFoundException($this->l10n->t('Session not found'));
441+
}
442+
443+
if (!$this->isContextAgentAvailable()) {
444+
throw new BadRequestException('context_agent_not_available');
445+
}
446+
try {
447+
$lastUserMessage = $this->messageMapper->getLastHumanMessage($sessionId);
448+
} catch (DoesNotExistException $e) {
449+
throw new NotFoundException($this->l10n->t('No user message found in this session'), previous: $e);
450+
} catch (MultipleObjectsReturnedException|Exception $e) {
451+
throw new InternalException(previous: $e);
452+
}
453+
454+
455+
try {
456+
$session = $this->sessionMapper->getUserSession($userId, $sessionId);
457+
} catch (DoesNotExistException $e) {
458+
throw new NotFoundException($this->l10n->t('Session not found'), previous: $e);
459+
} catch (MultipleObjectsReturnedException|Exception $e) {
460+
throw new InternalException(previous: $e);
461+
}
462+
// We reset the context for each interaction, because this is an assignment,
463+
// the assistant does not remember things between assignment runs
464+
$lastConversationToken = '{}';
465+
466+
// classic agency
467+
$prompt = $lastUserMessage->getContent();
468+
$taskId = $this->scheduleAgencyTask($userId, $prompt, 0, $lastConversationToken, $sessionId);
469+
return $taskId;
470+
}
471+
424472
/**
425473
* @throws BadRequestException
426474
* @throws InternalException
@@ -494,7 +542,7 @@ private function getAudioHistory(array $history): array {
494542
'role' => $message->getRole(),
495543
];
496544
$attachments = $message->jsonSerialize()['attachments'];
497-
if ($message->getRole() === 'assistant'
545+
if ($message->getRole() === Message::ROLE_ASSISTANT
498546
&& count($attachments) > 0
499547
&& $attachments[0]['type'] === 'Audio'
500548
&& isset($attachments[0]['remote_audio_id'])

0 commit comments

Comments
 (0)