Skip to content

Commit

Permalink
CyberBuddy - Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
csavelief committed Oct 16, 2024
1 parent 96475d1 commit c0b1bae
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 53 deletions.
87 changes: 87 additions & 0 deletions app/Modules/CyberBuddy/Conversations/QuestionsAndAnswers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

namespace App\Modules\CyberBuddy\Conversations;

use App\Modules\CyberBuddy\Helpers\ApiUtilsFacade as ApiUtils;
use App\Modules\CyberBuddy\Http\Controllers\CyberBuddyController;
use App\Modules\CyberBuddy\Models\Collection;
use BotMan\BotMan\Messages\Conversations\Conversation;
use BotMan\BotMan\Messages\Incoming\Answer;
use BotMan\BotMan\Messages\Outgoing\Actions\Button;
use BotMan\BotMan\Messages\Outgoing\Question;
use Illuminate\Support\Str;

class QuestionsAndAnswers extends Conversation
{
public ?string $historyKey;
public ?string $collection;
public ?string $message;

public function __construct(string $message)
{
$this->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 <b>{$this->collection}</b>.");

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();
}
}
67 changes: 14 additions & 53 deletions app/Modules/CyberBuddy/Http/Controllers/CyberBuddyController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -25,6 +23,11 @@

class CyberBuddyController extends Controller
{
public function __construct()
{
//
}

public static function enhanceAnswerWithSources(string $answer, Collection $sources): string
{
$matches = [];
Expand All @@ -49,11 +52,6 @@ public static function enhanceAnswerWithSources(string $answer, Collection $sour
return Str::replace(["\n\n", "\n-"], "<br>", $answer);
}

public function __construct()
{
//
}

public function showPage()
{
return view('modules.cyber-buddy.page');
Expand Down Expand Up @@ -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) {
Expand All @@ -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();
Expand Down Expand Up @@ -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']) {
Expand All @@ -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;
Expand All @@ -313,42 +317,10 @@ public function handle(): void
if (!$user) {
$botman->reply('Connectez-vous pour accéder à cette commande.<br>Pour ce faire, vous pouvez utiliser la commande <b>/login {username} {password}</b>');
} 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 <b>{$collection->name}</b>. 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();
}
Expand All @@ -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
Expand Down

0 comments on commit c0b1bae

Please sign in to comment.