Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 9m24s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 9m15s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 9m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 9m21s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 10m33s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 10m5s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 8m10s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 8m8s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 48s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m23s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
135 lines
4.9 KiB
PHP
135 lines
4.9 KiB
PHP
<?php
|
||
|
||
namespace App\Ai;
|
||
|
||
use App\Support\Settings;
|
||
use Illuminate\Support\Facades\Crypt;
|
||
use Illuminate\Support\Facades\Http;
|
||
use RuntimeException;
|
||
use Throwable;
|
||
|
||
/**
|
||
* KI-Assistent (derzeit Anthropic Claude) – z. B. für Vorschläge in Leichter Sprache.
|
||
* Nur aktiv, wenn die Administration ihn eingerichtet hat. Die Texte werden dazu an
|
||
* den Anbieter übertragen; darauf weist die Oberfläche hin.
|
||
*/
|
||
class AiAssistant
|
||
{
|
||
public const ENDPOINT = 'https://api.anthropic.com/v1/messages';
|
||
|
||
public const DEFAULT_MODEL = 'claude-sonnet-5';
|
||
|
||
public const MAX_INPUT = 20000;
|
||
|
||
public function __construct(private readonly Settings $settings) {}
|
||
|
||
public function available(): bool
|
||
{
|
||
return (bool) $this->settings->get('ai.enabled') && filled($this->settings->get('ai.api_key'));
|
||
}
|
||
|
||
public function model(): string
|
||
{
|
||
return (string) ($this->settings->get('ai.model') ?: self::DEFAULT_MODEL);
|
||
}
|
||
|
||
/**
|
||
* @param array{enabled: bool, model: ?string, api_key: ?string} $values
|
||
*/
|
||
public function save(array $values): void
|
||
{
|
||
$data = [
|
||
'ai.enabled' => (bool) $values['enabled'],
|
||
'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']));
|
||
}
|
||
|
||
$this->settings->setMany($data);
|
||
}
|
||
|
||
public function forgetKey(): void
|
||
{
|
||
$this->settings->setMany(['ai.api_key' => null, 'ai.enabled' => false]);
|
||
}
|
||
|
||
/**
|
||
* 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.
|
||
PROMPT,
|
||
"Titel: {$title}\n\nText:\n{$text}",
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 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.');
|
||
}
|
||
|
||
try {
|
||
$key = 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.');
|
||
}
|
||
|
||
$response = Http::timeout(120)->acceptJson()
|
||
->withHeaders(['x-api-key' => $key, 'anthropic-version' => '2023-06-01'])
|
||
->post(self::ENDPOINT, [
|
||
'model' => $this->model(),
|
||
'max_tokens' => 4096,
|
||
'system' => $system,
|
||
'messages' => [['role' => 'user', 'content' => $user]],
|
||
]);
|
||
|
||
if (! $response->successful()) {
|
||
$message = (string) ($response->json('error.message') ?? '');
|
||
|
||
throw new RuntimeException(match ($response->status()) {
|
||
401, 403 => 'Der API-Schlüssel wurde abgelehnt.',
|
||
404 => 'Das Modell „'.$this->model().'“ ist nicht verfügbar.',
|
||
429 => 'Der KI-Dienst ist gerade ausgelastet. Bitte gleich noch einmal versuchen.',
|
||
default => 'Der KI-Dienst hat nicht geantwortet'.($message !== '' ? ': '.$message : '.'),
|
||
});
|
||
}
|
||
|
||
$text = collect((array) $response->json('content'))->where('type', 'text')->pluck('text')->implode("\n");
|
||
|
||
// Falls doch in Code-Block verpackt
|
||
return trim(preg_replace('/^```(?:html)?\s*|\s*```$/', '', trim($text)) ?? '');
|
||
}
|
||
}
|