Skip to content

Commit

Permalink
LLM OCP API: Implement ocs API
Browse files Browse the repository at this point in the history
Signed-off-by: Marcel Klehr <mklehr@gmx.net>
  • Loading branch information
marcelklehr committed Jul 7, 2023
1 parent 9d5717d commit 795b097
Show file tree
Hide file tree
Showing 11 changed files with 167 additions and 16 deletions.
96 changes: 96 additions & 0 deletions core/Controller/LanguageModelApiController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

declare(strict_types=1);

/**
* @copyright Copyright (c) 2022 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/


namespace OC\Core\Controller;

use InvalidArgumentException;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\IL10N;
use OCP\IRequest;
use OCP\LanguageModel\AbstractLanguageModelTask;
use OCP\LanguageModel\ILanguageModelManager;
use OCP\PreConditionNotMetException;

class LanguageModelApiController extends \OCP\AppFramework\OCSController {
public function __construct(
string $appName,
IRequest $request,
private ILanguageModelManager $languageModelManager,
private IL10N $l,
private ?string $userId,
) {
parent::__construct($appName, $request);
}

/**
* @PublicPage
*/
public function tasks(): DataResponse {
return new DataResponse([
'tasks' => $this->languageModelManager->getAvailableTaskTypes(),
]);
}

/**
* @PublicPage
* @UserRateThrottle(limit=20, period=120)
* @AnonRateThrottle(limit=5, period=120)
*/
public function schedule(string $text, string $type, ?string $appId): DataResponse {
try {
$task = AbstractLanguageModelTask::factory($type, $text, $this->userId, $appId);
} catch (InvalidArgumentException $e) {
return new DataResponse(['message' => $this->l->t('Requested task type does not exist')], Http::STATUS_BAD_REQUEST);
}
try {
$this->languageModelManager->scheduleTask($task);

return new DataResponse([
'task' => $task,
]);
} catch (PreConditionNotMetException) {
return new DataResponse(['message' => $this->l->t('Necessary language model provider is not available')], Http::STATUS_PRECONDITION_FAILED);
}
}

/**
* @PublicPage
*/
public function getTask(int $id): DataResponse {
try {
$task = $this->languageModelManager->getTask($id);

return new DataResponse([
'task' => $task,
]);
} catch (\ValueError $e) {
return new DataResponse(['message' => $this->l->t('Task not found')], Http::STATUS_NOT_FOUND);
} catch (\RuntimeException $e) {
return new DataResponse(['message' => $this->l->t('Internal error')], Http::STATUS_INTERNAL_SERVER_ERROR);
}
}
}
3 changes: 3 additions & 0 deletions core/Migrations/Version28000Date20230616104802.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt
$table->addColumn('input', Types::TEXT, [
'notnull' => true,
]);
$table->addColumn('output', Types::TEXT, [
'notnull' => false,
]);
$table->addColumn('status', Types::INTEGER, [
'notnull' => false,
'length' => 6,
Expand Down
4 changes: 4 additions & 0 deletions core/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@

['root' => '/translation', 'name' => 'TranslationApi#languages', 'url' => '/languages', 'verb' => 'GET'],
['root' => '/translation', 'name' => 'TranslationApi#translate', 'url' => '/translate', 'verb' => 'POST'],

['root' => '/languagemodel', 'name' => 'LanguageModelApi#tasks', 'url' => '/tasks', 'verb' => 'GET'],
['root' => '/languagemodel', 'name' => 'LanguageModelApi#schedule', 'url' => '/schedule', 'verb' => 'POST'],
['root' => '/languagemodel', 'name' => 'LanguageModelApi#getTask', 'url' => '/task/{id}', 'verb' => 'GET'],
],
]);

Expand Down
7 changes: 4 additions & 3 deletions lib/private/LanguageModel/Db/Task.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ class Task extends Entity {
/**
* @var string[]
*/
public static array $columns = ['id', 'type', 'input', 'status', 'user_id', 'app_id'];
public static array $columns = ['id', 'type', 'input', 'output', 'status', 'user_id', 'app_id'];

/**
* @var string[]
*/
public static array $fields = ['id', 'type', 'input', 'status', 'userId', 'appId'];
public static array $fields = ['id', 'type', 'input', 'output', 'status', 'userId', 'appId'];


public function __construct() {
Expand All @@ -49,8 +49,9 @@ public function __construct() {
public static function fromLanguageModelTask(ILanguageModelTask $task): Task {
return Task::fromParams([
'type' => $task->getType(),
'status' => ILanguageModelTask::STATUS_UNKNOWN,
'status' => $task->getStatus(),
'input' => $task->getInput(),
'output' => $task->getOutput(),
'userId' => $task->getUserId(),
'appId' => $task->getAppId(),
]);
Expand Down
11 changes: 9 additions & 2 deletions lib/private/LanguageModel/LanguageModelManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ public function getAvailableTasks(): array {
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 !empty(array_filter($this->getAvailableTasks(), fn ($class) => $task instanceof $class));
}
Expand All @@ -104,10 +111,10 @@ public function runTask(ILanguageModelTask $task): string {
try {
$task->setStatus(ILanguageModelTask::STATUS_RUNNING);
$this->taskMapper->update(Task::fromLanguageModelTask($task));
$output = $task->visitProvider($provider);
$task->setOutput($task->visitProvider($provider));
$task->setStatus(ILanguageModelTask::STATUS_SUCCESSFUL);
$this->taskMapper->update(Task::fromLanguageModelTask($task));
return $output;
return $task->getOutput();
} catch (\RuntimeException $e) {
$this->logger->info('LanguageModel call using provider ' . $provider->getName() . ' failed', ['exception' => $e]);
$task->setStatus(ILanguageModelTask::STATUS_FAILED);
Expand Down
4 changes: 2 additions & 2 deletions lib/private/LanguageModel/TaskBackgroundJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ protected function run($argument) {
$taskId = $argument['taskId'];
$task = $this->languageModelManager->getTask($taskId);
try {
$output = $this->languageModelManager->runTask($task);
$event = new TaskSuccessfulEvent($task, $output);
$this->languageModelManager->runTask($task);
$event = new TaskSuccessfulEvent($task);

} catch (\RuntimeException|PreConditionNotMetException $e) {
$event = new TaskFailedEvent($task, $e->getMessage());
Expand Down
4 changes: 4 additions & 0 deletions lib/private/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@
use OC\IntegrityCheck\Helpers\AppLocator;
use OC\IntegrityCheck\Helpers\EnvironmentHelper;
use OC\IntegrityCheck\Helpers\FileAccessHelper;
use OC\LanguageModel\LanguageModelManager;
use OC\LDAP\NullLDAPProviderFactory;
use OC\KnownUser\KnownUserService;
use OC\Lock\DBLockingProvider;
Expand Down Expand Up @@ -229,6 +230,7 @@
use OCP\IUserManager;
use OCP\IUserSession;
use OCP\L10N\IFactory;
use OCP\LanguageModel\ILanguageModelManager;
use OCP\LDAP\ILDAPProvider;
use OCP\LDAP\ILDAPProviderFactory;
use OCP\Lock\ILockingProvider;
Expand Down Expand Up @@ -1470,6 +1472,8 @@ public function __construct($webRoot, \OC\Config $config) {

$this->registerAlias(IEventSourceFactory::class, EventSourceFactory::class);

$this->registerAlias(ILanguageModelManager::class, LanguageModelManager::class);

$this->connectDispatcher();
}

Expand Down
11 changes: 11 additions & 0 deletions lib/public/AppFramework/Bootstrap/IRegistrationContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\Template\ICustomTemplateProvider;
use OCP\IContainer;
use OCP\LanguageModel\ILanguageModelProvider;
use OCP\Notification\INotifier;
use OCP\Preview\IProviderV2;
use OCP\SpeechToText\ISpeechToTextProvider;
Expand Down Expand Up @@ -219,6 +220,16 @@ public function registerWellKnownHandler(string $class): void;
*/
public function registerSpeechToTextProvider(string $providerClass): void;

/**
* Register a custom LanguageModel provider class that provides a promptable language model
* through the OCP\LanguageModel APIs
*
* @param string $providerClass
* @psalm-param class-string<ILanguageModelProvider> $providerClass
* @since 27.0.0
*/
public function registerLanguageModelProvider(string $providerClass): void;

/**
* Register a custom template provider class that is able to inject custom templates
* in addition to the user defined ones
Expand Down
21 changes: 21 additions & 0 deletions lib/public/LanguageModel/AbstractLanguageModelTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,34 @@ public final function getUserId(): ?string {
return $this->userId;
}

public function jsonSerialize() {
return [
'id' => $this->getId(),
'type' => $this->getType(),
'status' => $this->getStatus(),
'userId' => $this->getUserId(),
'appId' => $this->getAppId(),
'input' => $this->getInput(),
'output' => $this->getOutput(),
];
}


public final static function fromTaskEntity(Task $taskEntity): ILanguageModelTask {
$task = self::factory($taskEntity->getType(), $taskEntity->getInput(), $taskEntity->getuserId(), $taskEntity->getAppId());
$task->setId($taskEntity->getId());
$task->setStatus($taskEntity->getStatus());
return $task;
}

/**
* @param string $type
* @param string $input
* @param string|null $userId
* @param string $appId
* @return ILanguageModelTask
* @throws \InvalidArgumentException
*/
public final static function factory(string $type, string $input, ?string $userId, string $appId): ILanguageModelTask {
if (!in_array($type, self::TYPES)) {
throw new \InvalidArgumentException('Unknown task type');
Expand Down
10 changes: 1 addition & 9 deletions lib/public/LanguageModel/Events/TaskSuccessfulEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,7 @@
*/
class TaskSuccessfulEvent extends AbstractLanguageModelEvent {

public function __construct(ILanguageModelTask $task,
private string $output) {
public function __construct(ILanguageModelTask $task) {
parent::__construct($task);
}

/**
* @return string
*/
public function getErrorMessage(): string {
return $this->output;
}
}
12 changes: 12 additions & 0 deletions lib/public/LanguageModel/ILanguageModelManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ public function hasProviders(): bool;
*/
public function getAvailableTasks(): array;

/**
* @return string[]
* @since 28.0.0
*/
public function getAvailableTaskTypes(): array;

/**
* @throws PreConditionNotMetException If no or not the requested provider was registered but this method was still called
* @throws RuntimeException If something else failed
Expand All @@ -60,5 +66,11 @@ public function runTask(ILanguageModelTask $task): string;
*/
public function scheduleTask(ILanguageModelTask $task) : void;

/**
* @param int $id The id of the task
* @return ILanguageModelTask
* @throws RuntimeException If the query failed
* @throws \ValueError If the task could not be found
*/
public function getTask(int $id): ILanguageModelTask;
}

0 comments on commit 795b097

Please sign in to comment.