Добавлен сервис AI

Добавлен ai агент для формирования и проверки статистики
Добавлен ai агент для поддержки
This commit is contained in:
brusnitsyn
2026-07-20 16:58:21 +09:00
parent 6350159943
commit a9e032f658
21 changed files with 1546 additions and 4 deletions

View File

@@ -0,0 +1,79 @@
<?php
namespace App\Http\Controllers\Api\Ai;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\Ai\AiDispatcherService;
use App\Services\DateRangeService;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
class AiController extends Controller
{
public function __construct(
protected AiDispatcherService $dispatcher,
protected DateRangeService $dateRangeService
) {}
public function ask(Request $request)
{
$request->validate([
'question' => 'required|string|max:500',
'period_start' => 'nullable',
'period_end' => 'nullable',
]);
$user = $request->user();
$role = $user?->role ?? 'guest';
$question = $request->question;
$periodStart = $request->period_start;
$periodEnd = $request->period_end;
$dates = $this->dateRangeService->getDateRangeForUser($user, $periodStart, $periodEnd, false);
$cacheKey = 'ai_stats_' . md5("{$role}|{$periodStart}|{$periodEnd}|{$question}");
$cached = Cache::get($cacheKey);
if ($cached) {
return response()->json([
'success' => true,
'from_cache' => true,
'answer' => $cached['answer'],
'structured' => $cached['structured'] ?? null,
]);
}
try {
$result = $this->dispatcher->dispatch(
question: "Период с {$dates[0]} по {$dates[1]}. Вопрос: {$question}",
role: $role
);
// Cache::put($cacheKey, [
// 'answer' => $result['answer'],
// 'structured' => $result['structured'] ?? null,
// ], now()->addMinutes(10));
return response()->json([
'success' => true,
'from_cache' => false,
'answer' => $result['answer'],
'structured' => $result['structured'] ?? null,
]);
} catch (\Exception $e) {
Log::error('AI Dispatch Error: ' . $e->getMessage(), [
'user' => $user?->id,
'question' => $question,
'period' => "$periodStart - $periodEnd",
]);
return response()->json([
'success' => false,
'message' => 'Не удалось обработать запрос. Попробуйте позже.',
], 500);
}
}
}