v0.11 U6: Bring your own key für die KI-Auswertung (Anthropic, OpenRouter)
Deploy FeWo mit PipelineManager / deploy (push) Successful in 5m11s

- Jeder Mandant verbindet unter „System › KI-Anbindung“ seinen eigenen
  Zugang: Anbieter (Anthropic oder OpenRouter), API-Schlüssel, Modell für
  die erste Auswertung und für die Prüfung – keine Modellkennung im Code,
  kein zentraler Betreiberschlüssel (FEWO_AI_API_KEY entfällt).
- Gespeichert im bestehenden TenantService (ai_guest_mail): Schlüssel
  verschlüsselt, nie wieder angezeigt, nie in Meldungen; Anbieter/Modelle
  in settings, Prüfergebnis in check_status/check_message/checked_at.
- Feste Endpunkte je Anbieter (AiProvider), nicht konfigurierbar.
  OpenRouter mit response_format json_schema (strict) und
  provider.require_parameters.
- „Verbindung prüfen“ testet beide Modelle. Ein abgelehnter Zugang
  (401/402/403) schaltet die Auswertung für den Mandanten ab, meldet es im
  Postfach der Verwaltung; Nachrichten bleiben zur Prüfung im Posteingang.
- Zweistufige Extraktion und ihre Sicherheitsregeln unverändert.
- Zielarchitektur §3.8, Umsetzungsplan U6, Bericht, Drehbuch, Status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-03 14:19:13 +01:00
1 parent 6f9aa46943
commit 6862dec201
20 files changed
+752 -95

No files matched your search

+17 -17
View File
@@ -2,21 +2,24 @@
namespace App\Actions;
use App\Communication\Extraction\AccessRejected;
use App\Communication\Extraction\AiAccess;
use App\Communication\Extraction\ExtractionFailed;
use App\Communication\Extraction\MessageExtractor;
use App\Communication\Extraction\RiskAssessment;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\FactSource;
use App\Enums\InboxMessageKind;
use App\Enums\TenantServiceKey;
use App\Filament\Pages\AiConnection;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\InboundMessage;
use App\Models\ServiceUsage;
use App\Models\TenantService;
use App\Process\CaseLog;
use App\Support\Inbox;
use App\Support\Settings;
use App\Tenancy\TenantFeatures;
/**
* The risk-based two-stage extraction of v0.11 (CH-14, E-035): the small model extracts facts with evidence and
@@ -40,8 +43,9 @@ public function handle(InboundMessage $message): string
return (string) $message->extraction_status;
}
$apiKey = $this->apiKey();
if (! app(TenantFeatures::class)->enabled(TenantServiceKey::AiGuestMail) || $apiKey === null) {
// Bring your own key: only the landlord's own, complete and not rejected access is used.
$access = AiAccess::for(Settings::tenant());
if ($access === null) {
$message->update(['extraction_status' => 'disabled']);
return 'disabled';
@@ -49,19 +53,26 @@ public function handle(InboundMessage $message): string
$record = ['prompt_version' => MessageExtractor::promptVersion()];
try {
$first = $this->extractor->extract($apiKey, $message, $booking);
$first = $this->extractor->extract($access, $message, $booking);
$this->meter();
$record['first'] = $first;
$data = $first['data'];
$checked = $this->risk->facts($booking, (string) $message->body, $data);
if ($this->risk->needsReview($booking, $checked, $data)) {
$review = $this->extractor->review($apiKey, $message, $booking, $data);
$review = $this->extractor->review($access, $message, $booking, $data);
$this->meter();
$record['review'] = $review;
$data = $review['data'];
$checked = $this->markDisagreements($this->risk->facts($booking, (string) $message->body, $data), $first['data']);
}
} catch (AccessRejected $exception) {
// The access is no longer valid: off for this landlord until he saves or checks it again (no retry loop).
AiAccess::markInvalid(Settings::tenant(), $exception->getMessage());
app(Inbox::class)->post(InboxMessageKind::AiAccessRejected, 'ai-access', 'KI-Anbindung abgelehnt', $exception->getMessage().' Die automatische Auswertung ist ausgeschaltet, bis Sie den Zugang unter System › KI-Anbindung prüfen. Nachrichten liegen im Posteingang.', actionUrl: AiConnection::getUrl());
$message->update(['extraction_status' => 'failed', 'extraction' => [...$record, 'error' => $exception->getMessage()]]);
return 'failed';
} catch (ExtractionFailed $exception) {
$message->update(['extraction_status' => 'failed', 'extraction' => [...$record, 'error' => $exception->getMessage()]]);
CaseLog::record($booking, 'mail_in', 'Automatische Auswertung nicht möglich – bitte die Nachricht selbst lesen', actor: CaseLog::SYSTEM);
@@ -168,17 +179,6 @@ private function finish(InboundMessage $message, array $automatic, array $propos
$task?->forceFill(['note' => '„'.mb_substr((string) $message->subject, 0, 120).'“ – '.(implode(', ', $parts) ?: 'keine Angaben erkannt').'. Im Posteingang ansehen.'])->save();
}
/**
* The landlord's own key of the service, otherwise the operator's key of the installation.
*/
private function apiKey(): ?string
{
$tenant = Settings::tenant();
$own = $tenant === null ? null : TenantService::query()->where('tenant_id', $tenant->id)->where('service', TenantServiceKey::AiGuestMail->value)->first()?->api_key;
return filled($own) ? (string) $own : (filled(config('fewo.ai.api_key')) ? (string) config('fewo.ai.api_key') : null);
}
private function meter(): void
{
if (($tenant = Settings::tenant()) !== null) {
@@ -0,0 +1,9 @@
<?php
namespace App\Communication\Extraction;
/**
* The provider rejected the landlord's access (invalid key, no credit, no permission). The message never contains the
* key.
*/
class AccessRejected extends ExtractionFailed {}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace App\Communication\Extraction;
use App\Enums\TenantServiceKey;
use App\Models\Tenant;
use App\Models\TenantService;
use App\Tenancy\TenantFeatures;
/**
* A landlord's own AI access (bring your own key): provider, key and the two models of the extraction. There is no
* central operator key and no built-in model – without a complete access, or after the provider rejected the key,
* the extraction is off and messages go to the landlord.
*/
final class AiAccess
{
public const OK = 'ok';
public const INVALID = 'invalid';
public function __construct(
public readonly AiProvider $provider,
#[\SensitiveParameter] public readonly string $key,
public readonly string $smallModel,
public readonly string $reviewModel,
) {}
/**
* The usable access of a landlord, or null (service off, incomplete, or rejected by the provider).
*/
public static function for(?Tenant $tenant): ?self
{
if ($tenant === null || ! app(TenantFeatures::class)->enabled(TenantServiceKey::AiGuestMail, $tenant)) {
return null;
}
$service = self::service($tenant);
if ($service === null || $service->check_status === self::INVALID) {
return null;
}
return self::fromService($service);
}
/**
* The access as configured, regardless of the last check (for the check itself).
*/
public static function fromService(TenantService $service): ?self
{
$settings = (array) $service->settings;
$provider = AiProvider::tryFrom((string) ($settings['provider'] ?? ''));
$small = trim((string) ($settings['small_model'] ?? ''));
$review = trim((string) ($settings['review_model'] ?? ''));
if ($provider === null || blank($service->api_key) || $small === '' || $review === '') {
return null;
}
return new self($provider, (string) $service->api_key, $small, $review);
}
public static function service(Tenant $tenant): ?TenantService
{
return TenantService::query()->where('tenant_id', $tenant->id)->where('service', TenantServiceKey::AiGuestMail->value)->first();
}
/**
* The provider rejected the key: the extraction stays off until the landlord saves or checks the access again.
*/
public static function markInvalid(Tenant $tenant, string $message): void
{
self::service($tenant)?->forceFill(['check_status' => self::INVALID, 'check_message' => mb_substr($message, 0, 500), 'checked_at' => now()])->save();
}
public function __debugInfo(): array
{
return ['provider' => $this->provider->value, 'key' => '***', 'smallModel' => $this->smallModel, 'reviewModel' => $this->reviewModel];
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Communication\Extraction;
use Filament\Support\Contracts\HasLabel;
/**
* The AI providers a landlord may connect (bring your own key, v0.11). Endpoints are fixed here – no configuration,
* form or environment value can point the extraction at another host.
*/
enum AiProvider: string implements HasLabel
{
case Anthropic = 'anthropic';
case OpenRouter = 'openrouter';
public function getLabel(): string
{
return match ($this) {
self::Anthropic => 'Anthropic (Claude API)',
self::OpenRouter => 'OpenRouter',
};
}
public function endpoint(): string
{
return match ($this) {
self::Anthropic => 'https://api.anthropic.com/v1/messages',
self::OpenRouter => 'https://openrouter.ai/api/v1/chat/completions',
};
}
/**
* Examples for the form – suggestions only, nothing is preset.
*/
public function modelExamples(): string
{
return match ($this) {
self::Anthropic => 'z. B. klein „claude-haiku-5-5“, groß „claude-opus-5-5“',
self::OpenRouter => 'z. B. klein „anthropic/claude-haiku-5-5“, groß „anthropic/claude-opus-5-5“ (Kennung wie bei OpenRouter angezeigt)',
};
}
}
+108 -31
View File
@@ -3,26 +3,70 @@
namespace App\Communication\Extraction;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* The model connection for the extraction (Claude Messages API over HTTP – no SDK dependency, as approved in the
* v0.11 plan). One call: system prompt, the message as user content, and a JSON schema the answer must follow
* (structured outputs, `output_config.format`). Provider, endpoint and models come from config('fewo.ai').
* The model connection of the extraction with the landlord's own access (bring your own key, v0.11): Anthropic's
* Messages API or OpenRouter's chat completions, both over HTTP to the provider's fixed endpoint (AiProvider), no SDK
* dependency. One call: system prompt, the message, and a JSON schema the answer must follow (structured outputs).
* The key travels only in the request header; it is never part of an exception, a log line or a stored result.
*/
class LlmClient
{
/** Server-side refusal fallback (opt-in default for Claude Opus 5.5). */
private const FALLBACK_BETA = 'server-side-fallback-2026-07-01';
/** Server-side refusal fallback on Anthropic (opt-in default for the Claude Opus family). */
private const ANTHROPIC_FALLBACK_BETA = 'server-side-fallback-2026-07-01';
/**
* @param array<string, mixed> $schema
* @return array{data: array<string, mixed>, model: string, usage: array<string, mixed>}
*
* @throws ExtractionFailed
* @throws AccessRejected when the provider rejects the access
* @throws ExtractionFailed for every other unusable outcome
*/
public function structured(string $apiKey, string $model, string $system, string $message, array $schema, string $effort = 'medium'): array
public function structured(AiAccess $access, string $model, string $system, string $message, array $schema, string $effort = 'medium'): array
{
[$headers, $body] = match ($access->provider) {
AiProvider::Anthropic => $this->anthropic($access, $model, $system, $message, $schema, $effort),
AiProvider::OpenRouter => $this->openRouter($access, $model, $system, $message, $schema),
};
try {
$response = Http::withHeaders($headers)
->timeout((int) config('fewo.ai.timeout', 40))
// Only passing problems are repeated; a rejected key or a bad request is not.
->retry(2, 2000, fn (Throwable $exception): bool => $exception instanceof ConnectionException || ($exception instanceof RequestException && in_array($exception->response->status(), [429, 500, 502, 503, 529], true)), throw: false)
->post($access->provider->endpoint(), $body);
} catch (ConnectionException) {
throw new ExtractionFailed('Keine Verbindung zu '.$access->provider->getLabel().'.');
}
if (in_array($response->status(), [401, 402, 403], true)) {
throw new AccessRejected($access->provider->getLabel().' lehnt den Zugang ab ('.$response->status().': '.$this->providerMessage($response, $access).').');
}
if (! $response->successful()) {
throw new ExtractionFailed($access->provider->getLabel().' antwortet mit '.$response->status().' ('.$this->providerMessage($response, $access).').');
}
$payload = (array) $response->json();
$text = $access->provider === AiProvider::Anthropic ? $this->anthropicText($payload) : $this->openRouterText($payload);
$data = json_decode($text, true);
if (! is_array($data)) {
throw new ExtractionFailed('Die Antwort ist kein gültiges JSON.');
}
return ['data' => $data, 'model' => (string) ($payload['model'] ?? $model), 'usage' => (array) ($payload['usage'] ?? [])];
}
/**
* @param array<string, mixed> $schema
* @return array{0: array<string, string>, 1: array<string, mixed>}
*/
private function anthropic(AiAccess $access, string $model, string $system, string $message, array $schema, string $effort): array
{
$headers = ['x-api-key' => $access->key, 'anthropic-version' => (string) config('fewo.ai.anthropic_version'), 'content-type' => 'application/json'];
$body = [
'model' => $model,
'max_tokens' => 4096,
@@ -30,37 +74,70 @@ public function structured(string $apiKey, string $model, string $system, string
'messages' => [['role' => 'user', 'content' => $message]],
'output_config' => ['effort' => $effort, 'format' => ['type' => 'json_schema', 'schema' => $schema]],
];
$headers = ['x-api-key' => $apiKey, 'anthropic-version' => (string) config('fewo.ai.api_version'), 'content-type' => 'application/json'];
if (str_starts_with($model, 'claude-opus-')) {
$body['fallbacks'] = 'default';
$headers['anthropic-beta'] = self::FALLBACK_BETA;
$headers['anthropic-beta'] = self::ANTHROPIC_FALLBACK_BETA;
}
try {
$response = Http::withHeaders($headers)->timeout((int) config('fewo.ai.timeout', 40))->retry(2, 2000, throw: false)->post((string) config('fewo.ai.endpoint'), $body);
} catch (ConnectionException $exception) {
throw new ExtractionFailed('Keine Verbindung zum KI-Dienst: '.$exception->getMessage(), previous: $exception);
}
return [$headers, $body];
}
if (! $response->successful()) {
throw new ExtractionFailed('KI-Dienst antwortet mit '.$response->status().'.');
}
/**
* @param array<string, mixed> $schema
* @return array{0: array<string, string>, 1: array<string, mixed>}
*/
private function openRouter(AiAccess $access, string $model, string $system, string $message, array $schema): array
{
return [
['Authorization' => 'Bearer '.$access->key, 'content-type' => 'application/json', 'HTTP-Referer' => (string) config('app.url'), 'X-OpenRouter-Title' => 'FewoPortal'],
[
'model' => $model,
'max_tokens' => 4096,
'messages' => [['role' => 'system', 'content' => $system], ['role' => 'user', 'content' => $message]],
'response_format' => ['type' => 'json_schema', 'json_schema' => ['name' => 'extraction', 'strict' => true, 'schema' => $schema]],
// Only providers that honour the schema; otherwise it would merely be a hint.
'provider' => ['require_parameters' => true],
],
];
}
$payload = (array) $response->json();
$stop = $payload['stop_reason'] ?? null;
if ($stop === 'refusal') {
throw new ExtractionFailed('Der KI-Dienst hat die Auswertung abgelehnt.');
}
if ($stop === 'max_tokens') {
throw new ExtractionFailed('Die Antwort des KI-Dienstes ist unvollständig.');
}
/**
* @param array<string, mixed> $payload
*/
private function anthropicText(array $payload): string
{
match ($payload['stop_reason'] ?? null) {
'refusal' => throw new ExtractionFailed('Der Anbieter hat die Auswertung abgelehnt.'),
'max_tokens' => throw new ExtractionFailed('Die Antwort ist unvollständig.'),
default => null,
};
$text = collect((array) ($payload['content'] ?? []))->where('type', 'text')->pluck('text')->implode('');
$data = json_decode($text, true);
if (! is_array($data)) {
throw new ExtractionFailed('Die Antwort des KI-Dienstes ist kein gültiges JSON.');
}
return collect((array) ($payload['content'] ?? []))->where('type', 'text')->pluck('text')->implode('');
}
return ['data' => $data, 'model' => (string) ($payload['model'] ?? $model), 'usage' => (array) ($payload['usage'] ?? [])];
/**
* @param array<string, mixed> $payload
*/
private function openRouterText(array $payload): string
{
$choice = (array) ($payload['choices'][0] ?? []);
match ($choice['finish_reason'] ?? null) {
'content_filter' => throw new ExtractionFailed('Der Anbieter hat die Auswertung abgelehnt.'),
'length' => throw new ExtractionFailed('Die Antwort ist unvollständig.'),
'error' => throw new ExtractionFailed('Der Anbieter meldet einen Fehler.'),
default => null,
};
return (string) ($choice['message']['content'] ?? '');
}
/**
* The provider's own short message, cut and without anything that looks like a key.
*/
private function providerMessage(Response $response, AiAccess $access): string
{
$message = str_replace($access->key, '***', (string) ($response->json('error.message') ?? $response->json('error.type') ?? ''));
return mb_substr((string) preg_replace('/(sk-[A-Za-z0-9_\-]{6})[A-Za-z0-9_\-]+/', '$1…', $message), 0, 200) ?: 'ohne Angabe';
}
}
@@ -9,7 +9,8 @@
/**
* The model side of the extraction (v0.11, CH-14): versioned prompts with defined placeholders, a JSON schema for the
* answer and its validation here (the answer is checked, not trusted). The small model extracts; the review model
* sees the original and the first extraction. Both only return candidates – nothing is stored or changed here.
* sees the original and the first extraction – both as configured in the landlord's own access. Both only return
* candidates – nothing is stored or changed here.
*/
class MessageExtractor
{
@@ -20,9 +21,9 @@ public function __construct(private LlmClient $client) {}
*
* @throws ExtractionFailed
*/
public function extract(string $apiKey, InboundMessage $message, Booking $booking): array
public function extract(AiAccess $access, InboundMessage $message, Booking $booking): array
{
return $this->call($apiKey, (string) config('fewo.ai.small_model'), $this->prompt('', $booking), $this->messageText($message), 'medium');
return $this->call($access, $access->smallModel, $this->prompt('', $booking), $this->messageText($message), 'medium');
}
/**
@@ -31,9 +32,9 @@ public function extract(string $apiKey, InboundMessage $message, Booking $bookin
*
* @throws ExtractionFailed
*/
public function review(string $apiKey, InboundMessage $message, Booking $booking, array $first): array
public function review(AiAccess $access, InboundMessage $message, Booking $booking, array $first): array
{
return $this->call($apiKey, (string) config('fewo.ai.review_model'), $this->prompt('-review', $booking, ['first_extraction' => json_encode($first, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)]), $this->messageText($message), 'high');
return $this->call($access, $access->reviewModel, $this->prompt('-review', $booking, ['first_extraction' => json_encode($first, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)]), $this->messageText($message), 'high');
}
public static function promptVersion(): string
@@ -87,13 +88,13 @@ public static function schema(): array
/**
* @return array{data: array{facts: list<array{field: string, value: string, evidence: string, confidence: float|int}>, change_requests: list<array{field: string, value: string, evidence: string}>, intent: string, uncertainties: list<string>}, model: string}
*/
private function call(string $apiKey, string $model, string $system, string $text, string $effort): array
private function call(AiAccess $access, string $model, string $system, string $text, string $effort): array
{
$schema = self::schema();
$lastError = null;
// One repetition when the answer does not fit the schema, then the message goes to the landlord.
for ($attempt = 1; $attempt <= 2; $attempt++) {
$result = $this->client->structured($apiKey, $model, $system, $text, $schema, $effort);
$result = $this->client->structured($access, $model, $system, $text, $schema, $effort);
$lastError = $this->violation($result['data'], $schema);
if ($lastError === null) {
return ['data' => $result['data'], 'model' => $result['model']];
+10 -5
View File
@@ -2,11 +2,13 @@
namespace App\Console\Commands;
use App\Communication\Extraction\AiAccess;
use App\Communication\Extraction\ExtractionFailed;
use App\Communication\Extraction\MessageExtractor;
use App\Models\Booking;
use App\Models\InboundMessage;
use App\Models\Property;
use App\Models\Tenant;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
@@ -16,16 +18,19 @@
* counted separately – no system guarantees that it finds every detail, so the rate of missed ones is reported, not
* hidden. Calls the configured models (costs money); meant for calibrating prompts and thresholds before go-live.
*/
#[Signature('ai:evaluate {--path= : JSON file with samples} {--key= : API key (default: FEWO_AI_API_KEY)}')]
#[Signature('ai:evaluate {tenant : ID of the landlord whose own AI access is used} {--path= : JSON file with samples}')]
#[Description('Evaluate the guest message extraction against sample messages (wrong values and missed details)')]
class EvaluateExtraction extends Command
{
public function handle(MessageExtractor $extractor): int
{
$path = (string) ($this->option('path') ?: resource_path('prompts/extraction/evaluation/samples.json'));
$key = (string) ($this->option('key') ?: config('fewo.ai.api_key'));
if ($key === '') {
$this->error('Kein API-Schlüssel (FEWO_AI_API_KEY oder --key).');
// Bring your own key: the landlord's own access, as configured (System › KI-Anbindung).
$tenant = Tenant::query()->find((int) $this->argument('tenant'));
$service = $tenant === null ? null : AiAccess::service($tenant);
$access = $service === null ? null : AiAccess::fromService($service);
if ($access === null) {
$this->error('Für diesen Mandanten ist keine vollständige KI-Anbindung gespeichert.');
return self::FAILURE;
}
@@ -41,7 +46,7 @@ public function handle(MessageExtractor $extractor): int
$message = new InboundMessage(['subject' => $sample['subject'], 'body' => $sample['body']]);
try {
$result = $extractor->extract($key, $message, $booking)['data'];
$result = $extractor->extract($access, $message, $booking)['data'];
} catch (ExtractionFailed $exception) {
$totals['failed']++;
$this->warn("{$sample['id']}: {$exception->getMessage()}");
+3 -1
View File
@@ -15,6 +15,7 @@ enum InboxMessageKind: string implements HasColor, HasLabel
case OfferMailFailed = 'offer_mail_failed';
case OfferRejected = 'offer_rejected';
case SyncFailed = 'sync_failed';
case AiAccessRejected = 'ai_access_rejected';
public function getLabel(): string
{
@@ -24,6 +25,7 @@ public function getLabel(): string
self::OfferMailFailed => 'Angebot nicht zugestellt',
self::OfferRejected => 'Annahme abgewiesen',
self::SyncFailed => 'Kalenderabgleich gestört',
self::AiAccessRejected => 'KI-Anbindung abgelehnt',
};
}
@@ -31,7 +33,7 @@ public function getColor(): string
{
return match ($this) {
self::ChannelConflict, self::SyncFailed => 'danger',
self::ConfirmationFailed, self::OfferMailFailed, self::OfferRejected => 'warning',
self::ConfirmationFailed, self::OfferMailFailed, self::OfferRejected, self::AiAccessRejected => 'warning',
};
}
}
+196
View File
@@ -0,0 +1,196 @@
<?php
namespace App\Filament\Pages;
use App\Communication\Extraction\AiAccess;
use App\Communication\Extraction\AiProvider;
use App\Communication\Extraction\ExtractionFailed;
use App\Communication\Extraction\LlmClient;
use App\Enums\TenantServiceKey;
use App\Enums\UserRole;
use App\Filament\Concerns\FollowsAdminMode;
use App\Models\Tenant;
use App\Models\TenantService;
use App\Support\Settings;
use App\Tenancy\TenantFeatures;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\EmbeddedSchema;
use Filament\Schemas\Components\Form;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use UnitEnum;
/**
* "KI-Anbindung" (v0.11, bring your own key): the landlord connects his own AI access for the evaluation of guest
* messages – provider (Anthropic or OpenRouter), key and the two models. The key is stored encrypted and never shown
* again; an empty field keeps it. A check sends a tiny test request to both models. The page only exists when the
* operator switched the service on for this landlord.
*/
class AiConnection extends Page
{
use FollowsAdminMode;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedSparkles;
protected static string|UnitEnum|null $navigationGroup = 'System';
protected static ?string $navigationLabel = 'KI-Anbindung';
protected static ?string $title = 'KI-Anbindung';
protected static ?string $slug = 'ki-anbindung';
protected static ?int $navigationSort = 3;
/** @var array<string, mixed> */
public array $data = [];
public static function canAccess(): bool
{
return (bool) auth()->user()?->hasRole(UserRole::Admin) && app(TenantFeatures::class)->enabled(TenantServiceKey::AiGuestMail);
}
public function mount(): void
{
$settings = (array) $this->service()?->settings;
// The key is never put into the form.
$this->form->fill([
'provider' => $settings['provider'] ?? null,
'small_model' => $settings['small_model'] ?? null,
'review_model' => $settings['review_model'] ?? null,
'api_key' => null,
]);
}
public function form(Schema $schema): Schema
{
return $schema
->statePath('data')
->components([
Section::make('Ihr Zugang')
->description('Die Auswertung von Gast-Nachrichten nutzt Ihren eigenen Zugang bei einem KI-Anbieter; die Kosten rechnet der Anbieter mit Ihnen ab. Nachrichten werden dafür an den Anbieter übermittelt – bitte Auftragsverarbeitung und Datenschutzhinweise beachten. Ohne gültigen Zugang bleibt jede Nachricht zur Prüfung im Posteingang.')
->columns(2)
->schema([
Select::make('provider')->label('Anbieter')->options(AiProvider::class)->required()->live(),
TextInput::make('api_key')->label('API-Schlüssel')->password()->autocomplete('new-password')->maxLength(500)
->placeholder(fn (): string => filled($this->service()?->api_key) ? 'gespeichert – leer lassen, um ihn zu behalten' : 'noch keiner gespeichert')
->helperText('Wird verschlüsselt gespeichert und nie wieder angezeigt.'),
TextInput::make('small_model')->label('Modell für die erste Auswertung (klein, günstig)')->required()->maxLength(150)
->helperText(fn (Get $get): string => self::provider($get('provider'))?->modelExamples() ?? 'Kennung des Modells beim Anbieter'),
TextInput::make('review_model')->label('Modell für die Prüfung unsicherer Fälle (groß)')->required()->maxLength(150)
->helperText('Wird nur gefragt, wenn eine Angabe widersprüchlich, unplausibel oder unsicher ist.'),
]),
Section::make('Stand')
->schema([Text::make(fn (): string => $this->checkSummary())]),
]);
}
public function content(Schema $schema): Schema
{
return $schema->components([
Form::make([EmbeddedSchema::make('form')])
->id('form')
->livewireSubmitHandler('save')
->footer([Actions::make([
Action::make('save')->label('Speichern')->submit('save'),
Action::make('check')->label('Verbindung prüfen')->color('gray')->icon(Heroicon::OutlinedSignal)->action(fn () => $this->check()),
Action::make('removeKey')->label('Schlüssel entfernen')->color('danger')->requiresConfirmation()
->modalDescription('Danach ist die automatische Auswertung aus, bis ein neuer Schlüssel gespeichert ist.')
->visible(fn (): bool => filled($this->service()?->api_key))
->action(fn () => $this->removeKey()),
])]),
]);
}
public function save(): void
{
$state = $this->form->getState();
$service = $this->service() ?? new TenantService(['tenant_id' => $this->tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true]);
$service->settings = ['provider' => self::provider($state['provider'])?->value, 'small_model' => trim((string) $state['small_model']), 'review_model' => trim((string) $state['review_model'])];
if (filled($state['api_key'] ?? null)) {
$service->api_key = trim((string) $state['api_key']);
}
// A changed access is checked again before it counts as rejected.
$service->forceFill(['check_status' => null, 'check_message' => null])->save();
$this->data['api_key'] = null;
Notification::make()->title('Gespeichert')->body(filled($service->api_key) ? 'Bitte „Verbindung prüfen“ ausführen.' : 'Ohne Schlüssel bleibt die Auswertung aus.')->success()->send();
}
/**
* Sends a minimal structured request to both models; the result is stored, the key never shown.
*/
public function check(): void
{
$service = $this->service();
$access = $service === null ? null : AiAccess::fromService($service);
if ($access === null) {
Notification::make()->title('Unvollständig')->body('Bitte Anbieter, Schlüssel und beide Modelle speichern.')->warning()->send();
return;
}
$schema = ['type' => 'object', 'additionalProperties' => false, 'required' => ['ok'], 'properties' => ['ok' => ['type' => 'boolean']]];
try {
foreach ([$access->smallModel, $access->reviewModel] as $model) {
app(LlmClient::class)->structured($access, $model, 'Answer with {"ok": true}.', 'Test', $schema, 'low');
}
} catch (ExtractionFailed $exception) {
$service->forceFill(['check_status' => AiAccess::INVALID, 'check_message' => mb_substr($exception->getMessage(), 0, 500), 'checked_at' => now()])->save();
Notification::make()->title('Prüfung fehlgeschlagen')->body($exception->getMessage())->danger()->send();
return;
}
$service->forceFill(['check_status' => AiAccess::OK, 'check_message' => null, 'checked_at' => now()])->save();
Notification::make()->title('Verbindung in Ordnung')->body('Beide Modelle antworten im erwarteten Format.')->success()->send();
}
public function removeKey(): void
{
$this->service()?->forceFill(['api_key' => null, 'check_status' => null, 'check_message' => null, 'checked_at' => null])->save();
Notification::make()->title('Schlüssel entfernt')->success()->send();
}
private static function provider(mixed $value): ?AiProvider
{
return $value instanceof AiProvider ? $value : AiProvider::tryFrom((string) $value);
}
private function checkSummary(): string
{
$service = $this->service();
if ($service === null || blank($service->api_key)) {
return 'Kein Zugang gespeichert – Nachrichten werden nicht automatisch ausgewertet.';
}
return match ($service->check_status) {
AiAccess::OK => 'Zuletzt erfolgreich geprüft am '.$service->checked_at?->format('d.m.Y, H:i').' Uhr.',
AiAccess::INVALID => 'Abgelehnt am '.$service->checked_at?->format('d.m.Y, H:i').' Uhr: '.$service->check_message.' Die automatische Auswertung ist aus.',
default => 'Gespeichert, noch nicht geprüft.',
};
}
private function service(): ?TenantService
{
return AiAccess::service($this->tenant());
}
private function tenant(): Tenant
{
$tenant = Settings::tenant();
abort_if($tenant === null, 404);
return $tenant;
}
}
+6 -3
View File
@@ -7,10 +7,11 @@
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A service the operator switched on for a landlord. The own API key is optional and stored encrypted;
* an empty key means that the operator's key applies (no service calls it yet).
* A service the operator switched on for a landlord. A service that calls an external provider uses the landlord's
* own access (bring your own key, v0.11): the key is stored encrypted and never shown again; provider and models are
* in settings, the result of the last check beside them.
*/
#[Fillable(['tenant_id', 'service', 'is_enabled', 'api_key'])]
#[Fillable(['tenant_id', 'service', 'is_enabled', 'api_key', 'settings', 'check_status', 'check_message', 'checked_at'])]
class TenantService extends Model
{
/** @var list<string> */
@@ -24,6 +25,8 @@ protected function casts(): array
return [
'is_enabled' => 'boolean',
'api_key' => 'encrypted',
'settings' => 'array',
'checked_at' => 'immutable_datetime',
];
}