value => null, ModerationService::OPENAI->value => $this->validateForOpenAI($attribute, $value, $fail), default => throw new RuntimeException('Invalid moderation service config value'), }; } /** * Apply content filtering with OpenAI Moderation API. * * @param string $attribute * @param mixed $value * @param Closure(string): PotentiallyTranslatedString $fail * @return void */ private function validateForOpenAI(string $attribute, mixed $value, Closure $fail): void { try { $response = Http::acceptJson() ->withToken(Config::get(ServiceConstants::OPENAI_BEARER_TOKEN)) ->post('https://api.openai.com/v1/moderations', ['input' => $value]) ->throw() ->json(); $flagged = Arr::get($response, 'results.0.flagged'); if (! empty($flagged)) { $fail(__('validation.moderation', ['attribute' => $attribute])); } } catch (Exception $e) { // Don't block site functionality if third-party service is down Log::error($e->getMessage(), ['value' => $value]); } } }