KI-Assistent: OpenAI und Ollama als Anbieter (0.35.0)
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
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
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
b3d6140f2e
commit
268742983a
133 changed files with 651 additions and 390 deletions
|
|
@ -2,49 +2,109 @@
|
|||
|
||||
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 (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.
|
||||
* 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
|
||||
{
|
||||
return (bool) $this->settings->get('ai.enabled') && filled($this->settings->get('ai.api_key'));
|
||||
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') ?: self::DEFAULT_MODEL);
|
||||
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, model: ?string, api_key: ?string} $values
|
||||
* @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);
|
||||
|
|
@ -52,7 +112,35 @@ class AiAssistant
|
|||
|
||||
public function forgetKey(): void
|
||||
{
|
||||
$this->settings->setMany(['ai.api_key' => null, 'ai.enabled' => false]);
|
||||
$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.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -81,7 +169,7 @@ class AiAssistant
|
|||
- 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.
|
||||
Kein Markdown, keine Einleitung, keine Erklärung. Antworte auf Deutsch.
|
||||
PROMPT,
|
||||
"Titel: {$title}\n\nText:\n{$text}",
|
||||
);
|
||||
|
|
@ -101,35 +189,76 @@ class AiAssistant
|
|||
throw new RuntimeException('Der KI-Assistent ist nicht eingerichtet.');
|
||||
}
|
||||
|
||||
// Lokale Modelle brauchen mitunter länger
|
||||
@set_time_limit(360);
|
||||
|
||||
try {
|
||||
$key = Crypt::decryptString((string) $this->settings->get('ai.api_key'));
|
||||
$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.');
|
||||
}
|
||||
}
|
||||
|
||||
$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]],
|
||||
]);
|
||||
private function errorMessage(Response $response): string
|
||||
{
|
||||
$message = (string) ($response->json('error.message') ?? $response->json('error') ?? '');
|
||||
|
||||
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)) ?? '');
|
||||
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) : '.'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue