* * @throws AiException */ public static function decode(string $text): array { $start = strpos($text, '{'); $end = strrpos($text, '}'); if ($start === false || $end === false || $end < $start) { throw new AiException('The AI answer contains no JSON object.', AiException::INVALID_RESULT); } $data = json_decode(substr($text, $start, $end - $start + 1), true); if (! is_array($data) || array_is_list($data)) { throw new AiException('The AI answer is not valid JSON: '.json_last_error_msg(), AiException::INVALID_RESULT); } return $data; } }