validate([ 'message' => ['required', 'string', 'max:2000'], 'history' => ['nullable', 'array', 'max:20'], 'history.*.role' => ['nullable', 'string'], 'history.*.text' => ['nullable', 'string'], ]); if (! $afia->enabled()) { return response()->json(['message' => 'Afia is not available right now.'], 503); } try { $reply = $afia->chat(trim($validated['message']), $validated['history'] ?? [], $this->context($request)); } catch (\Throwable $e) { report($e); return response()->json(['message' => 'Afia could not respond right now. Please try again.'], 502); } return response()->json(['reply' => $reply]); } /** @return array */ private function context(Request $request): array { $organization = app(OrganizationResolver::class)->resolveForUser($request->user()); if ($organization === null) { return ['signed_in' => 'yes', 'setup' => 'onboarding_pending']; } $owner = $this->ownerRef($request); $ticketQuery = Ticket::owned($owner)->where('organization_id', $organization->id); return [ 'signed_in' => 'yes', 'organization' => $organization->name, 'active_queues' => ServiceQueue::owned($owner)->where('organization_id', $organization->id)->where('is_active', true)->count(), 'tickets_waiting' => (clone $ticketQuery)->where('status', 'waiting')->count(), 'tickets_serving' => (clone $ticketQuery)->whereIn('status', ['called', 'serving'])->count(), 'tickets_completed_today' => (clone $ticketQuery)->where('status', 'completed')->whereDate('completed_at', today())->count(), ]; } }