*/ public function normalize(string $payload): array { if (trim($payload) === '[DONE]') { return [ProviderEvent::done('done')]; } $decoded = json_decode($payload, true); if (! is_array($decoded)) { return [ProviderEvent::error('INVALID_JSON', 'Agent provider returned invalid JSON', [ 'raw' => $payload, ])]; } $events = []; $choices = $decoded['choices'] ?? []; $firstChoice = is_array($choices) ? ($choices[0] ?? null) : null; $delta = is_array($firstChoice) ? ($firstChoice['delta'] ?? null) : null; if (is_array($delta)) { $content = $delta['content'] ?? null; if (is_string($content) && $content !== '') { $events[] = ProviderEvent::messageDelta($content); } } if (is_array($firstChoice) && array_key_exists('finish_reason', $firstChoice) && $firstChoice['finish_reason'] !== null) { $events[] = ProviderEvent::done((string) $firstChoice['finish_reason']); } if (isset($decoded['usage']) && is_array($decoded['usage'])) { $events[] = ProviderEvent::usage($decoded['usage']); } return $events; } }