Manager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\TextProcessing;
  8. use OC\AppFramework\Bootstrap\Coordinator;
  9. use OC\TextProcessing\Db\Task as DbTask;
  10. use OC\TextProcessing\Db\TaskMapper;
  11. use OCP\AppFramework\Db\DoesNotExistException;
  12. use OCP\AppFramework\Db\MultipleObjectsReturnedException;
  13. use OCP\BackgroundJob\IJobList;
  14. use OCP\Common\Exception\NotFoundException;
  15. use OCP\DB\Exception;
  16. use OCP\IConfig;
  17. use OCP\IServerContainer;
  18. use OCP\PreConditionNotMetException;
  19. use OCP\TaskProcessing\IManager as TaskProcessingIManager;
  20. use OCP\TaskProcessing\TaskTypes\TextToText;
  21. use OCP\TaskProcessing\TaskTypes\TextToTextHeadline;
  22. use OCP\TaskProcessing\TaskTypes\TextToTextSummary;
  23. use OCP\TaskProcessing\TaskTypes\TextToTextTopics;
  24. use OCP\TextProcessing\Exception\TaskFailureException;
  25. use OCP\TextProcessing\FreePromptTaskType;
  26. use OCP\TextProcessing\HeadlineTaskType;
  27. use OCP\TextProcessing\IManager;
  28. use OCP\TextProcessing\IProvider;
  29. use OCP\TextProcessing\IProviderWithExpectedRuntime;
  30. use OCP\TextProcessing\IProviderWithId;
  31. use OCP\TextProcessing\SummaryTaskType;
  32. use OCP\TextProcessing\Task;
  33. use OCP\TextProcessing\Task as OCPTask;
  34. use OCP\TextProcessing\TopicsTaskType;
  35. use Psr\Log\LoggerInterface;
  36. use RuntimeException;
  37. use Throwable;
  38. class Manager implements IManager {
  39. /** @var ?IProvider[] */
  40. private ?array $providers = null;
  41. public function __construct(
  42. private IServerContainer $serverContainer,
  43. private Coordinator $coordinator,
  44. private LoggerInterface $logger,
  45. private IJobList $jobList,
  46. private TaskMapper $taskMapper,
  47. private IConfig $config,
  48. private TaskProcessingIManager $taskProcessingManager,
  49. ) {
  50. }
  51. public function getProviders(): array {
  52. $context = $this->coordinator->getRegistrationContext();
  53. if ($context === null) {
  54. return [];
  55. }
  56. if ($this->providers !== null) {
  57. return $this->providers;
  58. }
  59. $this->providers = [];
  60. foreach ($context->getTextProcessingProviders() as $providerServiceRegistration) {
  61. $class = $providerServiceRegistration->getService();
  62. try {
  63. $this->providers[$class] = $this->serverContainer->get($class);
  64. } catch (Throwable $e) {
  65. $this->logger->error('Failed to load Text processing provider ' . $class, [
  66. 'exception' => $e,
  67. ]);
  68. }
  69. }
  70. return $this->providers;
  71. }
  72. public function hasProviders(): bool {
  73. $context = $this->coordinator->getRegistrationContext();
  74. if ($context === null) {
  75. return false;
  76. }
  77. return count($context->getTextProcessingProviders()) > 0;
  78. }
  79. /**
  80. * @inheritDoc
  81. */
  82. public function getAvailableTaskTypes(): array {
  83. $tasks = [];
  84. foreach ($this->getProviders() as $provider) {
  85. $tasks[$provider->getTaskType()] = true;
  86. }
  87. return array_keys($tasks);
  88. }
  89. public function canHandleTask(OCPTask $task): bool {
  90. return in_array($task->getType(), $this->getAvailableTaskTypes());
  91. }
  92. /**
  93. * @inheritDoc
  94. */
  95. public function runTask(OCPTask $task): string {
  96. // try to run a task processing task if possible
  97. $taskTypeClass = $task->getType();
  98. $taskProcessingCompatibleTaskTypes = [
  99. FreePromptTaskType::class => TextToText::ID,
  100. HeadlineTaskType::class => TextToTextHeadline::ID,
  101. SummaryTaskType::class => TextToTextSummary::ID,
  102. TopicsTaskType::class => TextToTextTopics::ID,
  103. ];
  104. if (isset($taskProcessingCompatibleTaskTypes[$taskTypeClass]) && isset($this->taskProcessingManager->getAvailableTaskTypes()[$taskProcessingCompatibleTaskTypes[$taskTypeClass]])) {
  105. try {
  106. $taskProcessingTaskTypeId = $taskProcessingCompatibleTaskTypes[$taskTypeClass];
  107. $taskProcessingTask = new \OCP\TaskProcessing\Task(
  108. $taskProcessingTaskTypeId,
  109. ['input' => $task->getInput()],
  110. $task->getAppId(),
  111. $task->getUserId(),
  112. $task->getIdentifier(),
  113. );
  114. $task->setStatus(OCPTask::STATUS_RUNNING);
  115. if ($task->getId() === null) {
  116. $taskEntity = $this->taskMapper->insert(DbTask::fromPublicTask($task));
  117. $task->setId($taskEntity->getId());
  118. } else {
  119. $this->taskMapper->update(DbTask::fromPublicTask($task));
  120. }
  121. $this->logger->debug('Running a TextProcessing (' . $taskTypeClass . ') task with TaskProcessing');
  122. $taskProcessingResultTask = $this->taskProcessingManager->runTask($taskProcessingTask);
  123. if ($taskProcessingResultTask->getStatus() === \OCP\TaskProcessing\Task::STATUS_SUCCESSFUL) {
  124. $output = $taskProcessingResultTask->getOutput();
  125. if (isset($output['output']) && is_string($output['output'])) {
  126. $task->setOutput($output['output']);
  127. $task->setStatus(OCPTask::STATUS_SUCCESSFUL);
  128. $this->taskMapper->update(DbTask::fromPublicTask($task));
  129. return $output['output'];
  130. }
  131. }
  132. } catch (\Throwable $e) {
  133. $this->logger->error('TextProcessing to TaskProcessing failed', ['exception' => $e]);
  134. $task->setStatus(OCPTask::STATUS_FAILED);
  135. $this->taskMapper->update(DbTask::fromPublicTask($task));
  136. throw new TaskFailureException('TextProcessing to TaskProcessing failed: ' . $e->getMessage(), 0, $e);
  137. }
  138. $task->setStatus(OCPTask::STATUS_FAILED);
  139. $this->taskMapper->update(DbTask::fromPublicTask($task));
  140. throw new TaskFailureException('Could not run task');
  141. }
  142. // try to run the text processing task
  143. if (!$this->canHandleTask($task)) {
  144. throw new PreConditionNotMetException('No text processing provider is installed that can handle this task');
  145. }
  146. $providers = $this->getPreferredProviders($task);
  147. foreach ($providers as $provider) {
  148. try {
  149. $task->setStatus(OCPTask::STATUS_RUNNING);
  150. if ($provider instanceof IProviderWithExpectedRuntime) {
  151. $completionExpectedAt = new \DateTime('now');
  152. $completionExpectedAt->add(new \DateInterval('PT'.$provider->getExpectedRuntime().'S'));
  153. $task->setCompletionExpectedAt($completionExpectedAt);
  154. }
  155. if ($task->getId() === null) {
  156. $taskEntity = $this->taskMapper->insert(DbTask::fromPublicTask($task));
  157. $task->setId($taskEntity->getId());
  158. } else {
  159. $this->taskMapper->update(DbTask::fromPublicTask($task));
  160. }
  161. $output = $task->visitProvider($provider);
  162. $task->setOutput($output);
  163. $task->setStatus(OCPTask::STATUS_SUCCESSFUL);
  164. $this->taskMapper->update(DbTask::fromPublicTask($task));
  165. return $output;
  166. } catch (\Throwable $e) {
  167. $this->logger->error('LanguageModel call using provider ' . $provider->getName() . ' failed', ['exception' => $e]);
  168. $task->setStatus(OCPTask::STATUS_FAILED);
  169. $this->taskMapper->update(DbTask::fromPublicTask($task));
  170. throw new TaskFailureException('LanguageModel call using provider ' . $provider->getName() . ' failed: ' . $e->getMessage(), 0, $e);
  171. }
  172. }
  173. $task->setStatus(OCPTask::STATUS_FAILED);
  174. $this->taskMapper->update(DbTask::fromPublicTask($task));
  175. throw new TaskFailureException('Could not run task');
  176. }
  177. /**
  178. * @inheritDoc
  179. */
  180. public function scheduleTask(OCPTask $task): void {
  181. if (!$this->canHandleTask($task)) {
  182. throw new PreConditionNotMetException('No LanguageModel provider is installed that can handle this task');
  183. }
  184. $task->setStatus(OCPTask::STATUS_SCHEDULED);
  185. $providers = $this->getPreferredProviders($task);
  186. if (count($providers) === 0) {
  187. throw new PreConditionNotMetException('No LanguageModel provider is installed that can handle this task');
  188. }
  189. [$provider,] = $providers;
  190. if ($provider instanceof IProviderWithExpectedRuntime) {
  191. $completionExpectedAt = new \DateTime('now');
  192. $completionExpectedAt->add(new \DateInterval('PT'.$provider->getExpectedRuntime().'S'));
  193. $task->setCompletionExpectedAt($completionExpectedAt);
  194. }
  195. $taskEntity = DbTask::fromPublicTask($task);
  196. $this->taskMapper->insert($taskEntity);
  197. $task->setId($taskEntity->getId());
  198. $this->jobList->add(TaskBackgroundJob::class, [
  199. 'taskId' => $task->getId()
  200. ]);
  201. }
  202. /**
  203. * @inheritDoc
  204. */
  205. public function runOrScheduleTask(OCPTask $task): bool {
  206. if (!$this->canHandleTask($task)) {
  207. throw new PreConditionNotMetException('No LanguageModel provider is installed that can handle this task');
  208. }
  209. [$provider,] = $this->getPreferredProviders($task);
  210. $maxExecutionTime = (int)ini_get('max_execution_time');
  211. // Offload the task to a background job if the expected runtime of the likely provider is longer than 80% of our max execution time
  212. // or if the provider doesn't provide a getExpectedRuntime() method
  213. if (!$provider instanceof IProviderWithExpectedRuntime || $provider->getExpectedRuntime() > $maxExecutionTime * 0.8) {
  214. $this->scheduleTask($task);
  215. return false;
  216. }
  217. $this->runTask($task);
  218. return true;
  219. }
  220. /**
  221. * @inheritDoc
  222. */
  223. public function deleteTask(Task $task): void {
  224. $taskEntity = DbTask::fromPublicTask($task);
  225. $this->taskMapper->delete($taskEntity);
  226. $this->jobList->remove(TaskBackgroundJob::class, [
  227. 'taskId' => $task->getId()
  228. ]);
  229. }
  230. /**
  231. * Get a task from its id
  232. *
  233. * @param int $id The id of the task
  234. * @return OCPTask
  235. * @throws RuntimeException If the query failed
  236. * @throws NotFoundException If the task could not be found
  237. */
  238. public function getTask(int $id): OCPTask {
  239. try {
  240. $taskEntity = $this->taskMapper->find($id);
  241. return $taskEntity->toPublicTask();
  242. } catch (DoesNotExistException $e) {
  243. throw new NotFoundException('Could not find task with the provided id');
  244. } catch (MultipleObjectsReturnedException $e) {
  245. throw new RuntimeException('Could not uniquely identify task with given id', 0, $e);
  246. } catch (Exception $e) {
  247. throw new RuntimeException('Failure while trying to find task by id: ' . $e->getMessage(), 0, $e);
  248. }
  249. }
  250. /**
  251. * Get a task from its user id and task id
  252. * If userId is null, this can only get a task that was scheduled anonymously
  253. *
  254. * @param int $id The id of the task
  255. * @param string|null $userId The user id that scheduled the task
  256. * @return OCPTask
  257. * @throws RuntimeException If the query failed
  258. * @throws NotFoundException If the task could not be found
  259. */
  260. public function getUserTask(int $id, ?string $userId): OCPTask {
  261. try {
  262. $taskEntity = $this->taskMapper->findByIdAndUser($id, $userId);
  263. return $taskEntity->toPublicTask();
  264. } catch (DoesNotExistException $e) {
  265. throw new NotFoundException('Could not find task with the provided id and user id');
  266. } catch (MultipleObjectsReturnedException $e) {
  267. throw new RuntimeException('Could not uniquely identify task with given id and user id', 0, $e);
  268. } catch (Exception $e) {
  269. throw new RuntimeException('Failure while trying to find task by id and user id: ' . $e->getMessage(), 0, $e);
  270. }
  271. }
  272. /**
  273. * Get a list of tasks scheduled by a specific user for a specific app
  274. * and optionally with a specific identifier.
  275. * This cannot be used to get anonymously scheduled tasks
  276. *
  277. * @param string $userId
  278. * @param string $appId
  279. * @param string|null $identifier
  280. * @return array
  281. */
  282. public function getUserTasksByApp(string $userId, string $appId, ?string $identifier = null): array {
  283. try {
  284. $taskEntities = $this->taskMapper->findUserTasksByApp($userId, $appId, $identifier);
  285. return array_map(static function (DbTask $taskEntity) {
  286. return $taskEntity->toPublicTask();
  287. }, $taskEntities);
  288. } catch (Exception $e) {
  289. throw new RuntimeException('Failure while trying to find tasks by appId and identifier: ' . $e->getMessage(), 0, $e);
  290. }
  291. }
  292. /**
  293. * @param OCPTask $task
  294. * @return IProvider[]
  295. */
  296. public function getPreferredProviders(OCPTask $task): array {
  297. $providers = $this->getProviders();
  298. $json = $this->config->getAppValue('core', 'ai.textprocessing_provider_preferences', '');
  299. if ($json !== '') {
  300. $preferences = json_decode($json, true);
  301. if (isset($preferences[$task->getType()])) {
  302. // If a preference for this task type is set, move the preferred provider to the start
  303. $provider = current(array_values(array_filter($providers, function ($provider) use ($preferences, $task) {
  304. if ($provider instanceof IProviderWithId) {
  305. return $provider->getId() === $preferences[$task->getType()];
  306. }
  307. return $provider::class === $preferences[$task->getType()];
  308. })));
  309. if ($provider !== false) {
  310. $providers = array_filter($providers, fn ($p) => $p !== $provider);
  311. array_unshift($providers, $provider);
  312. }
  313. }
  314. }
  315. return array_values(array_filter($providers, fn (IProvider $provider) => $task->canUseProvider($provider)));
  316. }
  317. }