69 lines
1.9 KiB
PHP
69 lines
1.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
final class AiConfigRepository
|
|
{
|
|
private string $path;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->path = storage_path('system/ai.json');
|
|
}
|
|
|
|
public function get(): array
|
|
{
|
|
$saved = decode_json_file($this->path, []);
|
|
$config = array_replace($this->defaults(), is_array($saved) ? $saved : []);
|
|
|
|
$config['model'] = trim((string) ($config['model'] ?? $this->defaults()['model']));
|
|
if ($config['model'] === '') {
|
|
$config['model'] = $this->defaults()['model'];
|
|
}
|
|
|
|
$config['timeout'] = max(5, min(120, (int) ($config['timeout'] ?? $this->defaults()['timeout'])));
|
|
|
|
return $config;
|
|
}
|
|
|
|
public function save(array $input): array
|
|
{
|
|
$config = [
|
|
'model' => trim((string) ($input['model'] ?? $this->defaults()['model'])),
|
|
'timeout' => max(5, min(120, (int) ($input['timeout'] ?? $this->defaults()['timeout']))),
|
|
];
|
|
|
|
if ($config['model'] === '') {
|
|
$config['model'] = $this->defaults()['model'];
|
|
}
|
|
|
|
$directory = dirname($this->path);
|
|
if (!is_dir($directory)) {
|
|
mkdir($directory, 0775, true);
|
|
}
|
|
|
|
$bytes = file_put_contents(
|
|
$this->path,
|
|
json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
|
|
LOCK_EX
|
|
);
|
|
|
|
if ($bytes === false) {
|
|
throw new RuntimeException('Die KI-Konfiguration konnte nicht gespeichert werden.');
|
|
}
|
|
|
|
return $config;
|
|
}
|
|
|
|
private function defaults(): array
|
|
{
|
|
$model = trim((string) ($_ENV['OPENAI_MODEL'] ?? getenv('OPENAI_MODEL') ?: 'gpt-4o-mini'));
|
|
$timeout = (int) ($_ENV['OPENAI_TIMEOUT'] ?? getenv('OPENAI_TIMEOUT') ?: 25);
|
|
|
|
return [
|
|
'model' => $model !== '' ? $model : 'gpt-4o-mini',
|
|
'timeout' => max(5, min(120, $timeout > 0 ? $timeout : 25)),
|
|
];
|
|
}
|
|
}
|