$schema * @return array{data: array, model: string, usage: array} * * @throws ExtractionFailed */ public function structured(string $apiKey, string $model, string $system, string $message, array $schema, string $effort = 'medium'): array { $body = [ 'model' => $model, 'max_tokens' => 4096, 'system' => $system, 'messages' => [['role' => 'user', 'content' => $message]], 'output_config' => ['effort' => $effort, 'format' => ['type' => 'json_schema', 'schema' => $schema]], ]; $headers = ['x-api-key' => $apiKey, 'anthropic-version' => (string) config('fewo.ai.api_version'), 'content-type' => 'application/json']; if (str_starts_with($model, 'claude-opus-')) { $body['fallbacks'] = 'default'; $headers['anthropic-beta'] = self::FALLBACK_BETA; } try { $response = Http::withHeaders($headers)->timeout((int) config('fewo.ai.timeout', 40))->retry(2, 2000, throw: false)->post((string) config('fewo.ai.endpoint'), $body); } catch (ConnectionException $exception) { throw new ExtractionFailed('Keine Verbindung zum KI-Dienst: '.$exception->getMessage(), previous: $exception); } if (! $response->successful()) { throw new ExtractionFailed('KI-Dienst antwortet mit '.$response->status().'.'); } $payload = (array) $response->json(); $stop = $payload['stop_reason'] ?? null; if ($stop === 'refusal') { throw new ExtractionFailed('Der KI-Dienst hat die Auswertung abgelehnt.'); } if ($stop === 'max_tokens') { throw new ExtractionFailed('Die Antwort des KI-Dienstes ist unvollständig.'); } $text = collect((array) ($payload['content'] ?? []))->where('type', 'text')->pluck('text')->implode(''); $data = json_decode($text, true); if (! is_array($data)) { throw new ExtractionFailed('Die Antwort des KI-Dienstes ist kein gültiges JSON.'); } return ['data' => $data, 'model' => (string) ($payload['model'] ?? $model), 'usage' => (array) ($payload['usage'] ?? [])]; } }