-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathTextProcessingService.php
237 lines (209 loc) · 7.53 KB
/
TextProcessingService.php
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
<?php
declare(strict_types=1);
namespace OCA\AppAPI\Service;
use OCA\AppAPI\AppInfo\Application;
use OCA\AppAPI\Db\TextProcessing\TextProcessingProvider;
use OCA\AppAPI\Db\TextProcessing\TextProcessingProviderMapper;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\DB\Exception;
use OCP\ICache;
use OCP\ICacheFactory;
use OCP\IServerContainer;
use OCP\TextProcessing\IProviderWithId;
use OCP\TextProcessing\IProviderWithUserId;
use Psr\Log\LoggerInterface;
class TextProcessingService {
// We do support only available on server-side Text Processing Task Types
public const TASK_TYPES = [
'free_prompt' => 'OCP\TextProcessing\FreePromptTaskType',
'headline' => 'OCP\TextProcessing\HeadlineTaskType',
'summary' => 'OCP\TextProcessing\SummaryTaskType',
'topics' => 'OCP\TextProcessing\TopicsTaskType',
];
private ICache $cache;
public function __construct(
ICacheFactory $cacheFactory,
private readonly TextProcessingProviderMapper $mapper,
private readonly LoggerInterface $logger,
) {
$this->cache = $cacheFactory->createDistributed(Application::APP_ID . '/ex__text_processing_providers');
}
public function getRegisteredTextProcessingProviders(): array {
try {
$cacheKey = '/ex_text_processing_providers';
$providers = $this->cache->get($cacheKey);
if ($providers === null) {
$providers = $this->mapper->findAllEnabled();
$this->cache->set($cacheKey, $providers);
}
return array_map(function ($provider) {
return $provider instanceof TextProcessingProvider ? $provider : new TextProcessingProvider($provider);
}, $providers);
} catch (Exception) {
return [];
}
}
public function getExAppTextProcessingProvider(string $appId, string $name): ?TextProcessingProvider {
$cacheKey = '/ex_text_processing_providers_' . $appId . '_' . $name;
$cached = $this->cache->get($cacheKey);
if ($cached !== null) {
return $cached instanceof TextProcessingProvider ? $cached : new TextProcessingProvider($cached);
}
try {
$textProcessingProvider = $this->mapper->findByAppidName($appId, $name);
} catch (DoesNotExistException|MultipleObjectsReturnedException|Exception) {
return null;
}
$this->cache->set($cacheKey, $textProcessingProvider);
return $textProcessingProvider;
}
public function registerTextProcessingProvider(
string $appId,
string $name,
string $displayName,
string $actionHandler,
string $taskType
): ?TextProcessingProvider {
try {
$textProcessingProvider = $this->mapper->findByAppidName($appId, $name);
} catch (DoesNotExistException|MultipleObjectsReturnedException|Exception) {
$textProcessingProvider = null;
}
try {
if (!$this->isTaskTypeValid($taskType)) {
return null;
}
$newTextProcessingProvider = new TextProcessingProvider([
'appid' => $appId,
'name' => $name,
'display_name' => $displayName,
'action_handler' => ltrim($actionHandler, '/'),
'task_type' => $taskType,
]);
if ($textProcessingProvider !== null) {
$newTextProcessingProvider->setId($textProcessingProvider->getId());
}
$textProcessingProvider = $this->mapper->insertOrUpdate($newTextProcessingProvider);
$this->cache->set('/ex_text_processing_providers_' . $appId . '_' . $name, $textProcessingProvider);
$this->resetCacheEnabled();
} catch (Exception $e) {
$this->logger->error(
sprintf('Failed to register ExApp %s TextProcessingProvider %s. Error: %s', $appId, $name, $e->getMessage()), ['exception' => $e]
);
return null;
}
return $textProcessingProvider;
}
public function unregisterTextProcessingProvider(string $appId, string $name): ?TextProcessingProvider {
try {
$textProcessingProvider = $this->getExAppTextProcessingProvider($appId, $name);
if ($textProcessingProvider === null) {
return null;
}
$this->mapper->delete($textProcessingProvider);
$this->cache->remove('/ex_text_processing_providers_' . $appId . '_' . $name);
$this->resetCacheEnabled();
return $textProcessingProvider;
} catch (Exception $e) {
$this->logger->error(sprintf('Failed to unregister ExApp %s TextProcessingProvider %s. Error: %s', $appId, $name, $e->getMessage()), ['exception' => $e]);
return null;
}
}
/**
* Register dynamically ExApps TextProcessing providers with ID using anonymous classes.
*
* @param IRegistrationContext $context
* @param IServerContainer $serverContainer
*
* @return void
*/
public function registerExAppTextProcessingProviders(IRegistrationContext &$context, IServerContainer $serverContainer): void {
$exAppsProviders = $this->getRegisteredTextProcessingProviders();
/** @var TextProcessingProvider $exAppProvider */
foreach ($exAppsProviders as $exAppProvider) {
if (!$this->isTaskTypeValid($exAppProvider->getTaskType())) {
continue;
}
$className = '\\OCA\\AppAPI\\' . $exAppProvider->getAppid() . '\\' . $exAppProvider->getName();
$provider = $this->getAnonymousExAppProvider($exAppProvider, $className, $serverContainer);
$context->registerService($className, function () use ($provider) {
return $provider;
});
$context->registerTextProcessingProvider($className);
}
}
/**
* @psalm-suppress UndefinedClass, MissingDependency, InvalidReturnStatement, InvalidReturnType
*/
private function getAnonymousExAppProvider(
TextProcessingProvider $provider,
string $className,
IServerContainer $serverContainer
): IProviderWithId {
return new class($provider, $serverContainer, $className) implements IProviderWithId, IProviderWithUserId {
private ?string $userId;
public function __construct(
private readonly TextProcessingProvider $provider,
private readonly IServerContainer $serverContainer,
private readonly string $className,
) {
}
public function getId(): string {
return $this->className;
}
public function getName(): string {
return $this->provider->getDisplayName();
}
public function process(string $prompt, float $maxExecutionTime = 0): string {
/** @var AppAPIService $service */
$service = $this->serverContainer->get(AppAPIService::class);
$route = $this->provider->getActionHandler();
$response = $service->requestToExAppById($this->provider->getAppid(),
$route,
$this->userId,
'POST',
params: [
'prompt' => $prompt,
'max_execution_time' => $maxExecutionTime,
],
options: [
'timeout' => $maxExecutionTime,
],
);
if (is_array($response)) {
throw new \Exception(sprintf('Failed process text task: %s:%s:%s. Error: %s',
$this->provider->getAppid(),
$this->provider->getName(),
$this->provider->getTaskType(),
$response['error']
));
}
return $response->getBody();
}
public function getTaskType(): string {
return TextProcessingService::TASK_TYPES[$this->provider->getTaskType()];
}
public function setUserId(?string $userId): void {
$this->userId = $userId;
}
};
}
private function isTaskTypeValid(string $getActionType): bool {
return in_array($getActionType, array_keys(self::TASK_TYPES));
}
private function resetCacheEnabled(): void {
$this->cache->remove('/ex_text_processing_providers');
}
public function unregisterExAppTextProcessingProviders(string $appId): int {
try {
$result = $this->mapper->removeAllByAppId($appId);
} catch (Exception) {
$result = -1;
}
$this->cache->clear('/ex_text_processing_providers_' . $appId);
$this->resetCacheEnabled();
return $result;
}
}