diff --git a/app/Actions/ExtractMessageFacts.php b/app/Actions/ExtractMessageFacts.php index 7255878..b5692da 100644 --- a/app/Actions/ExtractMessageFacts.php +++ b/app/Actions/ExtractMessageFacts.php @@ -2,21 +2,24 @@ namespace App\Actions; +use App\Communication\Extraction\AccessRejected; +use App\Communication\Extraction\AiAccess; use App\Communication\Extraction\ExtractionFailed; use App\Communication\Extraction\MessageExtractor; use App\Communication\Extraction\RiskAssessment; use App\Enums\BookingTaskKind; use App\Enums\BookingTaskStatus; use App\Enums\FactSource; +use App\Enums\InboxMessageKind; use App\Enums\TenantServiceKey; +use App\Filament\Pages\AiConnection; use App\Models\Booking; use App\Models\BookingTask; use App\Models\InboundMessage; use App\Models\ServiceUsage; -use App\Models\TenantService; use App\Process\CaseLog; +use App\Support\Inbox; use App\Support\Settings; -use App\Tenancy\TenantFeatures; /** * The risk-based two-stage extraction of v0.11 (CH-14, E-035): the small model extracts facts with evidence and @@ -40,8 +43,9 @@ public function handle(InboundMessage $message): string return (string) $message->extraction_status; } - $apiKey = $this->apiKey(); - if (! app(TenantFeatures::class)->enabled(TenantServiceKey::AiGuestMail) || $apiKey === null) { + // Bring your own key: only the landlord's own, complete and not rejected access is used. + $access = AiAccess::for(Settings::tenant()); + if ($access === null) { $message->update(['extraction_status' => 'disabled']); return 'disabled'; @@ -49,19 +53,26 @@ public function handle(InboundMessage $message): string $record = ['prompt_version' => MessageExtractor::promptVersion()]; try { - $first = $this->extractor->extract($apiKey, $message, $booking); + $first = $this->extractor->extract($access, $message, $booking); $this->meter(); $record['first'] = $first; $data = $first['data']; $checked = $this->risk->facts($booking, (string) $message->body, $data); if ($this->risk->needsReview($booking, $checked, $data)) { - $review = $this->extractor->review($apiKey, $message, $booking, $data); + $review = $this->extractor->review($access, $message, $booking, $data); $this->meter(); $record['review'] = $review; $data = $review['data']; $checked = $this->markDisagreements($this->risk->facts($booking, (string) $message->body, $data), $first['data']); } + } catch (AccessRejected $exception) { + // The access is no longer valid: off for this landlord until he saves or checks it again (no retry loop). + AiAccess::markInvalid(Settings::tenant(), $exception->getMessage()); + app(Inbox::class)->post(InboxMessageKind::AiAccessRejected, 'ai-access', 'KI-Anbindung abgelehnt', $exception->getMessage().' Die automatische Auswertung ist ausgeschaltet, bis Sie den Zugang unter System › KI-Anbindung prüfen. Nachrichten liegen im Posteingang.', actionUrl: AiConnection::getUrl()); + $message->update(['extraction_status' => 'failed', 'extraction' => [...$record, 'error' => $exception->getMessage()]]); + + return 'failed'; } catch (ExtractionFailed $exception) { $message->update(['extraction_status' => 'failed', 'extraction' => [...$record, 'error' => $exception->getMessage()]]); CaseLog::record($booking, 'mail_in', 'Automatische Auswertung nicht möglich – bitte die Nachricht selbst lesen', actor: CaseLog::SYSTEM); @@ -168,17 +179,6 @@ private function finish(InboundMessage $message, array $automatic, array $propos $task?->forceFill(['note' => '„'.mb_substr((string) $message->subject, 0, 120).'“ – '.(implode(', ', $parts) ?: 'keine Angaben erkannt').'. Im Posteingang ansehen.'])->save(); } - /** - * The landlord's own key of the service, otherwise the operator's key of the installation. - */ - private function apiKey(): ?string - { - $tenant = Settings::tenant(); - $own = $tenant === null ? null : TenantService::query()->where('tenant_id', $tenant->id)->where('service', TenantServiceKey::AiGuestMail->value)->first()?->api_key; - - return filled($own) ? (string) $own : (filled(config('fewo.ai.api_key')) ? (string) config('fewo.ai.api_key') : null); - } - private function meter(): void { if (($tenant = Settings::tenant()) !== null) { diff --git a/app/Communication/Extraction/AccessRejected.php b/app/Communication/Extraction/AccessRejected.php new file mode 100644 index 0000000..a18da1e --- /dev/null +++ b/app/Communication/Extraction/AccessRejected.php @@ -0,0 +1,9 @@ +enabled(TenantServiceKey::AiGuestMail, $tenant)) { + return null; + } + + $service = self::service($tenant); + if ($service === null || $service->check_status === self::INVALID) { + return null; + } + + return self::fromService($service); + } + + /** + * The access as configured, regardless of the last check (for the check itself). + */ + public static function fromService(TenantService $service): ?self + { + $settings = (array) $service->settings; + $provider = AiProvider::tryFrom((string) ($settings['provider'] ?? '')); + $small = trim((string) ($settings['small_model'] ?? '')); + $review = trim((string) ($settings['review_model'] ?? '')); + if ($provider === null || blank($service->api_key) || $small === '' || $review === '') { + return null; + } + + return new self($provider, (string) $service->api_key, $small, $review); + } + + public static function service(Tenant $tenant): ?TenantService + { + return TenantService::query()->where('tenant_id', $tenant->id)->where('service', TenantServiceKey::AiGuestMail->value)->first(); + } + + /** + * The provider rejected the key: the extraction stays off until the landlord saves or checks the access again. + */ + public static function markInvalid(Tenant $tenant, string $message): void + { + self::service($tenant)?->forceFill(['check_status' => self::INVALID, 'check_message' => mb_substr($message, 0, 500), 'checked_at' => now()])->save(); + } + + public function __debugInfo(): array + { + return ['provider' => $this->provider->value, 'key' => '***', 'smallModel' => $this->smallModel, 'reviewModel' => $this->reviewModel]; + } +} diff --git a/app/Communication/Extraction/AiProvider.php b/app/Communication/Extraction/AiProvider.php new file mode 100644 index 0000000..367516d --- /dev/null +++ b/app/Communication/Extraction/AiProvider.php @@ -0,0 +1,42 @@ + 'Anthropic (Claude API)', + self::OpenRouter => 'OpenRouter', + }; + } + + public function endpoint(): string + { + return match ($this) { + self::Anthropic => 'https://api.anthropic.com/v1/messages', + self::OpenRouter => 'https://openrouter.ai/api/v1/chat/completions', + }; + } + + /** + * Examples for the form – suggestions only, nothing is preset. + */ + public function modelExamples(): string + { + return match ($this) { + self::Anthropic => 'z. B. klein „claude-haiku-5-5“, groß „claude-opus-5-5“', + self::OpenRouter => 'z. B. klein „anthropic/claude-haiku-5-5“, groß „anthropic/claude-opus-5-5“ (Kennung wie bei OpenRouter angezeigt)', + }; + } +} diff --git a/app/Communication/Extraction/LlmClient.php b/app/Communication/Extraction/LlmClient.php index 2291280..60227d8 100644 --- a/app/Communication/Extraction/LlmClient.php +++ b/app/Communication/Extraction/LlmClient.php @@ -3,26 +3,70 @@ namespace App\Communication\Extraction; use Illuminate\Http\Client\ConnectionException; +use Illuminate\Http\Client\RequestException; +use Illuminate\Http\Client\Response; use Illuminate\Support\Facades\Http; +use Throwable; /** - * The model connection for the extraction (Claude Messages API over HTTP – no SDK dependency, as approved in the - * v0.11 plan). One call: system prompt, the message as user content, and a JSON schema the answer must follow - * (structured outputs, `output_config.format`). Provider, endpoint and models come from config('fewo.ai'). + * The model connection of the extraction with the landlord's own access (bring your own key, v0.11): Anthropic's + * Messages API or OpenRouter's chat completions, both over HTTP to the provider's fixed endpoint (AiProvider), no SDK + * dependency. One call: system prompt, the message, and a JSON schema the answer must follow (structured outputs). + * The key travels only in the request header; it is never part of an exception, a log line or a stored result. */ class LlmClient { - /** Server-side refusal fallback (opt-in default for Claude Opus 5.5). */ - private const FALLBACK_BETA = 'server-side-fallback-2026-07-01'; + /** Server-side refusal fallback on Anthropic (opt-in default for the Claude Opus family). */ + private const ANTHROPIC_FALLBACK_BETA = 'server-side-fallback-2026-07-01'; /** * @param array $schema * @return array{data: array, model: string, usage: array} * - * @throws ExtractionFailed + * @throws AccessRejected when the provider rejects the access + * @throws ExtractionFailed for every other unusable outcome */ - public function structured(string $apiKey, string $model, string $system, string $message, array $schema, string $effort = 'medium'): array + public function structured(AiAccess $access, string $model, string $system, string $message, array $schema, string $effort = 'medium'): array { + [$headers, $body] = match ($access->provider) { + AiProvider::Anthropic => $this->anthropic($access, $model, $system, $message, $schema, $effort), + AiProvider::OpenRouter => $this->openRouter($access, $model, $system, $message, $schema), + }; + + try { + $response = Http::withHeaders($headers) + ->timeout((int) config('fewo.ai.timeout', 40)) + // Only passing problems are repeated; a rejected key or a bad request is not. + ->retry(2, 2000, fn (Throwable $exception): bool => $exception instanceof ConnectionException || ($exception instanceof RequestException && in_array($exception->response->status(), [429, 500, 502, 503, 529], true)), throw: false) + ->post($access->provider->endpoint(), $body); + } catch (ConnectionException) { + throw new ExtractionFailed('Keine Verbindung zu '.$access->provider->getLabel().'.'); + } + + if (in_array($response->status(), [401, 402, 403], true)) { + throw new AccessRejected($access->provider->getLabel().' lehnt den Zugang ab ('.$response->status().': '.$this->providerMessage($response, $access).').'); + } + if (! $response->successful()) { + throw new ExtractionFailed($access->provider->getLabel().' antwortet mit '.$response->status().' ('.$this->providerMessage($response, $access).').'); + } + + $payload = (array) $response->json(); + $text = $access->provider === AiProvider::Anthropic ? $this->anthropicText($payload) : $this->openRouterText($payload); + $data = json_decode($text, true); + if (! is_array($data)) { + throw new ExtractionFailed('Die Antwort ist kein gültiges JSON.'); + } + + return ['data' => $data, 'model' => (string) ($payload['model'] ?? $model), 'usage' => (array) ($payload['usage'] ?? [])]; + } + + /** + * @param array $schema + * @return array{0: array, 1: array} + */ + private function anthropic(AiAccess $access, string $model, string $system, string $message, array $schema, string $effort): array + { + $headers = ['x-api-key' => $access->key, 'anthropic-version' => (string) config('fewo.ai.anthropic_version'), 'content-type' => 'application/json']; $body = [ 'model' => $model, 'max_tokens' => 4096, @@ -30,37 +74,70 @@ public function structured(string $apiKey, string $model, string $system, string '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; + $headers['anthropic-beta'] = self::ANTHROPIC_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); - } + return [$headers, $body]; + } - if (! $response->successful()) { - throw new ExtractionFailed('KI-Dienst antwortet mit '.$response->status().'.'); - } + /** + * @param array $schema + * @return array{0: array, 1: array} + */ + private function openRouter(AiAccess $access, string $model, string $system, string $message, array $schema): array + { + return [ + ['Authorization' => 'Bearer '.$access->key, 'content-type' => 'application/json', 'HTTP-Referer' => (string) config('app.url'), 'X-OpenRouter-Title' => 'FewoPortal'], + [ + 'model' => $model, + 'max_tokens' => 4096, + 'messages' => [['role' => 'system', 'content' => $system], ['role' => 'user', 'content' => $message]], + 'response_format' => ['type' => 'json_schema', 'json_schema' => ['name' => 'extraction', 'strict' => true, 'schema' => $schema]], + // Only providers that honour the schema; otherwise it would merely be a hint. + 'provider' => ['require_parameters' => true], + ], + ]; + } - $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.'); - } + /** + * @param array $payload + */ + private function anthropicText(array $payload): string + { + match ($payload['stop_reason'] ?? null) { + 'refusal' => throw new ExtractionFailed('Der Anbieter hat die Auswertung abgelehnt.'), + 'max_tokens' => throw new ExtractionFailed('Die Antwort ist unvollständig.'), + default => null, + }; - $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 collect((array) ($payload['content'] ?? []))->where('type', 'text')->pluck('text')->implode(''); + } - return ['data' => $data, 'model' => (string) ($payload['model'] ?? $model), 'usage' => (array) ($payload['usage'] ?? [])]; + /** + * @param array $payload + */ + private function openRouterText(array $payload): string + { + $choice = (array) ($payload['choices'][0] ?? []); + match ($choice['finish_reason'] ?? null) { + 'content_filter' => throw new ExtractionFailed('Der Anbieter hat die Auswertung abgelehnt.'), + 'length' => throw new ExtractionFailed('Die Antwort ist unvollständig.'), + 'error' => throw new ExtractionFailed('Der Anbieter meldet einen Fehler.'), + default => null, + }; + + return (string) ($choice['message']['content'] ?? ''); + } + + /** + * The provider's own short message, cut and without anything that looks like a key. + */ + private function providerMessage(Response $response, AiAccess $access): string + { + $message = str_replace($access->key, '***', (string) ($response->json('error.message') ?? $response->json('error.type') ?? '')); + + return mb_substr((string) preg_replace('/(sk-[A-Za-z0-9_\-]{6})[A-Za-z0-9_\-]+/', '$1…', $message), 0, 200) ?: 'ohne Angabe'; } } diff --git a/app/Communication/Extraction/MessageExtractor.php b/app/Communication/Extraction/MessageExtractor.php index b7f50ab..c400090 100644 --- a/app/Communication/Extraction/MessageExtractor.php +++ b/app/Communication/Extraction/MessageExtractor.php @@ -9,7 +9,8 @@ /** * The model side of the extraction (v0.11, CH-14): versioned prompts with defined placeholders, a JSON schema for the * answer and its validation here (the answer is checked, not trusted). The small model extracts; the review model - * sees the original and the first extraction. Both only return candidates – nothing is stored or changed here. + * sees the original and the first extraction – both as configured in the landlord's own access. Both only return + * candidates – nothing is stored or changed here. */ class MessageExtractor { @@ -20,9 +21,9 @@ public function __construct(private LlmClient $client) {} * * @throws ExtractionFailed */ - public function extract(string $apiKey, InboundMessage $message, Booking $booking): array + public function extract(AiAccess $access, InboundMessage $message, Booking $booking): array { - return $this->call($apiKey, (string) config('fewo.ai.small_model'), $this->prompt('', $booking), $this->messageText($message), 'medium'); + return $this->call($access, $access->smallModel, $this->prompt('', $booking), $this->messageText($message), 'medium'); } /** @@ -31,9 +32,9 @@ public function extract(string $apiKey, InboundMessage $message, Booking $bookin * * @throws ExtractionFailed */ - public function review(string $apiKey, InboundMessage $message, Booking $booking, array $first): array + public function review(AiAccess $access, InboundMessage $message, Booking $booking, array $first): array { - return $this->call($apiKey, (string) config('fewo.ai.review_model'), $this->prompt('-review', $booking, ['first_extraction' => json_encode($first, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)]), $this->messageText($message), 'high'); + return $this->call($access, $access->reviewModel, $this->prompt('-review', $booking, ['first_extraction' => json_encode($first, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)]), $this->messageText($message), 'high'); } public static function promptVersion(): string @@ -87,13 +88,13 @@ public static function schema(): array /** * @return array{data: array{facts: list, change_requests: list, intent: string, uncertainties: list}, model: string} */ - private function call(string $apiKey, string $model, string $system, string $text, string $effort): array + private function call(AiAccess $access, string $model, string $system, string $text, string $effort): array { $schema = self::schema(); $lastError = null; // One repetition when the answer does not fit the schema, then the message goes to the landlord. for ($attempt = 1; $attempt <= 2; $attempt++) { - $result = $this->client->structured($apiKey, $model, $system, $text, $schema, $effort); + $result = $this->client->structured($access, $model, $system, $text, $schema, $effort); $lastError = $this->violation($result['data'], $schema); if ($lastError === null) { return ['data' => $result['data'], 'model' => $result['model']]; diff --git a/app/Console/Commands/EvaluateExtraction.php b/app/Console/Commands/EvaluateExtraction.php index e4a2a06..6d00da8 100644 --- a/app/Console/Commands/EvaluateExtraction.php +++ b/app/Console/Commands/EvaluateExtraction.php @@ -2,11 +2,13 @@ namespace App\Console\Commands; +use App\Communication\Extraction\AiAccess; use App\Communication\Extraction\ExtractionFailed; use App\Communication\Extraction\MessageExtractor; use App\Models\Booking; use App\Models\InboundMessage; use App\Models\Property; +use App\Models\Tenant; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; @@ -16,16 +18,19 @@ * counted separately – no system guarantees that it finds every detail, so the rate of missed ones is reported, not * hidden. Calls the configured models (costs money); meant for calibrating prompts and thresholds before go-live. */ -#[Signature('ai:evaluate {--path= : JSON file with samples} {--key= : API key (default: FEWO_AI_API_KEY)}')] +#[Signature('ai:evaluate {tenant : ID of the landlord whose own AI access is used} {--path= : JSON file with samples}')] #[Description('Evaluate the guest message extraction against sample messages (wrong values and missed details)')] class EvaluateExtraction extends Command { public function handle(MessageExtractor $extractor): int { $path = (string) ($this->option('path') ?: resource_path('prompts/extraction/evaluation/samples.json')); - $key = (string) ($this->option('key') ?: config('fewo.ai.api_key')); - if ($key === '') { - $this->error('Kein API-Schlüssel (FEWO_AI_API_KEY oder --key).'); + // Bring your own key: the landlord's own access, as configured (System › KI-Anbindung). + $tenant = Tenant::query()->find((int) $this->argument('tenant')); + $service = $tenant === null ? null : AiAccess::service($tenant); + $access = $service === null ? null : AiAccess::fromService($service); + if ($access === null) { + $this->error('Für diesen Mandanten ist keine vollständige KI-Anbindung gespeichert.'); return self::FAILURE; } @@ -41,7 +46,7 @@ public function handle(MessageExtractor $extractor): int $message = new InboundMessage(['subject' => $sample['subject'], 'body' => $sample['body']]); try { - $result = $extractor->extract($key, $message, $booking)['data']; + $result = $extractor->extract($access, $message, $booking)['data']; } catch (ExtractionFailed $exception) { $totals['failed']++; $this->warn("{$sample['id']}: {$exception->getMessage()}"); diff --git a/app/Enums/InboxMessageKind.php b/app/Enums/InboxMessageKind.php index 89f231c..3dff97e 100644 --- a/app/Enums/InboxMessageKind.php +++ b/app/Enums/InboxMessageKind.php @@ -15,6 +15,7 @@ enum InboxMessageKind: string implements HasColor, HasLabel case OfferMailFailed = 'offer_mail_failed'; case OfferRejected = 'offer_rejected'; case SyncFailed = 'sync_failed'; + case AiAccessRejected = 'ai_access_rejected'; public function getLabel(): string { @@ -24,6 +25,7 @@ public function getLabel(): string self::OfferMailFailed => 'Angebot nicht zugestellt', self::OfferRejected => 'Annahme abgewiesen', self::SyncFailed => 'Kalenderabgleich gestört', + self::AiAccessRejected => 'KI-Anbindung abgelehnt', }; } @@ -31,7 +33,7 @@ public function getColor(): string { return match ($this) { self::ChannelConflict, self::SyncFailed => 'danger', - self::ConfirmationFailed, self::OfferMailFailed, self::OfferRejected => 'warning', + self::ConfirmationFailed, self::OfferMailFailed, self::OfferRejected, self::AiAccessRejected => 'warning', }; } } diff --git a/app/Filament/Pages/AiConnection.php b/app/Filament/Pages/AiConnection.php new file mode 100644 index 0000000..d1f5fe3 --- /dev/null +++ b/app/Filament/Pages/AiConnection.php @@ -0,0 +1,196 @@ + */ + public array $data = []; + + public static function canAccess(): bool + { + return (bool) auth()->user()?->hasRole(UserRole::Admin) && app(TenantFeatures::class)->enabled(TenantServiceKey::AiGuestMail); + } + + public function mount(): void + { + $settings = (array) $this->service()?->settings; + + // The key is never put into the form. + $this->form->fill([ + 'provider' => $settings['provider'] ?? null, + 'small_model' => $settings['small_model'] ?? null, + 'review_model' => $settings['review_model'] ?? null, + 'api_key' => null, + ]); + } + + public function form(Schema $schema): Schema + { + return $schema + ->statePath('data') + ->components([ + Section::make('Ihr Zugang') + ->description('Die Auswertung von Gast-Nachrichten nutzt Ihren eigenen Zugang bei einem KI-Anbieter; die Kosten rechnet der Anbieter mit Ihnen ab. Nachrichten werden dafür an den Anbieter übermittelt – bitte Auftragsverarbeitung und Datenschutzhinweise beachten. Ohne gültigen Zugang bleibt jede Nachricht zur Prüfung im Posteingang.') + ->columns(2) + ->schema([ + Select::make('provider')->label('Anbieter')->options(AiProvider::class)->required()->live(), + TextInput::make('api_key')->label('API-Schlüssel')->password()->autocomplete('new-password')->maxLength(500) + ->placeholder(fn (): string => filled($this->service()?->api_key) ? 'gespeichert – leer lassen, um ihn zu behalten' : 'noch keiner gespeichert') + ->helperText('Wird verschlüsselt gespeichert und nie wieder angezeigt.'), + TextInput::make('small_model')->label('Modell für die erste Auswertung (klein, günstig)')->required()->maxLength(150) + ->helperText(fn (Get $get): string => self::provider($get('provider'))?->modelExamples() ?? 'Kennung des Modells beim Anbieter'), + TextInput::make('review_model')->label('Modell für die Prüfung unsicherer Fälle (groß)')->required()->maxLength(150) + ->helperText('Wird nur gefragt, wenn eine Angabe widersprüchlich, unplausibel oder unsicher ist.'), + ]), + Section::make('Stand') + ->schema([Text::make(fn (): string => $this->checkSummary())]), + ]); + } + + public function content(Schema $schema): Schema + { + return $schema->components([ + Form::make([EmbeddedSchema::make('form')]) + ->id('form') + ->livewireSubmitHandler('save') + ->footer([Actions::make([ + Action::make('save')->label('Speichern')->submit('save'), + Action::make('check')->label('Verbindung prüfen')->color('gray')->icon(Heroicon::OutlinedSignal)->action(fn () => $this->check()), + Action::make('removeKey')->label('Schlüssel entfernen')->color('danger')->requiresConfirmation() + ->modalDescription('Danach ist die automatische Auswertung aus, bis ein neuer Schlüssel gespeichert ist.') + ->visible(fn (): bool => filled($this->service()?->api_key)) + ->action(fn () => $this->removeKey()), + ])]), + ]); + } + + public function save(): void + { + $state = $this->form->getState(); + $service = $this->service() ?? new TenantService(['tenant_id' => $this->tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true]); + $service->settings = ['provider' => self::provider($state['provider'])?->value, 'small_model' => trim((string) $state['small_model']), 'review_model' => trim((string) $state['review_model'])]; + if (filled($state['api_key'] ?? null)) { + $service->api_key = trim((string) $state['api_key']); + } + // A changed access is checked again before it counts as rejected. + $service->forceFill(['check_status' => null, 'check_message' => null])->save(); + $this->data['api_key'] = null; + + Notification::make()->title('Gespeichert')->body(filled($service->api_key) ? 'Bitte „Verbindung prüfen“ ausführen.' : 'Ohne Schlüssel bleibt die Auswertung aus.')->success()->send(); + } + + /** + * Sends a minimal structured request to both models; the result is stored, the key never shown. + */ + public function check(): void + { + $service = $this->service(); + $access = $service === null ? null : AiAccess::fromService($service); + if ($access === null) { + Notification::make()->title('Unvollständig')->body('Bitte Anbieter, Schlüssel und beide Modelle speichern.')->warning()->send(); + + return; + } + + $schema = ['type' => 'object', 'additionalProperties' => false, 'required' => ['ok'], 'properties' => ['ok' => ['type' => 'boolean']]]; + try { + foreach ([$access->smallModel, $access->reviewModel] as $model) { + app(LlmClient::class)->structured($access, $model, 'Answer with {"ok": true}.', 'Test', $schema, 'low'); + } + } catch (ExtractionFailed $exception) { + $service->forceFill(['check_status' => AiAccess::INVALID, 'check_message' => mb_substr($exception->getMessage(), 0, 500), 'checked_at' => now()])->save(); + Notification::make()->title('Prüfung fehlgeschlagen')->body($exception->getMessage())->danger()->send(); + + return; + } + + $service->forceFill(['check_status' => AiAccess::OK, 'check_message' => null, 'checked_at' => now()])->save(); + Notification::make()->title('Verbindung in Ordnung')->body('Beide Modelle antworten im erwarteten Format.')->success()->send(); + } + + public function removeKey(): void + { + $this->service()?->forceFill(['api_key' => null, 'check_status' => null, 'check_message' => null, 'checked_at' => null])->save(); + Notification::make()->title('Schlüssel entfernt')->success()->send(); + } + + private static function provider(mixed $value): ?AiProvider + { + return $value instanceof AiProvider ? $value : AiProvider::tryFrom((string) $value); + } + + private function checkSummary(): string + { + $service = $this->service(); + if ($service === null || blank($service->api_key)) { + return 'Kein Zugang gespeichert – Nachrichten werden nicht automatisch ausgewertet.'; + } + + return match ($service->check_status) { + AiAccess::OK => 'Zuletzt erfolgreich geprüft am '.$service->checked_at?->format('d.m.Y, H:i').' Uhr.', + AiAccess::INVALID => 'Abgelehnt am '.$service->checked_at?->format('d.m.Y, H:i').' Uhr: '.$service->check_message.' Die automatische Auswertung ist aus.', + default => 'Gespeichert, noch nicht geprüft.', + }; + } + + private function service(): ?TenantService + { + return AiAccess::service($this->tenant()); + } + + private function tenant(): Tenant + { + $tenant = Settings::tenant(); + abort_if($tenant === null, 404); + + return $tenant; + } +} diff --git a/app/Models/TenantService.php b/app/Models/TenantService.php index 01acc8c..c33a6d7 100644 --- a/app/Models/TenantService.php +++ b/app/Models/TenantService.php @@ -7,10 +7,11 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; /** - * A service the operator switched on for a landlord. The own API key is optional and stored encrypted; - * an empty key means that the operator's key applies (no service calls it yet). + * A service the operator switched on for a landlord. A service that calls an external provider uses the landlord's + * own access (bring your own key, v0.11): the key is stored encrypted and never shown again; provider and models are + * in settings, the result of the last check beside them. */ -#[Fillable(['tenant_id', 'service', 'is_enabled', 'api_key'])] +#[Fillable(['tenant_id', 'service', 'is_enabled', 'api_key', 'settings', 'check_status', 'check_message', 'checked_at'])] class TenantService extends Model { /** @var list */ @@ -24,6 +25,8 @@ protected function casts(): array return [ 'is_enabled' => 'boolean', 'api_key' => 'encrypted', + 'settings' => 'array', + 'checked_at' => 'immutable_datetime', ]; } diff --git a/config/fewo.php b/config/fewo.php index 610c863..6db4510 100644 --- a/config/fewo.php +++ b/config/fewo.php @@ -108,12 +108,10 @@ | v0.11 extraction of guest messages (CH-14): a small model extracts, rules check, a larger model reviews risky | results. Thresholds are starting values to be calibrated with representative messages (go-live condition). */ + // Provider, key and models are each landlord's own (System › KI-Anbindung); endpoints are fixed in + // App\Communication\Extraction\AiProvider. Here only the technical limits. 'ai' => [ - 'endpoint' => env('FEWO_AI_ENDPOINT', 'https://api.anthropic.com/v1/messages'), - 'api_version' => env('FEWO_AI_API_VERSION', '2026-10-21'), - 'api_key' => env('FEWO_AI_API_KEY'), - 'small_model' => env('FEWO_AI_SMALL_MODEL', 'claude-haiku-5-5'), - 'review_model' => env('FEWO_AI_REVIEW_MODEL', 'claude-opus-5-5'), + 'anthropic_version' => env('FEWO_AI_ANTHROPIC_VERSION', '2026-10-21'), 'timeout' => (int) env('FEWO_AI_TIMEOUT', 40), 'prompt_version' => env('FEWO_AI_PROMPT_VERSION', 'v1'), // Escalate to the review model when criticality × (1 − confidence) exceeds this value. diff --git a/database/migrations/2026_11_06_130000_add_ai_access_to_tenant_services.php b/database/migrations/2026_11_06_130000_add_ai_access_to_tenant_services.php new file mode 100644 index 0000000..5948c71 --- /dev/null +++ b/database/migrations/2026_11_06_130000_add_ai_access_to_tenant_services.php @@ -0,0 +1,29 @@ +json('settings')->nullable()->after('api_key'); + $table->string('check_status', 20)->nullable()->after('settings'); + $table->string('check_message', 500)->nullable()->after('check_status'); + $table->dateTime('checked_at')->nullable()->after('check_message'); + }); + } + + public function down(): void + { + Schema::table('tenant_services', function (Blueprint $table) { + $table->dropColumn(['settings', 'check_status', 'check_message', 'checked_at']); + }); + } +}; diff --git a/docs/Prozessarchitektur/Abnahme/V011_ABNAHME_TESTSYSTEM.md b/docs/Prozessarchitektur/Abnahme/V011_ABNAHME_TESTSYSTEM.md index f134199..7a38903 100644 --- a/docs/Prozessarchitektur/Abnahme/V011_ABNAHME_TESTSYSTEM.md +++ b/docs/Prozessarchitektur/Abnahme/V011_ABNAHME_TESTSYSTEM.md @@ -10,7 +10,7 @@ ## 1. Benötigte externe Dienste (vom Betreiber bereitzustellen) |---|---|---| | **Eigenes IMAP-Postfach** für die Gästekommunikation, z. B. `anfragen@…` bei Strato | Antworten der Gäste und Portal-Mails lesen (CH-01, CH-05) | Zugangsdaten unter System › Betrieb; „Was wird gelesen?“ = „Alle Nachrichten“; „Adresse dieses Postfachs“ = die Postfachadresse. Das Postfach darf nur für Anfragen und Antworten dienen. | | **SMTP** (wie bei T23) | Rückfragen und Angebote versenden | ist eingerichtet; Testbetrieb lässt nur die Testadresse zu | -| **KI-Zugang** (Anthropic API) | Auswertung der Antworten (CH-14) | Schlüssel als `FEWO_AI_API_KEY` in `shared/.env`, danach `bash scripts/deploy.sh staging artisan optimize`. Betreiberbereich › Mandant › Dienste: „KI: Gästekommunikation“ einschalten. | +| **Eigener KI-Zugang des Mandanten** (Anthropic oder OpenRouter, Bring your own key) | Auswertung der Antworten (CH-14) | Betreiberbereich › Mandant › Dienste: „KI: Gästekommunikation“ einschalten. Danach in der Verwaltung des Mandanten **System › KI-Anbindung**: Anbieter, API-Schlüssel, Modell für die erste Auswertung und für die Prüfung eintragen, „Verbindung prüfen“. Kein zentraler Schlüssel nötig. | | **Testpostfach**, das die Testadresse empfängt und von dem aus geantwortet werden kann | Rückfragen empfangen und beantworten | System › Betrieb › Testadresse | | Scheduler (n8n, vorhanden) | `channels:fetch-mail` jede Minute, `cases:data-requests` und `messages:extract` alle fünf Minuten | läuft über den vorhandenen Auslöser; nichts zu tun | @@ -29,7 +29,8 @@ ## 2. Testkonfiguration 3. **Kanäle › Eigene Webseite:** zunächst nichts ändern, die Standards gelten. Für Fall 7 vorübergehend die Klärungsreservierung „automatisch“ auf `0` setzen. 4. **Kanäle › FeWo-direkt:** Absender der Buchungs-E-Mails eingetragen (z. B. `fewo-direkt.de`). 5. **Preise:** Für die Testzeiträume sind Saisons hinterlegt (Lücke Januar bis März 2027 vorher schließen, siehe Status vom 02.11.2026). -6. **Wirksame Einstellungen** (Expertenansicht) prüfen: In der Spalte „Eigene Webseite – Anfrage“ stehen 15 Minuten (automatisch) bzw. 180 Minuten (Freigabe) und der Rückfragemodus „Automatisch“. +6. **KI-Anbindung:** „Verbindung prüfen“ zeigt „Verbindung in Ordnung“. Gegenprobe: einen falschen Schlüssel speichern und prüfen. Erwartet wird „Prüfung fehlgeschlagen“, die Auswertung ist aus, und Nachrichten bleiben im Posteingang. Danach den richtigen Schlüssel wieder eintragen. +7. **Wirksame Einstellungen** (Expertenansicht) prüfen: In der Spalte „Eigene Webseite – Anfrage“ stehen 15 Minuten (automatisch) bzw. 180 Minuten (Freigabe) und der Rückfragemodus „Automatisch“. ## 3. Drehbuch (etwa 90 Minuten) @@ -42,7 +43,7 @@ ## 3. Drehbuch (etwa 90 Minuten) | **3** | Zweite Anfrage ohne Anschrift. Den **Link** „Angaben ergänzen“ öffnen, nur die Straße senden, dann den Rest; das Formular zweimal absenden; einen älteren Link öffnen (M02 Link, M03, M09). | Nach der Teilantwort kommt eine gezielte Folgefrage mit neuem Link; der alte Link sagt „nicht mehr aktuell“. Doppeltes Absenden erzeugt nichts doppelt. Danach geht das Angebot hinaus. | | **4** | Dritte Anfrage ohne Anschrift; nicht antworten. Im Vorgang die nächste Erinnerung ablesen. Zum Abkürzen „Wie oft wird höchstens erinnert?“ = 1 und „Nach wie vielen Stunden …“ = 1 setzen (M08). | Nach einer Stunde kommt eine Erinnerung, nach einer weiteren Stunde die Aufgabe „Fehlende Angaben selbst beim Gast nachfragen“. Die Klärungsreservierung ist nach 15 Minuten abgelaufen und wurde durch nichts verlängert; der Vorgang bleibt offen. | | **5** | Vom Testpostfach eine **neue Mail ohne Bezug** an das Postfach senden: „Haben Sie im Dezember frei?“ (M04). | Posteingang „zu klären“, kein Vorgang. „Als neue Anfrage anlegen“ erzeugt die Anfrage; sie fragt nach der Anschrift. | -| **6** | Auf eine Rückfrage antworten: „Telefon 0171 1234567. Können wir einen Tag länger bleiben?“ (M05, M06). | Telefon übernommen. Aufgabe „Änderungswunsch des Gastes prüfen“; der Zeitraum ist **unverändert**. Optional: Betreiber führt `php artisan ai:evaluate` aus und notiert die Rate übersehener Angaben. | +| **6** | Auf eine Rückfrage antworten: „Telefon 0171 1234567. Können wir einen Tag länger bleiben?“ (M05, M06). | Telefon übernommen. Aufgabe „Änderungswunsch des Gastes prüfen“; der Zeitraum ist **unverändert**. Optional: `php artisan ai:evaluate ` ausführen (nutzt den Zugang des Mandanten) und notiert die Rate übersehener Angaben. | | **7** | Klärungsreservierung „automatisch“ der Webseite auf `0`, erneut ohne Anschrift anfragen (M11, M12). | Kein Kalendereintrag. Die Rückfrage sagt „noch nicht für Sie reserviert“, ohne Reservierungsbehauptung. Danach den Wert zurücksetzen. | | **8** | Portalbuchung: FeWo-direkt-Buchungsmail an das Postfach weiterleiten bzw. die vorhandene Testmail aus T04 verwenden (M07, M12, E-036). | Wie bisher: Sperre bzw. Vorgang „Beim Portal fest gebucht“. Keine Klärungsreservierung, kein Angebot. Fehlt nur die Anschrift, heißt die Rückfrage „Ihre Buchung ist verbindlich bestätigt …“. iCal-Abgleich läuft unverändert. | | **9** | **Regression v0.10:** Drehbuch der Gesamtabnahme v0.10 §8 in Kurzform (Annahme, Auskunft und Buchungswunsch, Ändern, Storno, Aufenthalt) (M10). | Unverändert; neu ist nur, dass Angebot und Wunschbestätigung die vollständige Anschrift verlangen. | diff --git a/docs/Prozessarchitektur/Implementierungsstände/UMSETZUNGSERGEBNIS_V011.md b/docs/Prozessarchitektur/Implementierungsstände/UMSETZUNGSERGEBNIS_V011.md index b722a91..4c4b88d 100644 --- a/docs/Prozessarchitektur/Implementierungsstände/UMSETZUNGSERGEBNIS_V011.md +++ b/docs/Prozessarchitektur/Implementierungsstände/UMSETZUNGSERGEBNIS_V011.md @@ -18,7 +18,7 @@ # Umsetzungsergebnis v0.11 – integrierter MVP ## 1. Ergebnis in Kürze - Alle sechs Pakete sind umgesetzt; ein durchgehender Integrationstest deckt die ganze Kette ab: Website-Anfrage ohne Anschrift → Klärungsreservierung → Rückfrage per Mail → Antwort des Gastes per E-Mail → Zuordnung über den Antwortbezug → KI-Auswertung → Fakteneingang → automatisches Angebot mit unverändertem Angebots-Hold → Annahme → verbindliche Buchung. -- **Tests:** 759 grün, vorher 702. Neu sind 57 Tests in 7 Dateien; 11 bestehende Testdateien wurden angepasst (Anschriften in Testdaten, siehe §5). +- **Tests:** 766 grün, vorher 702. Neu sind 64 Tests in 8 Dateien; 11 bestehende Testdateien wurden angepasst (Anschriften in Testdaten, siehe §5). - Die Architekturgrenzen sind eingehalten: - keine zweite Ablaufsteuerung (`CaseAutomation`/`CaseActivities` bleiben führend); - Angebots-Hold und Annahmefristen unverändert; @@ -36,13 +36,14 @@ ## 2. Was gebaut wurde | U3 | Klärungsreservierung (`hold_purpose`), Ablauf ohne Vorgangsende, Angebot danach nur bei freiem Zeitraum | `RequestHold`, `CreateReservation`, `TakeOverPortalInquiry`, `ExpireReservations`, `Booking::clarificationState` | | U4 | Beschaffungsvorgang mit Rückfrage, Folgefrage, Erinnerung, Grenzen; Mail nach tatsächlichem Sperrstatus; signierter Ergänzungslink | `RequestCaseData`, `DataRequest`, `DataRequested`, `GuestDataController`, `cases:data-requests` | | U5 | Postfächer (`mailboxes`), Nachrichteneingang (`inbound_messages`), Zuordnung nach CH-13, „Posteingang“, Message-ID der ausgehenden Mails | `ReceiveInboundMessage`, `MessageMatcher`, `InboundMessageResource`, `MailboxReader::fetchAll`, `LogBookingMail` | -| U6 | KI-Kaskade (klein → Regeln → groß), Prompts v1, Schema, Vorschläge im Posteingang, Messbefehl | `ExtractMessageFacts`, `MessageExtractor`, `RiskAssessment`, `LlmClient`, `messages:extract`, `ai:evaluate` | +| U6 | KI-Kaskade (klein → Regeln → groß), Prompts v1, Schema, Vorschläge im Posteingang, Messbefehl; **BYOK** je Mandant (Anthropic oder OpenRouter, Seite „KI-Anbindung“, Verbindungsprüfung) | `ExtractMessageFacts`, `MessageExtractor`, `RiskAssessment`, `LlmClient`, `messages:extract`, `ai:evaluate` | **Migrationen** (alle rückwärtskompatibel, keine wurde auf einem Server ausgeführt): - `2026_11_06_090000` Kanalart; - `…100000` Faktenprotokoll, Hold-Zweck, `guests.country` ohne Standardwert; - `…110000` Beschaffungsvorgänge und Message-ID; -- `…120000` Postfächer und Nachrichteneingang. +- `…120000` Postfächer und Nachrichteneingang; +- `…130000` KI-Zugang je Mandant (BYOK). ## 3. Rückverfolgbarkeit @@ -59,7 +60,7 @@ ## 3. Rückverfolgbarkeit | **CH-09/12** Portal-Mail mit Gastdaten, beliebige Reihenfolge | Portal-Mail mit Vorgangsbezug wird ausgewertet (Quelle Portal-Mail) | `CaseFactIntakeTest` (Portal ergänzt Personenzahl), `CaseIntakeTest` unverändert grün | | **CH-10** keine pauschale Rangfolge | Regel je Feld und Phase statt Quellenrang | `CaseFactIntakeTest` | | **CH-11** iCal-Abgleich unverändert | keine Änderung an Sync, Regeln, Export | Kanal- und Sync-Tests unverändert grün | -| **CH-14** zweistufige KI, Kritikalität im Programm, Konfidenz nicht maßgeblich | `RiskAssessment`, `ExtractMessageFacts` | `MessageExtractionTest` (Widerspruch trotz Konfidenz 0,99 → Prüfung, keine Übernahme) | +| **CH-14** zweistufige KI, Kritikalität im Programm, Konfidenz nicht maßgeblich; austauschbare Modellanbindung | `RiskAssessment`, `ExtractMessageFacts`, `AiAccess`, `AiProvider` | `MessageExtractionTest` (Widerspruch trotz Konfidenz 0,99 → Prüfung, keine Übernahme), `AiAccessTest` (BYOK, OpenRouter, abgelehnter Schlüssel, feste Endpunkte) | | **CH-15/16/17** Rückfrage, Folgefrage, Erinnerung; Zähler ohne Reset; Grenzen; eine offene Rückfrage | `DataRequest`, `RequestCaseData::answered/remindDue` | `DataRequestTest::test_reminders_follow_their_limit…`, `…partly_and_then_fully` | | **CH-18** signierter, versionierter Link, Lesen schreibt nicht, idempotent | `GuestDataController` | `DataRequestTest::test_foreign_outdated_and_unsigned_links_change_nothing` | | **S1–S6** | `RequestCaseData` (S1), `ReceiveInboundMessage` (S2), `MessageMatcher` und Extraktion (S3), `DataRequested` und Link (S4), `ContributeCaseFacts` (S5), `CaseAutomation::advance` (S6) | `V011EndToEndTest` | @@ -108,8 +109,10 @@ ## 4. Technische Entscheidungen in der Umsetzung - Hat der Mandant nur eine Wohnung, ist die Wohnung damit bestimmt. Bei mehreren muss der Wohnungsname in der Nachricht stehen. 7. **Portalanfragen (A2) ohne Gastdaten** reservieren beim Eingang nichts mehr: B1 gilt auch für sie. Die Angebots-Reservierung entsteht wie bisher mit dem Angebot. 8. **KI:** - - Kleines Modell `claude-haiku-5-5`, Prüfmodell `claude-opus-5-5`, beide per Konfiguration austauschbar. - - Für das Prüfmodell ist der serverseitige Fallback bei Ablehnung aktiv (`fallbacks: "default"`). Eine Ablehnung gilt trotzdem als Fehlschlag, und die Nachricht geht an die Vermieterin. + - **Bring your own key:** Jeder Mandant wählt unter „System › KI-Anbindung“ Anbieter (Anthropic oder OpenRouter), Schlüssel, kleines und großes Modell. Es gibt keinen zentralen Schlüssel und keine Modellkennung im Code; die Endpunkte sind fest je Anbieter (`AiProvider`). + - Ein abgelehnter Schlüssel (401/402/403) schaltet die Auswertung für den Mandanten ab und meldet es; die Nachrichten bleiben im Posteingang (Test `AiAccessTest`). + - OpenRouter wird genutzt, weil der Betreiber es ausdrücklich vorgibt. Es ist ein OpenAI-kompatibler Zugang; erzwungen werden das Schema (`strict`) und nur Anbieter, die es unterstützen (`provider.require_parameters`). + - Bei Anthropic ist für Modelle der Opus-Familie der serverseitige Fallback bei Ablehnung aktiv (`fallbacks: "default"`). Eine Ablehnung gilt trotzdem als Fehlschlag, und die Nachricht geht an die Vermieterin. - Die Anbindung läuft laut Plan über den HTTP-Client. Ein offizielles PHP-SDK gibt es; seine Aufnahme wäre eine Abhängigkeitsänderung und bräuchte eine Freigabe. - Die Prompt-Anweisungen sind englisch, Werte und Oberfläche deutsch. - Bekannte Werte gehen nur maskiert an den Anbieter. @@ -129,7 +132,7 @@ ## 6. Einschränkungen - **Kalibrierung:** Der mitgelieferte Messsatz hat erst 4 Nachrichten. Schwellen (Eskalation 0,2, Mindestkonfidenz 0,85) und Prompt v1 sind Startwerte. - **Texte** der Rückfrage, Folgefrage, Erinnerung und der Linkseite sind Arbeitsfassungen ohne rechtliche Freigabe. - **Aufbewahrung:** Nachrichtentexte und Faktwerte sind verschlüsselt gespeichert, werden aber noch nicht vom Anonymisierungslauf erfasst. Eine Löschfrist ist nicht beschlossen. -- **API-Schlüssel je Mandant:** Das Datenfeld ist vorhanden, eine Oberfläche nicht. Auf dem Testsystem gilt `FEWO_AI_API_KEY`. +- **KI-Zugang:** nur über die Seite „KI-Anbindung“ des Mandanten (BYOK); ein zentraler Schlüssel ist nicht vorgesehen. - **Postfach-Zugangsdaten** werden auf „System › Betrieb“ gepflegt und in den Postfach-Datensatz übernommen. Die alten Mandantenspalten bleiben bis zur Produktivmigration als Rückfall. - **Plus-Adressen** werden nicht genutzt; die Zuordnung läuft über Message-ID und Vorgangsnummer. - Nicht Teil des MVP laut v0.11: parallele Angebote, automatische Vertragsänderungen und Teilstorno, mehrere aktive Postfächer, Messenger, generative Antworten, Gastkonto. diff --git a/docs/Prozessarchitektur/Implementierungsstände/V011_TECHNISCHE_ZIELARCHITEKTUR.md b/docs/Prozessarchitektur/Implementierungsstände/V011_TECHNISCHE_ZIELARCHITEKTUR.md index ffa2398..01b1adb 100644 --- a/docs/Prozessarchitektur/Implementierungsstände/V011_TECHNISCHE_ZIELARCHITEKTUR.md +++ b/docs/Prozessarchitektur/Implementierungsstände/V011_TECHNISCHE_ZIELARCHITEKTUR.md @@ -15,6 +15,10 @@ ## 1. Leitentscheidungen 5. **Reservierungen nutzen die vorhandene Belegungsmechanik.** Die Klärungsreservierung ist ein Hold mit eigenem Zweck (`hold_purpose`) und wird nicht als neuer Status abgebildet. 6. **Synchron und begrenzt.** Es gibt keine Queue-Worker (Strato). Abruf, Zuordnung, Extraktion und Erinnerungen laufen als begrenzte Scheduler-Schritte. Jeder Schritt ist idempotent und setzt bei einem Abbruch wieder auf. 7. **Keine neue Abhängigkeit ohne Freigabe.** Die LLM-Anbindung läuft über den Laravel-HTTP-Client hinter einer kleinen Schnittstelle. +8. **Bring your own key:** + - Jeder Mandant verbindet seinen eigenen KI-Zugang: Anbieter, Schlüssel, kleines und großes Modell. + - Es gibt keinen zentralen Betreiberschlüssel und keine im Code verdrahteten Modellkennungen. + - Die Endpunkte sind je Anbieter fest hinterlegt. ## 2. Komponenten und Datenfluss @@ -213,7 +217,7 @@ ### 3.7 KI-Extraktion (C) - `RuleExtractor`: bestehender Portalparser und einfache Muster; - `LlmExtractor`: kleines Modell; - `ReviewLlmExtractor`: großes Modell, sieht Original und Erstextraktion. - - Die Modellanbindung `LlmClient` läuft über den HTTP-Client; Anbieter, Modell und Endpunkt kommen aus der Konfiguration (austauschbar). + - Die Modellanbindung `LlmClient` läuft über den HTTP-Client mit dem **Zugang des Mandanten** (`AiAccess`, siehe 3.8). Unterstützte Anbieter sind Anthropic (Messages API) und **OpenRouter** (Chat Completions mit `response_format: json_schema`, `strict`, `provider.require_parameters`). Die Endpunkte stehen fest im Enum `AiProvider` und lassen sich nicht über Konfiguration umlenken. - **Prompts** liegen versioniert als Dateien unter `resources/prompts/extraction/.md`, mit Platzhaltern wie `{{phase}}`, `{{requested_fields}}`, `{{known_values_masked}}`, `{{message}}`. Das JSON-Schema liegt daneben (`schema.json`). Die genutzte Version wird an jedem Ergebnis gespeichert. - **Ausgabe:** schema-validiert. Fakten mit `field`, `value`, `evidence` (Zitat) und `confidence`; Änderungsabsichten; Unsicherheiten. Bei ungültigem Schema wird einmal wiederholt, danach geht die Nachricht in die Klärung. - **Programmatische Risikoprüfung** (`App\Communication\Extraction\RiskAssessment`): @@ -226,11 +230,29 @@ ### 3.7 KI-Extraktion (C) - **Ergebnis:** `ContributeCaseFacts(source: llm)`. Die KI schreibt nie selbst. - **Betrieb:** - Schalter `ai_guest_mail` wird `isWired`; - - Schlüssel je Mandant (`Tenant::services`), Verbrauch in `ServiceUsage`; + - Schlüssel, Anbieter und Modelle je Mandant (`TenantService` des Dienstes `ai_guest_mail`), Verbrauch in `ServiceUsage`; - je Lauf höchstens N Nachrichten, Zeitlimit je Aufruf; - bei Ausfall bleibt die Nachricht `needs_review` (sicherer Rückfall). - **Messung (M05):** Der Befehl `ai:evaluate` führt einen Satz anonymisierter Testnachrichten mit Sollwerten aus und meldet getrennt Fehlwerte und übersehene Angaben. Er läuft ohne Netz in den Tests mit aufgezeichneten Antworten, mit Netz nur bewusst. +### 3.8 KI-Zugang je Mandant (Bring your own key) + +- **Ort:** Seite „System › KI-Anbindung“. Sie ist nur sichtbar, wenn der Betreiber den Dienst „KI: Gästekommunikation“ für den Mandanten eingeschaltet hat. +- **Felder:** Anbieter (Anthropic oder OpenRouter), API-Schlüssel, Modell für die erste Auswertung, Modell für die Prüfung. Die Modelle sind Pflicht; der Code gibt keine vor. +- **Speicherung:** im bestehenden `TenantService` des Dienstes `ai_guest_mail`. + - Schlüssel in `api_key`, verschlüsselt und `hidden`. + - Anbieter und Modelle in `settings`. + - Prüfergebnis in `check_status`, `check_message` und `checked_at`. +- **Anzeige:** Der Schlüssel wird nie wieder angezeigt. Ein leeres Feld behält ihn, „Schlüssel entfernen“ löscht ihn. +- **Keine Schlüssel in Meldungen:** Fehlermeldungen enthalten den Schlüssel nie, auch wenn der Anbieter ihn zurückspiegelt. +- **Verbindung prüfen:** Je eine minimale Anfrage mit strukturierter Ausgabe an beide Modelle; das Ergebnis wird gespeichert. +- **Abgelehnter Zugang** (HTTP 401/402/403): + - Der Zugang gilt als ungültig, und die Auswertung ist für diesen Mandanten aus, bis er gespeichert oder erneut geprüft wird. Es gibt keine Wiederholungsschleife. + - Die Vermieterin bekommt einen Hinweis im Postfach der Verwaltung. + - Die Nachrichten bleiben im Posteingang zur Prüfung. +- **Unvollständiger Zugang:** Fehlt der Zugang oder ist er unvollständig, wird nichts gesendet (`extraction_status = disabled`). +- **Wiederholung:** Nur vorübergehende Fehler werden wiederholt (Verbindung, 429, 5xx). + ## 4. Datenmodelländerungen (Übersicht) | Änderung | Rückwärtskompatibilität | @@ -243,6 +265,7 @@ ## 4. Datenmodelländerungen (Übersicht) | `mailboxes` (neu) mit Übernahme von `tenants.mailbox_*` | Alte Spalten bleiben bis nach der Produktivmigration lesbar (wie bei `properties.hold_hours`) | | `inbound_messages` (neu), `portal_emails.inbound_message_id` (nullable) | Portalpfad unverändert | | `BookingTaskKind`: `FactConflict`, `ChangeRequest`, `DataRequestApproval`, `GuestUnresponsive` | Enum-Erweiterung | +| `tenant_services.settings`, `check_status`, `check_message`, `checked_at` (BYOK) | nullable; Schlüssel bleibt in `api_key` | ## 5. Sicherheit und Datenschutz (technisch) @@ -268,7 +291,7 @@ ## 7. Technische Entscheidungen im Rahmen der Umsetzung | T1 | Webseite als Kanal | `channels.kind = website`, nur Konfiguration (§3.1) | | T2 | Nachweis je Angabe | `case_facts` als Protokoll, Daten bleiben in `guests`/`bookings` | | T3 | Technische Standards für offene Parameter | Rückfragemodus `approval`, Folgefragen 2, Erinnerungsabstand 24 h, Link 14 Tage; überschreibbar, Go-live-Freigabe | -| T4 | LLM-Anbindung | HTTP-Client, Anbieter konfigurierbar; Vorschlag kleines/großes Modell aus derselben Modellfamilie | +| T4 | LLM-Anbindung | HTTP-Client; BYOK je Mandant: Anthropic oder OpenRouter, kleines und großes Modell frei wählbar (keine Vorgabe im Code), feste Endpunkte | | T5 | Abruf im Modus `full` | Ungelesen lassen, UID-Merkpunkt je Postfach, Deduplizierung per Message-ID | | T6 | Antwortadresse | Message-ID-Bezug und Vorgangskennung im Betreff sicher; Plus-Adresse zusätzlich, wenn der Anbieter sie zustellt | | T7 | Eingang im Testbetrieb | normal verarbeiten, sichtbar gekennzeichnet; Versand bleibt über die Schranke umgeleitet | diff --git a/docs/Prozessarchitektur/Implementierungsstände/V011_UMSETZUNGSPLAN.md b/docs/Prozessarchitektur/Implementierungsstände/V011_UMSETZUNGSPLAN.md index 28f102e..9a0af45 100644 --- a/docs/Prozessarchitektur/Implementierungsstände/V011_UMSETZUNGSPLAN.md +++ b/docs/Prozessarchitektur/Implementierungsstände/V011_UMSETZUNGSPLAN.md @@ -274,7 +274,11 @@ ### U6 – KI-Extraktion **Wiederverwendung:** `TenantService` (`ai_guest_mail`, `api_key`), `ServiceUsage`, `TenantFeatures`, `PortalMailParser` als `RuleExtractor`, Fakteneingang. **Änderungen:** -1. `Extractor`-Schnittstelle, `RuleExtractor`, `LlmExtractor`, `ReviewLlmExtractor`, `LlmClient` (HTTP, konfigurierbarer Anbieter und konfigurierbares Modell). +1. `Extractor`-Schnittstelle, `RuleExtractor`, `LlmExtractor`, `ReviewLlmExtractor`, `LlmClient` (HTTP). + - **Bring your own key:** Anbieter Anthropic oder OpenRouter, Schlüssel sowie kleines und großes Modell je Mandant über „System › KI-Anbindung“, gespeichert im `TenantService` (Schlüssel verschlüsselt, nie wieder angezeigt). + - Feste Endpunkte; Verbindungsprüfung beider Modelle. + - Ein abgelehnter Zugang schaltet die Auswertung sicher ab. + - Kein zentraler Schlüssel, keine Modellkennungen im Code. 2. Prompt-Dateien mit Version und Platzhaltern, JSON-Schema, Validierung, einmalige Wiederholung. 3. `RiskAssessment` (Kritikalität aus Feldklasse, Phase und Abweichung; Eskalationsschwelle konfigurierbar; Mindestbedingungen für die Übernahme inkl. wörtlichem Belegabgleich). Widersprüche, Änderungsabsichten in P2/P3 und fehlgeschlagene Plausibilitätsprüfungen lösen **unabhängig von der Modellkonfidenz** die weitere Prüfung aus und werden nie automatisch übernommen. Die endgültigen Schwellen folgen aus der Kalibrierung (G6). 4. Scheduler-Schritt `messages:extract` (begrenzt je Lauf, Zeitlimit); bei Ausfall bleibt `needs_review`. diff --git a/docs/STATUS.md b/docs/STATUS.md index 5006253..9c79757 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -17,7 +17,8 @@ ## Aktueller Stand (03.11.2026) - **Datenbeschaffung:** Rückfrage, Folgefrage, Erinnerung, signierter Ergänzungslink; Texte nach tatsächlichem Sperrstatus. - **Posteingang:** eigenes Postfach im Modus „alle Nachrichten“, Zuordnung nach CH-13, Klärungsansicht. - **KI-Auswertung:** kleines Modell → Regeln → Prüfmodell; nur geprüfte Angaben gehen über den Fakteneingang. Der Dienst ist je Mandant standardmäßig aus. -- **Tests:** 759 grün. +- **KI-Zugang:** Bring your own key je Mandant (Anthropic oder OpenRouter, Seite „System › KI-Anbindung“, Verbindungsprüfung), kein zentraler Schlüssel. +- **Tests:** 766 grün. Dokumente: - [Umsetzungsergebnis v0.11](Prozessarchitektur/Implementierungsstände/UMSETZUNGSERGEBNIS_V011.md) (Rückverfolgung, Entscheidungen, Einschränkungen, Go-live-Bedingungen); @@ -25,7 +26,7 @@ ## Aktueller Stand (03.11.2026) - Planung: [Soll-Ist](Prozessarchitektur/Implementierungsstände/V011_SOLL_IST_ANALYSE.md), [Zielarchitektur](Prozessarchitektur/Implementierungsstände/V011_TECHNISCHE_ZIELARCHITEKTUR.md), [Umsetzungsplan](Prozessarchitektur/Implementierungsstände/V011_UMSETZUNGSPLAN.md). **Nächste Schritte:** -1. Abstimmung mit dem Betreiber: Auslieferung von `feature/aufenthalt` über `develop` auf das Testsystem (vier neue Migrationen), eigenes IMAP-Postfach, KI-Schlüssel (`FEWO_AI_API_KEY`). +1. Abstimmung mit dem Betreiber: Auslieferung von `feature/aufenthalt` über `develop` auf das Testsystem (vier neue Migrationen), eigenes IMAP-Postfach, KI-Zugang des Mandanten unter „System › KI-Anbindung“ (Dienst vorher im Betreiberbereich einschalten). 2. Fachliche Abnahme nach dem Drehbuch, danach die Go-live-Bedingungen G1–G8. 3. Weiterhin aus v0.10: echte Mietbedingungen und Bank, Rechtsprüfung, Bedienprobe. diff --git a/tests/Feature/AiAccessTest.php b/tests/Feature/AiAccessTest.php new file mode 100644 index 0000000..0149a7e --- /dev/null +++ b/tests/Feature/AiAccessTest.php @@ -0,0 +1,183 @@ + [], 'change_requests' => [], 'intent' => 'answer', 'uncertainties' => []]; + + protected function setUp(): void + { + parent::setUp(); + + $this->travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + Mail::fake(); + TenantService::query()->create(['tenant_id' => Settings::tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true]); + app(TenantFeatures::class)->forget(); + } + + public function test_without_the_landlords_own_complete_access_nothing_is_sent(): void + { + Http::fake(); + $this->assertSame('disabled', app(ExtractMessageFacts::class)->handle($this->message())); + + $this->access(['provider' => 'openrouter', 'small_model' => 'vendor/small', 'review_model' => ''], key: 'sk-or-1'); + $this->assertSame('disabled', app(ExtractMessageFacts::class)->handle($this->message('<2@x>', 'zwei@example.org', '2026-11-20', '2026-11-23')), 'both models are required'); + + Http::assertNothingSent(); + } + + public function test_openrouter_is_called_at_its_fixed_endpoint_with_the_landlords_key_and_a_strict_schema(): void + { + $this->access(['provider' => 'openrouter', 'small_model' => 'vendor/small', 'review_model' => 'vendor/large'], key: 'sk-or-v1-geheim'); + Http::fake(['https://openrouter.ai/api/v1/chat/completions' => Http::response(['choices' => [['finish_reason' => 'stop', 'message' => ['content' => json_encode(self::EXTRACTION)]]], 'model' => 'vendor/small'])]); + + $this->assertSame('done', app(ExtractMessageFacts::class)->handle($this->message())); + + Http::assertSent(function (Request $request): bool { + $body = $request->data(); + + return $request->url() === 'https://openrouter.ai/api/v1/chat/completions' + && $request->header('Authorization')[0] === 'Bearer sk-or-v1-geheim' + && $body['model'] === 'vendor/small' + && $body['response_format']['type'] === 'json_schema' + && $body['response_format']['json_schema']['strict'] === true + && $body['provider']['require_parameters'] === true + && $body['messages'][0]['role'] === 'system'; + }); + } + + public function test_a_rejected_key_switches_the_extraction_off_and_tells_the_landlord(): void + { + $this->access(['provider' => 'openrouter', 'small_model' => 'vendor/small', 'review_model' => 'vendor/large'], key: 'sk-or-v1-abgelaufen'); + Http::fake(['*' => Http::response(['error' => ['code' => 401, 'message' => 'Invalid key sk-or-v1-abgelaufen']], 401)]); + + $first = $this->message(); + $this->assertSame('failed', app(ExtractMessageFacts::class)->handle($first)); + Http::assertSentCount(1); + + $service = AiAccess::service(Settings::tenant()); + $this->assertSame(AiAccess::INVALID, $service->check_status); + $this->assertStringNotContainsString('abgelaufen', (string) $service->check_message, 'the key is never stored in a message'); + $this->assertStringNotContainsString('abgelaufen', (string) $first->fresh()->extraction['error']); + $this->assertSame(1, InboxMessage::query()->where('kind', 'ai_access_rejected')->count()); + + $this->assertSame('disabled', app(ExtractMessageFacts::class)->handle($this->message('<2@x>', 'zwei@example.org', '2026-11-20', '2026-11-23'))); + Http::assertSentCount(1); + } + + public function test_the_landlord_configures_the_access_the_key_is_encrypted_and_never_shown(): void + { + $this->actingAs(User::factory()->create()); + + Livewire::test(AiConnection::class) + ->fillForm(['provider' => 'anthropic', 'api_key' => 'sk-ant-geheim', 'small_model' => 'claude-haiku-5-5', 'review_model' => 'claude-opus-5-5']) + ->call('save')->assertHasNoFormErrors(); + + $service = AiAccess::service(Settings::tenant()); + $this->assertSame('sk-ant-geheim', $service->api_key); + $this->assertStringNotContainsString('sk-ant-geheim', (string) DB::table('tenant_services')->where('id', $service->id)->value('api_key'), 'encrypted at rest'); + $this->assertArrayNotHasKey('api_key', $service->toArray()); + + Livewire::test(AiConnection::class) + ->assertDontSee('sk-ant-geheim') + ->assertSee('gespeichert – leer lassen') + ->fillForm(['provider' => 'anthropic', 'api_key' => '', 'small_model' => 'claude-haiku-5-5', 'review_model' => 'claude-sonnet-5-5']) + ->call('save'); + + $this->assertSame(['sk-ant-geheim', 'claude-sonnet-5-5'], [$service->fresh()->api_key, $service->fresh()->settings['review_model']]); + } + + public function test_the_check_tries_both_models_and_records_the_result(): void + { + $this->actingAs(User::factory()->create()); + $this->access(['provider' => 'anthropic', 'small_model' => 'claude-haiku-5-5', 'review_model' => 'claude-opus-5-5'], key: 'sk-ant-1'); + $broken = false; + Http::fake(['https://api.anthropic.com/v1/messages' => function () use (&$broken) { + return $broken + ? Http::response(['error' => ['type' => 'not_found_error', 'message' => 'model: claude-falsch']], 404) + : Http::response(['content' => [['type' => 'text', 'text' => '{"ok":true}']], 'stop_reason' => 'end_turn', 'model' => 'x']); + }]); + + Livewire::test(AiConnection::class)->call('check')->assertNotified('Verbindung in Ordnung'); + + Http::assertSentCount(2); + $this->assertSame(AiAccess::OK, AiAccess::service(Settings::tenant())->check_status); + + $broken = true; + AiAccess::service(Settings::tenant())->update(['settings' => ['provider' => 'anthropic', 'small_model' => 'claude-falsch', 'review_model' => 'claude-opus-5-5']]); + Livewire::test(AiConnection::class)->call('check')->assertNotified('Prüfung fehlgeschlagen'); + $this->assertSame(AiAccess::INVALID, AiAccess::service(Settings::tenant())->check_status); + } + + public function test_the_page_exists_only_when_the_operator_switched_the_service_on(): void + { + $this->actingAs(User::factory()->create()); + TenantService::query()->update(['is_enabled' => false]); + app(TenantFeatures::class)->forget(); + + $this->assertFalse(AiConnection::canAccess()); + } + + public function test_endpoints_cannot_be_redirected_by_configuration(): void + { + config(['fewo.ai.endpoint' => 'https://evil.example/v1']); + $this->access(['provider' => 'anthropic', 'small_model' => 'claude-haiku-5-5', 'review_model' => 'claude-opus-5-5'], key: 'sk-ant-1'); + Http::fake(['*' => Http::response(['content' => [['type' => 'text', 'text' => json_encode(self::EXTRACTION)]], 'stop_reason' => 'end_turn'])]); + + app(ExtractMessageFacts::class)->handle($this->message()); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api.anthropic.com/v1/messages'); + Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), 'evil.example')); + } + + /** + * @param array $settings + */ + private function access(array $settings, string $key): void + { + TenantService::query()->update(['settings' => json_encode($settings), 'api_key' => encrypt($key, false)]); + } + + private function message(string $id = '<1@x>', string $email = 'gesa@example.org', string $arrival = '2026-11-07', string $departure = '2026-11-10'): InboundMessage + { + $booking = app(CreateReservation::class)->handle(Property::sole(), new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => $email]); + + return app(ReceiveInboundMessage::class)->handle(new PortalMail($id, $email, 'Re: '.$booking->reference, 'Strandweg 1, 18225 Kühlungsborn', CarbonImmutable::now()))->fresh(); + } +} diff --git a/tests/Feature/MessageExtractionTest.php b/tests/Feature/MessageExtractionTest.php index 8240f89..c09fbbc 100644 --- a/tests/Feature/MessageExtractionTest.php +++ b/tests/Feature/MessageExtractionTest.php @@ -62,8 +62,8 @@ protected function setUp(): void Storage::fake('local'); Content::save(['contract.terms' => '

Echte Bedingungen

', 'stay.cancellation' => '

Echtes Storno

']); Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051']); - config(['fewo.ai.api_key' => 'test-key']); - TenantService::query()->create(['tenant_id' => Settings::tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true]); + TenantService::query()->create(['tenant_id' => Settings::tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true, 'api_key' => 'test-key', + 'settings' => ['provider' => 'anthropic', 'small_model' => 'claude-haiku-5-5', 'review_model' => 'claude-opus-5-5']]); app(TenantFeatures::class)->forget(); } @@ -214,7 +214,7 @@ public function test_the_evaluation_reports_missed_details(): void { $this->fakeModels(small: $this->extraction([$this->fact('guest.street', 'Lindenallee 12', 'Lindenallee 12')])); - $this->artisan('ai:evaluate')->expectsOutputToContain('Übersehene Angaben:')->assertSuccessful(); + $this->artisan('ai:evaluate', ['tenant' => Settings::tenant()->id])->expectsOutputToContain('Übersehene Angaben:')->assertSuccessful(); } public function test_the_prompt_is_versioned_and_every_placeholder_is_filled(): void diff --git a/tests/Feature/V011EndToEndTest.php b/tests/Feature/V011EndToEndTest.php index a078a84..f8caec2 100644 --- a/tests/Feature/V011EndToEndTest.php +++ b/tests/Feature/V011EndToEndTest.php @@ -56,7 +56,7 @@ protected function setUp(): void $this->property = Property::sole(); Storage::fake('local'); Content::save(['contract.terms' => '

Echte Bedingungen

', 'stay.cancellation' => '

Echtes Storno

']); - config(['mail.default' => 'array', 'fewo.spam.min_seconds' => 0, 'fewo.ai.api_key' => 'test-key']); + config(['mail.default' => 'array', 'fewo.spam.min_seconds' => 0]); Mail::swap(new MailManager($this->app)); Settings::tenant()->update([ 'bank_iban' => 'DE02120300000000202051', @@ -64,7 +64,9 @@ protected function setUp(): void 'process_defaults' => ['processing' => 'automatic', 'data_request_mode' => 'automatic'], ]); Mailbox::query()->create(['tenant_id' => Settings::tenant()->id, 'host' => 'imap.example.org', 'username' => 'anfragen@example.org', 'password' => 'x', 'mode' => Mailbox::FULL, 'address' => 'anfragen@example.org', 'is_active' => true]); - TenantService::query()->create(['tenant_id' => Settings::tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true]); + // Bring your own key: the landlord's own access (here OpenRouter), no operator key. + TenantService::query()->create(['tenant_id' => Settings::tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true, 'api_key' => 'sk-or-test', + 'settings' => ['provider' => 'openrouter', 'small_model' => 'vendor/small-model', 'review_model' => 'vendor/large-model']]); app(TenantFeatures::class)->forget(); } @@ -138,10 +140,10 @@ public function test_a_binding_portal_booking_stays_binding_and_is_only_complete */ private function fakeExtraction(array $facts): void { - Http::fake(fn (Request $request) => Http::response([ - 'id' => 'msg', 'type' => 'message', 'role' => 'assistant', 'model' => $request->data()['model'], - 'content' => [['type' => 'text', 'text' => json_encode(['facts' => $facts, 'change_requests' => [], 'intent' => 'answer', 'uncertainties' => []])]], - 'stop_reason' => 'end_turn', 'usage' => ['input_tokens' => 10, 'output_tokens' => 10], - ])); + Http::fake(['https://openrouter.ai/api/v1/chat/completions' => fn (Request $request) => Http::response([ + 'id' => 'gen', 'model' => $request->data()['model'], + 'choices' => [['finish_reason' => 'stop', 'message' => ['role' => 'assistant', 'content' => json_encode(['facts' => $facts, 'change_requests' => [], 'intent' => 'answer', 'uncertainties' => []])]]], + 'usage' => ['prompt_tokens' => 10, 'completion_tokens' => 10], + ])]); } }