From c0b1bae523f34b9dbb559fac4c1541de56081b0c Mon Sep 17 00:00:00 2001 From: csavelief Date: Wed, 16 Oct 2024 13:49:14 +0200 Subject: [PATCH] CyberBuddy - Cleanup --- .../Conversations/QuestionsAndAnswers.php | 87 +++++++++++++++++++ .../Http/Controllers/CyberBuddyController.php | 67 +++----------- 2 files changed, 101 insertions(+), 53 deletions(-) create mode 100644 app/Modules/CyberBuddy/Conversations/QuestionsAndAnswers.php diff --git a/app/Modules/CyberBuddy/Conversations/QuestionsAndAnswers.php b/app/Modules/CyberBuddy/Conversations/QuestionsAndAnswers.php new file mode 100644 index 0000000..3de8092 --- /dev/null +++ b/app/Modules/CyberBuddy/Conversations/QuestionsAndAnswers.php @@ -0,0 +1,87 @@ +historyKey = null; + $this->collection = null; + $this->message = $message; + } + + public function run(): void + { + if ($this->historyKey && $this->collection && $this->message) { + $this->answerQuestion($this->message); + } else { + + $this->historyKey = Str::uuid()->toString(); + + if (Collection::where('is_deleted', false)->count() === 1) { + + $this->collection = Collection::where('is_deleted', false)->first()->name; + + if ($this->message) { + $this->answerQuestion($this->message); + } + } else { + + $collections = Collection::where('is_deleted', false) + ->get() + ->map(fn(Collection $collection) => Button::create($collection->name)->value($collection->id)) + ->toArray(); + + $question = Question::create('Quel corpus de documents souhaitez-vous utiliser?') + ->fallback('Le corpus sélectionné est inconnue.') + ->callbackId('collection') + ->addButtons($collections); + + $this->ask($question, function (Answer $answer) { + if ($answer->isInteractiveMessageReply()) { + + $this->collection = Collection::find($answer->getValue())->name; + $this->say("Le corpus selectionné est {$this->collection}."); + + if ($this->message) { + $this->answerQuestion($this->message); + } else { + $this->waitTheNextQuestion(); + } + } + }); + } + } + } + + private function waitTheNextQuestion(): void + { + $this->ask('Que puis-je faire pour vous maintenant?', fn(Answer $response) => $this->answerQuestion($response->getText())); + } + + private function answerQuestion(string $question): void + { + $response = ApiUtils::chat_manual_demo($this->historyKey, $this->collection, $question); + if ($response['error']) { + $this->say('Une erreur s\'est produite. Veuillez réessayer ultérieurement.'); + } else { + $answer = CyberBuddyController::enhanceAnswerWithSources($response['response'], collect($response['context'] ?? [])); + $this->say($answer); + } + $this->waitTheNextQuestion(); + } +} \ No newline at end of file diff --git a/app/Modules/CyberBuddy/Http/Controllers/CyberBuddyController.php b/app/Modules/CyberBuddy/Http/Controllers/CyberBuddyController.php index a88f460..e63babf 100644 --- a/app/Modules/CyberBuddy/Http/Controllers/CyberBuddyController.php +++ b/app/Modules/CyberBuddy/Http/Controllers/CyberBuddyController.php @@ -4,6 +4,7 @@ use App\Models\YnhServer; use App\Modules\AdversaryMeter\Http\Controllers\Controller; +use App\Modules\CyberBuddy\Conversations\QuestionsAndAnswers; use App\Modules\CyberBuddy\Events\IngestFile; use App\Modules\CyberBuddy\Helpers\ApiUtilsFacade as ApiUtils; use App\Modules\CyberBuddy\Http\Requests\DownloadOneFileRequest; @@ -14,9 +15,6 @@ use App\Modules\CyberBuddy\Rules\IsValidCollectionName; use App\User; use BotMan\BotMan\BotMan; -use BotMan\BotMan\Messages\Incoming\Answer; -use BotMan\BotMan\Messages\Outgoing\Actions\Button; -use BotMan\BotMan\Messages\Outgoing\Question; use Illuminate\Http\UploadedFile; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Auth; @@ -25,6 +23,11 @@ class CyberBuddyController extends Controller { + public function __construct() + { + // + } + public static function enhanceAnswerWithSources(string $answer, Collection $sources): string { $matches = []; @@ -49,11 +52,6 @@ public static function enhanceAnswerWithSources(string $answer, Collection $sour return Str::replace(["\n\n", "\n-"], "
", $answer); } - public function __construct() - { - // - } - public function showPage() { return view('modules.cyber-buddy.page'); @@ -225,6 +223,9 @@ public function uploadManyFiles(UploadManyFilesRequest $request) public function handle(): void { $botman = app('botman'); + + $botman->hears('/stop', fn(BotMan $botman) => $botman->reply('Conversation stopped.'))->stopsConversation(); + $botman->hears('/login {username} {password}', function (BotMan $botman, string $username, string $password) { $user = $this->user($botman); if ($user) { @@ -243,6 +244,7 @@ public function handle(): void } } })->skipsConversation(); + $botman->hears('/servers', function (BotMan $botman) { $user = $this->user($botman); $servers = $user ? YnhServer::forUser($user) : collect(); @@ -296,6 +298,7 @@ public function handle(): void "); } })->skipsConversation(); + $botman->hears('/question ([a-zA-Z0-9]+) (.*)', function (BotMan $botman, string $collection, string $question) { $response = ApiUtils::ask_chunks_demo($collection, $question); if ($response['error']) { @@ -305,6 +308,7 @@ public function handle(): void $botman->reply($answer); } })->skipsConversation(); + $botman->hears('{message}', function (BotMan $botman, string $message) { if (Str::startsWith($message, "/")) { return; @@ -313,42 +317,10 @@ public function handle(): void if (!$user) { $botman->reply('Connectez-vous pour accéder à cette commande.
Pour ce faire, vous pouvez utiliser la commande /login {username} {password}'); } else { - $historyKey = $this->historyKey($botman); - $collection = $botman->userStorage()->get('collection'); - if ($collection) { - $response = ApiUtils::chat_manual_demo($historyKey, $collection, $message); - if ($response['error']) { - $botman->reply('Une erreur s\'est produite. Veuillez réessayer ultérieurement.'); - } else { - $answer = CyberBuddyController::enhanceAnswerWithSources($response['response'], collect($response['context'] ?? [])); - $botman->reply($answer); - } - } else { - $collections = \App\Modules\CyberBuddy\Models\Collection::where('is_deleted', false) - ->get() - ->map(fn(\App\Modules\CyberBuddy\Models\Collection $collection) => Button::create($collection->name)->value($collection->id)) - ->toArray(); - $question = Question::create('Pour commencer, quel corpus de documents souhaitez-vous utiliser?') - ->fallback('Le corpus sélectionné est inconnue.') - ->callbackId('collection') - ->addButtons($collections); - $botman->ask($question, function (Answer $answer) use ($botman, $historyKey, $message) { - if ($answer->isInteractiveMessageReply()) { - $collection = \App\Modules\CyberBuddy\Models\Collection::find($answer->getValue()); - $botman->reply("Le corpus selectionné est {$collection->name}. Je vais maintenant pouvoir vous répondre!"); - $botman->userStorage()->save(['collection' => $collection->name]); - $response = ApiUtils::chat_manual_demo($historyKey, $collection->name, $message); - if ($response['error']) { - $botman->reply('Une erreur s\'est produite. Veuillez réessayer ultérieurement.'); - } else { - $answer = CyberBuddyController::enhanceAnswerWithSources($response['response'], collect($response['context'] ?? [])); - $botman->reply($answer); - } - } - }); - } + $botman->startConversation(new QuestionsAndAnswers($message)); } }); + $botman->fallback(fn(BotMan $botman) => $botman->reply('Désolé, je n\'ai pas compris votre commande.')); $botman->listen(); } @@ -368,17 +340,6 @@ private function user(BotMan $botman): ?User return $user; } - private function historyKey(BotMan $botman): string - { - /** @var string $historyKey */ - $historyKey = $botman->userStorage()->get('history_key'); - if (!$historyKey) { - $historyKey = Str::uuid()->toString(); - $botman->userStorage()->save(['history_key' => $historyKey]); - } - return $historyKey; - } - private function saveOneFile(\App\Modules\CyberBuddy\Models\Collection $collection, UploadedFile $file): ?string { // Extract file metadata