1
0

Manager.php 13 KB

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