47 lines
1.6 KiB
PHP
47 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\DTOs\ClassificationResultDTO;
|
|
use App\Models\AIDecision;
|
|
use App\Models\Article;
|
|
use App\Models\Ticket;
|
|
use App\Repositories\Contracts\ArticleRepositoryInterface;
|
|
|
|
class SemanticSearchService
|
|
{
|
|
public function __construct(
|
|
private readonly EmbeddingService $embeddingService,
|
|
private readonly ArticleRepositoryInterface $articleRepository,
|
|
private readonly AIClassifierService $classifierService,
|
|
) {}
|
|
|
|
public function findBestArticle(Ticket $ticket): array
|
|
{
|
|
$embedding = $ticket->embedding ?? $this->embeddingService->embed($ticket->message);
|
|
if ($ticket->embedding === null) {
|
|
$ticket->embedding = $embedding;
|
|
$ticket->save();
|
|
}
|
|
|
|
$candidates = $this->articleRepository->findSimilarByEmbedding($embedding, 5);
|
|
$classification = $this->classifierService->rank($ticket->message, $candidates);
|
|
|
|
$bestArticle = $classification->articleId ? Article::find($classification->articleId) : null;
|
|
|
|
AIDecision::query()->create([
|
|
'ticket_id' => $ticket->id,
|
|
'article_id' => $bestArticle?->id,
|
|
'confidence' => $classification->confidence,
|
|
'explanation' => $classification->explanation,
|
|
'raw_response' => $classification->rawResponse,
|
|
]);
|
|
|
|
return [
|
|
'best_article' => $bestArticle,
|
|
'confidence' => $classification->confidence,
|
|
'explanation' => $classification->explanation,
|
|
'top_3_candidates' => collect($candidates)->take(3)->map(fn ($c) => $c->toArray())->values()->all(),
|
|
];
|
|
}
|
|
} |