Skip to content

Commit

Permalink
feat: Improve error logger & get models from api
Browse files Browse the repository at this point in the history
  • Loading branch information
datlechin committed Sep 8, 2024
1 parent d595fa3 commit b929579
Show file tree
Hide file tree
Showing 8 changed files with 570 additions and 634 deletions.
11 changes: 8 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
"license": "MIT",
"require": {
"php": "^8.1",
"flarum/core": "^1.7.0",
"openai-php/client": "^0.3.5"
"flarum/core": "^1.8.5",
"openai-php/client": "^0.10.1"
},
"authors": [
{
Expand Down Expand Up @@ -59,5 +59,10 @@
}
},
"minimum-stability": "dev",
"prefer-stable": true
"prefer-stable": true,
"config": {
"allow-plugins": {
"php-http/discovery": true
}
}
}
3 changes: 3 additions & 0 deletions extend.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
->js(__DIR__.'/js/dist/admin.js')
->css(__DIR__.'/less/admin.less'),

(new Extend\Routes('api'))
->get('/datlechin-chatgpt/models', 'datlechin-chatgpt.models', Api\Controller\ShowOpenAiModelsController::class),

new Extend\Locales(__DIR__.'/locale'),

(new Extend\Settings())
Expand Down
39 changes: 24 additions & 15 deletions js/src/admin/components/ChatGPTSettings.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,31 @@
import app from 'flarum/admin/app';
import ExtensionPage from 'flarum/admin/components/ExtensionPage';
import Stream from 'flarum/common/utils/Stream';

export default class ChatGPTSettings extends ExtensionPage {
oninit(vnode) {
loading: boolean = true;
models: Stream<Record<string, string>>;

oninit(vnode: any) {
super.oninit(vnode);
this.loading = false;
this.models = Stream<Record<string, string>>({});

app
.request({
url: `${app.forum.attribute('apiUrl')}/datlechin-chatgpt/models`,
method: 'GET',
})
.then((response: any) => {
const models: Record<string, string> = {};
response.forEach((model: { id: string }) => {
models[model.id] = model.id;
});
this.models(models);
})
.finally(() => {
this.loading = false;
m.redraw();
});
}

content() {
Expand All @@ -24,19 +45,7 @@ export default class ChatGPTSettings extends ExtensionPage {
{this.buildSettingComponent({
setting: 'datlechin-chatgpt.model',
type: 'dropdown',
options: {
'text-davinci-003': 'text-davinci-003',
'gpt-3.5-turbo': 'gpt-3.5-turbo',
'gpt-3.5-turbo-16k': 'gpt-3.5-turbo-16k',
'text-davinci-002': 'text-davinci-002',
'code-davinci-002': 'code-davinci-002',
'gpt-4': 'gpt-4',
'gpt-4-0613': 'gpt-4-0613',
'gpt-4-32k': 'gpt-4-32k',
'gpt-4-32k-0613': 'gpt-4-32k-0613',
'gpt-4-0314': 'gpt-4-0314',
'gpt-4-32k-0314': 'gpt-4-32k-0314',
},
options: this.models(),
label: app.translator.trans('datlechin-chatgpt.admin.settings.model_label'),
help: app.translator.trans('datlechin-chatgpt.admin.settings.model_help', {
a: <a href="https://platform.openai.com/docs/models/overview" target="_blank" rel="noopener" />,
Expand Down
989 changes: 444 additions & 545 deletions js/yarn.lock

Large diffs are not rendered by default.

33 changes: 33 additions & 0 deletions src/Api/Controller/ShowOpenAiModelsController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace Datlechin\FlarumChatGPT\Api\Controller;

use Datlechin\FlarumChatGPT\OpenAIClient;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\Cache\Store;
use Laminas\Diactoros\Response\JsonResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class ShowOpenAiModelsController implements RequestHandlerInterface
{
public function __construct(
protected OpenAIClient $client,
protected Store $cache,
protected SettingsRepositoryInterface $settings
) {
}

public function handle(ServerRequestInterface $request): ResponseInterface
{
$data = $this->cache->get('datlechin-chatgpt.models') ?: [];

if (empty($data) && $this->settings->get('datlechin-chatgpt.api_key')) {
$data = $this->client->models()->list()->data;
$this->cache->put('datlechin-chatgpt.models', $data, 60 * 60);
}

return new JsonResponse($data);
}
}
35 changes: 9 additions & 26 deletions src/Listener/PostChatGPTAnswer.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,23 @@
namespace Datlechin\FlarumChatGPT\Listener;

use Carbon\Carbon;
use Datlechin\FlarumChatGPT\OpenAI;
use Datlechin\FlarumChatGPT\OpenAIClient;
use Flarum\Discussion\Event\Started;
use Flarum\Foundation\DispatchEventsTrait;
use Flarum\Post\CommentPost;
use Flarum\Settings\SettingsRepositoryInterface;
use Flarum\User\Exception\PermissionDeniedException;
use Flarum\User\User;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Arr;

class PostChatGPTAnswer
{
use DispatchEventsTrait;

protected $events;

protected SettingsRepositoryInterface $settings;

protected OpenAI $openAI;

public function __construct(Dispatcher $events, SettingsRepositoryInterface $settings, OpenAI $openAI)
{
$this->events = $events;
$this->settings = $settings;
$this->openAI = $openAI;
public function __construct(
protected Dispatcher $events,
protected SettingsRepositoryInterface $settings,
protected OpenAIClient $client
) {
}

/**
* @throws PermissionDeniedException
*/
public function handle(Started $event): void
{
if (! $this->settings->get('datlechin-chatgpt.enable_on_discussion_started', true)) {
Expand All @@ -41,7 +28,7 @@ public function handle(Started $event): void

$discussion = $event->discussion;
$actor = $event->actor;
$enabledTagIds = $this->settings->get('datlechin-chatgpt.enabled-tags', []);
$enabledTagIds = $this->settings->get('datlechin-chatgpt.enabled-tags', '[]');

if ($enabledTagIds = json_decode($enabledTagIds, true)) {
$discussion = $event->discussion;
Expand All @@ -57,13 +44,9 @@ public function handle(Started $event): void
$user = User::find($userId);
}

$userPromptId = $user->id ?? $actor->id;

$actor->assertCan('useChatGPTAssistant', $discussion);

$firstPost = $discussion->firstPost;

$content = $this->openAI->completions($firstPost->content);
$content = $this->client->completions($discussion->firstPost->content);

if (! $content) {
return;
Expand All @@ -72,7 +55,7 @@ public function handle(Started $event): void
$post = CommentPost::reply(
$discussion->id,
$content,
$userPromptId,
$user->id ?? $actor->id,
null,
);

Expand Down
45 changes: 0 additions & 45 deletions src/OpenAI.php

This file was deleted.

49 changes: 49 additions & 0 deletions src/OpenAIClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace Datlechin\FlarumChatGPT;

use Exception;
use Flarum\Settings\SettingsRepositoryInterface;
use OpenAI;
use OpenAI\Client;
use OpenAI\Resources\Models;
use Psr\Log\LoggerInterface;

class OpenAIClient
{
public ?Client $client = null;

public function __construct(protected SettingsRepositoryInterface $settings, protected LoggerInterface $logger)
{
$apiKey = $this->settings->get('datlechin-chatgpt.api_key');

if (empty($apiKey)) {
$this->logger->error('OpenAI API key is not set.');
return;
}

$this->client = OpenAI::client($apiKey);
}

public function completions(string $content = null): ?string
{
try {
$result = $this->client->completions()->create([
'model' => $this->settings->get('datlechin-chatgpt.model', 'text-davinci-003'),
'prompt' => $content,
'max_tokens' => (int) $this->settings->get('datlechin-chatgpt.max_tokens', 100),
]);
} catch (Exception $e) {
$this->logger->error($e->getMessage());

return null;
}

return $result->choices[0]->text;
}

public function models(): Models
{
return $this->client->models();
}
}

0 comments on commit b929579

Please sign in to comment.