First commit

This commit is contained in:
Saufi
2026-05-18 08:56:23 +08:00
commit fd3d3a4d2b
147 changed files with 22099 additions and 0 deletions

View File

@@ -0,0 +1,96 @@
<?php
namespace App\Actions\Chatbot;
use App\Jobs\LogChatInteractionJob;
use App\Models\ChatSession;
use App\Services\KnowledgeBase\RAGService;
use Illuminate\Http\Request;
use RuntimeException;
/**
* AskQuestionAction
*
* Tanggungjawab: Koordinasi satu soalan chatbot.
* 1. Urus sesi
* 2. Panggil RAGService
* 3. Dispatch log job (async)
* 4. Return result
*/
class AskQuestionAction
{
public function __construct(
private readonly RAGService $ragService
) {}
/**
* @param string $question
* @param ?int $categoryId
* @param Request $request
* @return array{
* answer: string,
* has_answer: bool,
* sources: array[],
* session_token: string,
* chat_log_id: ?int
* }
* @throws RuntimeException
*/
public function execute(
string $question,
?int $categoryId,
Request $request
): array {
// ── Urus sesi ────────────────────────────────────────────────────
$session = $this->resolveSession($request, $categoryId);
// ── Jawab soalan melalui RAG ──────────────────────────────────────
$result = $this->ragService->ask($question, $categoryId);
// ── Log secara async (jangan tangguh response) ────────────────────
LogChatInteractionJob::dispatch(
$session->session_token,
auth()->id(),
$categoryId,
$question,
$result['answer'],
$result['sources'],
$result['context_chunks'],
$result['model_used'],
$result['tokens_used'],
$result['response_time'],
$result['has_answer'],
);
return [
'answer' => $result['answer'],
'has_answer' => $result['has_answer'],
'sources' => $result['sources'],
'session_token' => $session->session_token,
];
}
private function resolveSession(Request $request, ?int $categoryId): ChatSession
{
$token = $request->session()->get('chat_session_token');
if ($token) {
$session = ChatSession::where('session_token', $token)->first();
if ($session) {
return $session;
}
}
// Buat sesi baru
$session = ChatSession::create([
'user_id' => auth()->id(),
'category_id' => $categoryId,
'ip_address' => $request->ip(),
'user_agent' => $request->userAgent(),
]);
$request->session()->put('chat_session_token', $session->session_token);
return $session;
}
}