aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/LanguageModel/LanguageModelManager.php
blob: e331da87b9051237ef27bfc575106e5f844d66b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
<?php

namespace OC\LanguageModel;

use OC\AppFramework\Bootstrap\Coordinator;
use OC\LanguageModel\Db\Task;
use OC\LanguageModel\Db\TaskMapper;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\BackgroundJob\IJobList;
use OCP\Common\Exception\NotFoundException;
use OCP\DB\Exception;
use OCP\IServerContainer;
use OCP\LanguageModel\AbstractLanguageModelTask;
use OCP\LanguageModel\FreePromptTask;
use OCP\LanguageModel\HeadlineTask;
use OCP\LanguageModel\IHeadlineProvider;
use OCP\LanguageModel\ILanguageModelManager;
use OCP\LanguageModel\ILanguageModelProvider;
use OCP\LanguageModel\ILanguageModelTask;
use OCP\LanguageModel\ISummaryProvider;
use OCP\LanguageModel\ITopicsProvider;
use OCP\LanguageModel\SummaryTask;
use OCP\LanguageModel\TopicsTask;
use OCP\PreConditionNotMetException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Throwable;

class LanguageModelManager implements ILanguageModelManager {
	/** @var ?ILanguageModelProvider[] */
	private ?array $providers = null;

	public function __construct(
		private IServerContainer $serverContainer,
		private Coordinator $coordinator,
		private LoggerInterface $logger,
		private IJobList $jobList,
		private TaskMapper $taskMapper,
	) {
	}

	public function getProviders(): array {
		$context = $this->coordinator->getRegistrationContext();
		if ($context === null) {
			return [];
		}

		if ($this->providers !== null) {
			return $this->providers;
		}

		$this->providers = [];

		foreach ($context->getLanguageModelProviders() as $providerServiceRegistration) {
			$class = $providerServiceRegistration->getService();
			try {
				$this->providers[$class] = $this->serverContainer->get($class);
			} catch (Throwable $e) {
				$this->logger->error('Failed to load LanguageModel provider ' . $class, [
					'exception' => $e,
				]);
			}
		}

		return $this->providers;
	}

	public function hasProviders(): bool {
		$context = $this->coordinator->getRegistrationContext();
		if ($context === null) {
			return false;
		}
		return count($context->getLanguageModelProviders()) > 0;
	}

	/**
	 * @inheritDoc
	 */
	public function getAvailableTasks(): array {
		$tasks = [];
		foreach ($this->getProviders() as $provider) {
			$tasks[FreePromptTask::class] = true;
			if ($provider instanceof ISummaryProvider) {
				$tasks[SummaryTask::class] = true;
			}
			if ($provider instanceof IHeadlineProvider) {
				$tasks[HeadlineTask::class] = true;
			}
			if ($provider instanceof ITopicsProvider) {
				$tasks[TopicsTask::class] = true;
			}
		}
		return array_keys($tasks);
	}

	/**
	 * @inheritDoc
	 */
	public function getAvailableTaskTypes(): array {
		return array_map(fn ($taskClass) => $taskClass::TYPE, $this->getAvailableTasks());
	}

	public function canHandleTask(ILanguageModelTask $task): bool {
		return count(array_filter($this->getAvailableTasks(), fn ($class) => $task instanceof $class)) > 0;
	}

	/**
	 * @inheritDoc
	 */
	public function runTask(ILanguageModelTask $task): string {
		if (!$this->canHandleTask($task)) {
			throw new PreConditionNotMetException('No LanguageModel provider is installed that can handle this task');
		}
		foreach ($this->getProviders() as $provider) {
			if (!$task->canUseProvider($provider)) {
				continue;
			}
			try {
				$task->setStatus(ILanguageModelTask::STATUS_RUNNING);
				if ($task->getId() === null) {
					$taskEntity = $this->taskMapper->insert(Task::fromLanguageModelTask($task));
					$task->setId($taskEntity->getId());
				} else {
					$this->taskMapper->update(Task::fromLanguageModelTask($task));
				}
				$output = $task->visitProvider($provider);
				$task->setOutput($output);
				$task->setStatus(ILanguageModelTask::STATUS_SUCCESSFUL);
				$this->taskMapper->update(Task::fromLanguageModelTask($task));
				return $output;
			} catch (\RuntimeException $e) {
				$this->logger->info('LanguageModel call using provider ' . $provider->getName() . ' failed', ['exception' => $e]);
				$task->setStatus(ILanguageModelTask::STATUS_FAILED);
				$this->taskMapper->update(Task::fromLanguageModelTask($task));
				throw $e;
			} catch (\Throwable $e) {
				$this->logger->info('LanguageModel call using provider ' . $provider->getName() . ' failed', ['exception' => $e]);
				$task->setStatus(ILanguageModelTask::STATUS_FAILED);
				$this->taskMapper->update(Task::fromLanguageModelTask($task));
				throw new RuntimeException('LanguageModel call using provider ' . $provider->getName() . ' failed: ' . $e->getMessage());
			}
		}

		throw new RuntimeException('Could not transcribe file');
	}

	/**
	 * @inheritDoc
	 * @throws Exception
	 */
	public function scheduleTask(ILanguageModelTask $task): void {
		if (!$this->canHandleTask($task)) {
			throw new PreConditionNotMetException('No LanguageModel provider is installed that can handle this task');
		}
		$task->setStatus(ILanguageModelTask::STATUS_SCHEDULED);
		$taskEntity = Task::fromLanguageModelTask($task);
		$this->taskMapper->insert($taskEntity);
		$task->setId($taskEntity->getId());
		$this->jobList->add(TaskBackgroundJob::class, [
			'taskId' => $task->getId()
		]);
	}

	/**
	 * @param int $id The id of the task
	 * @return ILanguageModelTask
	 * @throws RuntimeException If the query failed
	 * @throws NotFoundException If the task could not be found
	 */
	public function getTask(int $id): ILanguageModelTask {
		try {
			$taskEntity = $this->taskMapper->find($id);
			return AbstractLanguageModelTask::fromTaskEntity($taskEntity);
		} catch (DoesNotExistException $e) {
			throw new NotFoundException('Could not find task with the provided id');
		} catch (MultipleObjectsReturnedException $e) {
			throw new RuntimeException('Could not uniquely identify task with given id');
		} catch (Exception $e) {
			throw new RuntimeException('Failure while trying to find task by id: '.$e->getMessage());
		}
	}
}