Loheide-eu-mitarbeiterplatt.../app/Ai/AiAssistant.php
Friederich Loheide 9d8bdc08ce
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Has been skipped
CI / PHP 8.4 / mariadb:10.6 (pull_request) Has been skipped
CI / PHP 8.3 / mariadb:11.4 (pull_request) Has been skipped
CI / PHP 8.4 / mariadb:11.4 (pull_request) Has been skipped
CI / PHP 8.3 / mysql:8.0 (pull_request) Has been skipped
CI / PHP 8.4 / mysql:8.0 (pull_request) Has been skipped
CI / PHP 8.3 / mysql:8.4 (pull_request) Has been skipped
CI / PHP 8.4 / mysql:8.4 (pull_request) Has been skipped
CI / Browser-Tests (pull_request) Failing after 19m38s
CI / PHP 8.3 / mysql:8.4-1 (pull_request) Successful in 24m17s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 9m13s
CI / Build-Artefakte aktuell (pull_request) Successful in 6m4s
Frag das Portal (0.64.0)
Antworten mit Quellen aus Seiten, QM-Dokumenten, Glossar und Neuigkeiten –
nur aus Sichtbarem, über den KI-Assistenten (Anthropic, OpenAI, Ollama).
Wissensquellen als Registry für Plugins, Auswertung ohne Personenbezug.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 18:08:35 +00:00

272 lines
11 KiB
PHP
Raw Permalink 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\Ai;
use App\Support\SafeOutbound;
use App\Support\Settings;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
use RuntimeException;
use Throwable;
/**
* KI-Assistent, z. B. für Vorschläge in Leichter Sprache. Anbieter wählbar:
* Anthropic (Claude), OpenAI bzw. OpenAI-kompatible Dienste und Ollama auf einem
* eigenen Server. Nur aktiv, wenn die Administration ihn eingerichtet hat.
*/
class AiAssistant
{
public const PROVIDERS = [
'anthropic' => 'Anthropic (Claude)',
'openai' => 'OpenAI oder OpenAI-kompatibler Dienst',
'ollama' => 'Ollama (eigener Server)',
];
public const ENDPOINT = 'https://api.anthropic.com/v1/messages';
public const OPENAI_URL = 'https://api.openai.com/v1';
public const OLLAMA_URL = 'http://localhost:11434';
public const DEFAULT_MODEL = 'claude-sonnet-5';
public const MAX_INPUT = 20000;
public function __construct(private readonly Settings $settings) {}
public function provider(): string
{
$provider = (string) $this->settings->get('ai.provider', 'anthropic');
return isset(self::PROVIDERS[$provider]) ? $provider : 'anthropic';
}
public function available(): bool
{
if (! $this->settings->get('ai.enabled') || ($this->provider() !== 'anthropic' && blank($this->settings->get('ai.model')))) {
return false;
}
// Ollama braucht keinen Schlüssel
return $this->provider() === 'ollama' || filled($this->settings->get('ai.api_key'));
}
public function model(): string
{
return (string) ($this->settings->get('ai.model') ?: ($this->provider() === 'anthropic' ? self::DEFAULT_MODEL : ''));
}
public function baseUrl(): string
{
return rtrim((string) ($this->settings->get('ai.base_url') ?: match ($this->provider()) {
'openai' => self::OPENAI_URL,
'ollama' => self::OLLAMA_URL,
default => 'https://api.anthropic.com',
}), '/');
}
/** Verlässt der Text bei diesem Anbieter das eigene Netz? */
public function isExternal(): bool
{
return $this->provider() !== 'ollama';
}
/**
* @param array{enabled: bool, provider?: ?string, base_url?: ?string, model: ?string, api_key: ?string} $values
*/
public function save(array $values): void
{
$provider = isset(self::PROVIDERS[$values['provider'] ?? '']) ? $values['provider'] : 'anthropic';
$baseUrl = $provider === 'anthropic' || blank($values['base_url'] ?? null) ? null : rtrim(trim($values['base_url']), '/');
if ($baseUrl !== null) {
self::assertAllowedUrl($provider, $baseUrl);
}
// Gespeicherter Schlüssel gilt nur für dasselbe Ziel – sonst ließe er sich an einen eigenen Server umleiten
$destinationChanged = $provider !== $this->provider() || $baseUrl !== ($this->settings->get('ai.base_url') ?: null);
$keepKey = blank($values['api_key'] ?? null) && ! $destinationChanged;
if (blank($values['api_key'] ?? null) && $destinationChanged && filled($this->settings->get('ai.api_key')) && $provider !== 'ollama' && ($values['enabled'] ?? false)) {
throw ValidationException::withMessages(['data.api_key' => 'Anbieter oder Adresse wurden geändert – bitte den API-Schlüssel erneut eingeben.']);
}
$data = [
'ai.enabled' => (bool) $values['enabled'],
'ai.provider' => $provider,
'ai.base_url' => $baseUrl,
'ai.model' => filled($values['model'] ?? null) ? trim($values['model']) : null,
];
if (filled($values['api_key'] ?? null)) {
$data['ai.api_key'] = Crypt::encryptString(trim($values['api_key']));
} elseif (! $keepKey) {
$data['ai.api_key'] = null;
}
$this->settings->setMany($data);
}
public function forgetKey(): void
{
$this->settings->setMany(['ai.api_key' => null, 'ai.enabled' => $this->provider() === 'ollama' && (bool) $this->settings->get('ai.enabled')]);
}
/**
* OpenAI-kompatible Dienste nur über HTTPS und öffentliche Adressen. Ollama darf im
* eigenen Netz laufen – aber nie an Link-Local-Adressen (Metadaten-Dienste der Cloud).
*/
public static function assertAllowedUrl(string $provider, string $url): void
{
$scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));
$host = strtolower(trim((string) parse_url($url, PHP_URL_HOST), '[]'));
$fail = fn (string $message) => throw ValidationException::withMessages(['data.base_url' => $message]);
if ($host === '' || parse_url($url, PHP_URL_USER) !== null || parse_url($url, PHP_URL_QUERY) !== null) {
$fail('Bitte eine gültige Adresse angeben, z. B. '.($provider === 'ollama' ? self::OLLAMA_URL : self::OPENAI_URL).'.');
}
if ($provider === 'openai' && ($scheme !== 'https' || ! SafeOutbound::isPublicUrl($url, ['https']))) {
$fail('OpenAI-kompatible Dienste nur über HTTPS und eine öffentliche Adresse. Für einen Server im eigenen Netz „Ollama“ wählen.');
}
if ($provider === 'ollama') {
$ips = filter_var($host, FILTER_VALIDATE_IP) ? [$host] : (gethostbynamel($host) ?: []);
if (! in_array($scheme, ['http', 'https'], true) || $host === 'metadata.google.internal'
|| collect($ips)->contains(fn ($ip) => str_starts_with($ip, '169.254.') || str_starts_with(strtolower($ip), 'fe80:'))) {
$fail('Diese Adresse ist nicht erlaubt.');
}
}
}
/**
* Vorschlag in Leichter Sprache als einfaches HTML (h2, p, ul/li, strong).
*/
public function easyLanguage(string $title, string $text): string
{
$text = mb_substr(trim($text), 0, self::MAX_INPUT);
if ($text === '') {
throw new RuntimeException('Der Inhalt enthält keinen Text, der übertragen werden könnte.');
}
return $this->complete(
<<<'PROMPT'
Du übersetzt Texte aus dem Intranet eines Unternehmens in Leichte Sprache nach den Regeln des Netzwerks Leichte Sprache.
Regeln:
- Kurze Sätze. Ein Gedanke pro Satz. Keine Nebensätze, wenn es sich vermeiden lässt.
- Einfache, bekannte Wörter. Fachwörter und Abkürzungen erklären oder ersetzen.
- Aktive Formulierungen, keine Verneinungen wie „nicht unwichtig“.
- Die Leserinnen und Leser direkt ansprechen („Sie“).
- Zahlen als Ziffern, Datum ausgeschrieben (z. B. „am 3. Oktober“).
- Lange Wörter mit Bindestrich trennen (z. B. „Mitarbeiter-Versammlung“).
- Wichtiges zuerst. Nichts hinzuerfinden, nichts Wichtiges weglassen.
- Gliedern mit kurzen Zwischenüberschriften und Listen.
Antworte ausschließlich mit HTML aus diesen Elementen: <h2>, <p>, <ul>, <li>, <strong>.
Kein Markdown, keine Einleitung, keine Erklärung. Antworte auf Deutsch.
PROMPT,
"Titel: {$title}\n\nText:\n{$text}",
);
}
/**
* Freie Anfrage mit Systemanweisung, z. B. für „Frag das Portal“. Antwort als Text.
*/
public function ask(string $system, string $user): string
{
return $this->complete($system, mb_substr($user, 0, self::MAX_INPUT));
}
/**
* Verbindung prüfen (Administration).
*/
public function test(): string
{
return $this->complete('Antworte nur mit dem Wort „Verbunden“.', 'Test');
}
private function complete(string $system, string $user): string
{
if (! $this->available()) {
throw new RuntimeException('Der KI-Assistent ist nicht eingerichtet.');
}
// Lokale Modelle brauchen mitunter länger
@set_time_limit(360);
try {
$response = match ($this->provider()) {
'openai' => $this->client(120)->withToken($this->key())
->post($this->baseUrl().'/chat/completions', [
'model' => $this->model(),
'messages' => [['role' => 'system', 'content' => $system], ['role' => 'user', 'content' => $user]],
]),
'ollama' => $this->client(300)->when(filled($this->settings->get('ai.api_key')), fn ($http) => $http->withToken($this->key()))
->post($this->baseUrl().'/api/chat', [
'model' => $this->model(),
'stream' => false,
'messages' => [['role' => 'system', 'content' => $system], ['role' => 'user', 'content' => $user]],
]),
default => $this->client(120)->withHeaders(['x-api-key' => $this->key(), 'anthropic-version' => '2023-06-01'])
->post(self::ENDPOINT, [
'model' => $this->model(),
'max_tokens' => 4096,
'system' => $system,
'messages' => [['role' => 'user', 'content' => $user]],
]),
};
} catch (RuntimeException $e) {
throw $e;
} catch (Throwable) {
throw new RuntimeException('Der KI-Dienst unter '.$this->baseUrl().' ist nicht erreichbar.');
}
if (! $response->successful()) {
throw new RuntimeException($this->errorMessage($response));
}
$text = match ($this->provider()) {
'openai' => (string) $response->json('choices.0.message.content'),
'ollama' => (string) $response->json('message.content'),
default => collect((array) $response->json('content'))->where('type', 'text')->pluck('text')->implode("\n"),
};
// Manche Modelle „denken laut“ oder verpacken die Antwort in einen Code-Block
$text = preg_replace('#<think>.*?</think>#s', '', $text) ?? $text;
return trim(preg_replace('/^```(?:html)?\s*|\s*```$/', '', trim($text)) ?? '');
}
private function client(int $timeout): PendingRequest
{
// Keine Weiterleitungen – das Ziel ist fest eingetragen
return Http::timeout($timeout)->connectTimeout(10)->acceptJson()->withOptions(['allow_redirects' => false]);
}
private function key(): string
{
try {
return Crypt::decryptString((string) $this->settings->get('ai.api_key'));
} catch (Throwable) {
throw new RuntimeException('Der gespeicherte API-Schlüssel ist ungültig. Bitte neu eingeben.');
}
}
private function errorMessage(Response $response): string
{
$message = (string) ($response->json('error.message') ?? $response->json('error') ?? '');
return match ($response->status()) {
401, 403 => 'Der API-Schlüssel wurde abgelehnt.',
404 => 'Das Modell „'.$this->model().'“ ist nicht verfügbar'.($this->provider() === 'ollama' ? ' (auf dem Server mit „ollama pull '.$this->model().'“ laden).' : '.'),
429 => 'Der KI-Dienst ist gerade ausgelastet. Bitte gleich noch einmal versuchen.',
default => 'Der KI-Dienst hat nicht geantwortet'.($message !== '' ? ': '.mb_substr($message, 0, 200) : '.'),
};
}
}