Loheide-eu-mitarbeiterplatt.../app/Filament/Pages/AiSettingsPage.php
Friederich Loheide 268742983a
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 7m17s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 7m28s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 6m32s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 6m48s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 8m51s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 8m52s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 7m31s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 52s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 7m51s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m22s
KI-Assistent: OpenAI und Ollama als Anbieter (0.35.0)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 13:57:37 +00:00

159 lines
8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Filament\Pages;
use App\Ai\AiAssistant;
use App\Support\Audit;
use App\Support\Settings;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Illuminate\Validation\ValidationException;
use Throwable;
use UnitEnum;
/**
* KI-Assistent: API-Schlüssel und Modell, z. B. für Vorschläge in Leichter Sprache.
*/
class AiSettingsPage extends Page
{
protected string $view = 'filament.pages.settings-form';
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedSparkles;
protected static string|UnitEnum|null $navigationGroup = 'System';
protected static ?int $navigationSort = 6;
protected static ?string $navigationLabel = 'KI-Assistent';
protected static ?string $title = 'KI-Assistent';
protected static ?string $slug = 'ki-assistent';
/** @var array<string, mixed>|null */
public ?array $data = [];
public static function canAccess(): bool
{
return auth()->user()?->can('ai.manage') ?? false;
}
public function mount(Settings $settings): void
{
$this->form->fill([
'enabled' => (bool) $settings->get('ai.enabled'),
'provider' => app(AiAssistant::class)->provider(),
'base_url' => $settings->get('ai.base_url'),
'model' => $settings->get('ai.model') ?: (app(AiAssistant::class)->provider() === 'anthropic' ? AiAssistant::DEFAULT_MODEL : null),
'api_key' => null,
]);
}
public function form(Schema $schema): Schema
{
$hasKey = filled(app(Settings::class)->get('ai.api_key'));
$provider = fn (Get $get) => $get('provider') ?: 'anthropic';
return $schema
->components([
Section::make('Datenschutz')
->schema([
Text::make('Wenn der Assistent eingeschaltet ist, können Redakteurinnen und Redakteure Vorschläge in Leichter Sprache anfordern. Dazu wird der Text des Beitrags bzw. der Seite an den gewählten Dienst übertragen. Bei Anthropic und OpenAI verlässt er dabei das Haus – nur mit einem Vertrag zur Auftragsverarbeitung und nicht für vertrauliche Inhalte nutzen. Mit Ollama auf einem eigenen Server bleibt der Text im eigenen Netz. Übertragen wird nur, was alle Lesenden sehen – keine Blöcke für bestimmte Zielgruppen.'),
]),
Section::make('Zugang')
->columns(2)
->schema([
Toggle::make('enabled')->label('KI-Assistent einschalten')->columnSpanFull(),
Select::make('provider')->label('Anbieter')->options(AiAssistant::PROVIDERS)->required()->selectablePlaceholder(false)->native(false)->live()
->afterStateUpdated(function (Set $set, ?string $state) {
$set('model', $state === 'anthropic' ? AiAssistant::DEFAULT_MODEL : null);
$set('base_url', null);
})
->columnSpanFull(),
TextInput::make('base_url')->label('Adresse des Dienstes')->maxLength(300)->columnSpanFull()
->visible(fn (Get $get) => $provider($get) !== 'anthropic')
->required(fn (Get $get) => $provider($get) === 'ollama')
->placeholder(fn (Get $get) => $provider($get) === 'ollama' ? AiAssistant::OLLAMA_URL : AiAssistant::OPENAI_URL)
->helperText(fn (Get $get) => $provider($get) === 'ollama'
? 'Ollama-Server, z. B. http://ki-server:11434 – vom Webserver aus erreichbar.'
: 'Leer lassen für OpenAI. Für kompatible Dienste (z. B. Mistral, IONOS, OpenRouter) die Basisadresse inkl. /v1 eintragen.'),
TextInput::make('api_key')->password()->revealable()->maxLength(300)->autocomplete('new-password')
->label(fn (Get $get) => $provider($get) === 'ollama' ? 'API-Schlüssel (optional)' : 'API-Schlüssel')
->helperText(fn (Get $get) => match (true) {
$hasKey => 'Ein Schlüssel ist gespeichert. Leer lassen, um ihn zu behalten.',
$provider($get) === 'ollama' => 'Nur nötig, wenn vor Ollama ein Zugangsschutz liegt.',
$provider($get) === 'openai' => 'Erhalten Sie beim Anbieter, bei OpenAI unter platform.openai.com → API keys.',
default => 'Erhalten Sie in der Anthropic Console unter „API Keys“.',
}),
TextInput::make('model')->label('Modell')->required()->maxLength(100)
->placeholder(fn (Get $get) => match ($provider($get)) {
'ollama' => 'z. B. llama3.1:8b oder mistral-small',
'openai' => 'Modellname laut Anbieter',
default => AiAssistant::DEFAULT_MODEL,
})
->helperText(fn (Get $get) => match ($provider($get)) {
'ollama' => 'Das Modell muss auf dem Server geladen sein („ollama pull …“). Für gute Leichte Sprache mindestens ein mittelgroßes Modell mit gutem Deutsch.',
'openai' => 'Genau so, wie der Anbieter es nennt.',
default => 'Standard: '.AiAssistant::DEFAULT_MODEL,
}),
]),
])
->statePath('data');
}
public function save(AiAssistant $ai, Settings $settings): void
{
$state = $this->form->getState();
if ($state['enabled'] && ($state['provider'] ?? 'anthropic') !== 'ollama' && blank($state['api_key']) && blank($settings->get('ai.api_key'))) {
throw ValidationException::withMessages(['data.api_key' => 'Bitte einen API-Schlüssel eingeben.']);
}
$ai->save($state);
$this->data['api_key'] = null;
Audit::log('ai.settings_updated', ['enabled' => (bool) $state['enabled'], 'provider' => $state['provider'] ?? 'anthropic', 'model' => $state['model']]);
Notification::make()->success()->title('KI-Assistent gespeichert')->send();
}
protected function getHeaderActions(): array
{
return [
Action::make('test')
->label('Verbindung testen')
->icon(Heroicon::OutlinedSignal)
->color('gray')
->action(function (AiAssistant $ai) {
try {
$ai->test();
Notification::make()->success()->title('Verbindung klappt')->body(AiAssistant::PROVIDERS[$ai->provider()].' · Modell: '.$ai->model())->send();
} catch (Throwable $e) {
Notification::make()->danger()->title('Verbindung fehlgeschlagen')->body($e->getMessage())->persistent()->send();
}
}),
Action::make('forget')
->label('Schlüssel löschen')
->icon(Heroicon::OutlinedTrash)
->color('danger')
->requiresConfirmation()
->visible(fn () => filled(app(Settings::class)->get('ai.api_key')))
->action(function (AiAssistant $ai) {
$ai->forgetKey();
$this->data['enabled'] = false;
Audit::log('ai.key_removed');
Notification::make()->success()->title('Schlüssel gelöscht, Assistent ausgeschaltet')->send();
}),
];
}
}