Files
onboard/app/Http/Controllers/Api/Ai/AiController.php
brusnitsyn a9e032f658 Добавлен сервис AI
Добавлен ai агент для формирования и проверки статистики
Добавлен ai агент для поддержки
2026-07-20 16:58:21 +09:00

80 lines
2.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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);
}
}
}