Deploy FeWo mit PipelineManager / deploy (push) Successful in 5m11s
- Jeder Mandant verbindet unter „System › KI-Anbindung“ seinen eigenen Zugang: Anbieter (Anthropic oder OpenRouter), API-Schlüssel, Modell für die erste Auswertung und für die Prüfung – keine Modellkennung im Code, kein zentraler Betreiberschlüssel (FEWO_AI_API_KEY entfällt). - Gespeichert im bestehenden TenantService (ai_guest_mail): Schlüssel verschlüsselt, nie wieder angezeigt, nie in Meldungen; Anbieter/Modelle in settings, Prüfergebnis in check_status/check_message/checked_at. - Feste Endpunkte je Anbieter (AiProvider), nicht konfigurierbar. OpenRouter mit response_format json_schema (strict) und provider.require_parameters. - „Verbindung prüfen“ testet beide Modelle. Ein abgelehnter Zugang (401/402/403) schaltet die Auswertung für den Mandanten ab, meldet es im Postfach der Verwaltung; Nachrichten bleiben zur Prüfung im Posteingang. - Zweistufige Extraktion und ihre Sicherheitsregeln unverändert. - Zielarchitektur §3.8, Umsetzungsplan U6, Bericht, Drehbuch, Status. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
197 lines
8.9 KiB
PHP
197 lines
8.9 KiB
PHP
<?php
|
||
|
||
namespace App\Filament\Pages;
|
||
|
||
use App\Communication\Extraction\AiAccess;
|
||
use App\Communication\Extraction\AiProvider;
|
||
use App\Communication\Extraction\ExtractionFailed;
|
||
use App\Communication\Extraction\LlmClient;
|
||
use App\Enums\TenantServiceKey;
|
||
use App\Enums\UserRole;
|
||
use App\Filament\Concerns\FollowsAdminMode;
|
||
use App\Models\Tenant;
|
||
use App\Models\TenantService;
|
||
use App\Support\Settings;
|
||
use App\Tenancy\TenantFeatures;
|
||
use BackedEnum;
|
||
use Filament\Actions\Action;
|
||
use Filament\Forms\Components\Select;
|
||
use Filament\Forms\Components\TextInput;
|
||
use Filament\Notifications\Notification;
|
||
use Filament\Pages\Page;
|
||
use Filament\Schemas\Components\Actions;
|
||
use Filament\Schemas\Components\EmbeddedSchema;
|
||
use Filament\Schemas\Components\Form;
|
||
use Filament\Schemas\Components\Section;
|
||
use Filament\Schemas\Components\Text;
|
||
use Filament\Schemas\Components\Utilities\Get;
|
||
use Filament\Schemas\Schema;
|
||
use Filament\Support\Icons\Heroicon;
|
||
use UnitEnum;
|
||
|
||
/**
|
||
* "KI-Anbindung" (v0.11, bring your own key): the landlord connects his own AI access for the evaluation of guest
|
||
* messages – provider (Anthropic or OpenRouter), key and the two models. The key is stored encrypted and never shown
|
||
* again; an empty field keeps it. A check sends a tiny test request to both models. The page only exists when the
|
||
* operator switched the service on for this landlord.
|
||
*/
|
||
class AiConnection extends Page
|
||
{
|
||
use FollowsAdminMode;
|
||
|
||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedSparkles;
|
||
|
||
protected static string|UnitEnum|null $navigationGroup = 'System';
|
||
|
||
protected static ?string $navigationLabel = 'KI-Anbindung';
|
||
|
||
protected static ?string $title = 'KI-Anbindung';
|
||
|
||
protected static ?string $slug = 'ki-anbindung';
|
||
|
||
protected static ?int $navigationSort = 3;
|
||
|
||
/** @var array<string, mixed> */
|
||
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;
|
||
}
|
||
}
|