| 1234567891011121314151617181920212223242526272829303132333435 |
- <?php
-
- namespace App\StorePlan\Ai;
-
- use App\Ai\AiException;
-
- /**
- * Reads the JSON object out of an AI answer.
- * Models sometimes wrap JSON in ``` fences or add a sentence around it, so we cut from the first "{" to the last "}".
- */
- final class JsonAnswer
- {
- /**
- * @return array<string, mixed>
- *
- * @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;
- }
- }
|