Leichte Sprache automatisch für Leser, mehrere KI-Anbieter

Statt eines KI-Knopfs in der Redaktion entsteht die Leichte Sprache jetzt
automatisch für Leser:
- Ist „Leichte Sprache“ eingeschaltet und gibt es keine eigene Fassung,
  wird der Text beim ersten Aufruf live übertragen, gespeichert und allen
  weiteren Lesern sofort gezeigt; nach Textänderungen neu (Prüfsumme)
- Beim Speichern einer Seite/Meldung wird im Hintergrund vorab übertragen
  (Warteschlange, eine Übertragung gleichzeitig)
- Gekennzeichnet als „automatisch übertragen“ mit „Fehler melden“;
  eigene Fassungen der Redaktion haben immer Vorrang
- Modell-Ausgabe wird nur bereinigt als HTML angezeigt (Live-Text nur als
  reiner Text) – getestet mit Schadcode aus dem Modell

Anbieter (Einstellungen): Anthropic (Claude, Anthropic-SDK), OpenAI,
DeepSeek, Ollama (OpenAI-kompatibel über das OpenAI-SDK); Modelle laden,
Verbindung testen, API-Schlüssel AES-256-GCM-verschlüsselt und nie wieder
angezeigt, Tageslimit, Sperre pro Gerät, Anrede du/Sie.
Datenschutz-Vorlage um den Abschnitt „Automatische Leichte Sprache“ ergänzt.

Seed: „heute“ liegt nicht mehr in der Zukunft (Meldung sonst unsichtbar).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-10-03 05:49:18 +00:00
parent 8862a095c0
commit c20f3a73d0
34 changed files with 2527 additions and 329 deletions

View file

@ -39,7 +39,7 @@
{/if}
<div class="space-y-8">
<RichContent content={post.content} contentEasy={post.contentEasy} />
<RichContent content={post.content} contentEasy={post.contentEasy} contentEasyAuto={post.contentEasyAuto} easyAutoPending={post.easyAutoPending} kind="post" slug={post.slug} />
{#if post.videoUrl}<VideoEmbed url={post.videoUrl} />{/if}
<Gallery images={post.gallery} />
<Attachments items={post.attachments} />

View file

@ -40,7 +40,7 @@
{/if}
<div class="space-y-8">
<RichContent content={p.content} contentEasy={p.contentEasy} />
<RichContent content={p.content} contentEasy={p.contentEasy} contentEasyAuto={p.contentEasyAuto} easyAutoPending={p.easyAutoPending} kind="page" slug={p.slug} />
{#if p.children.length}
<section class="space-y-3">

View file

@ -1,10 +1,8 @@
import { eq, sql } from 'drizzle-orm';
import { db } from '$lib/server/db';
import { messages } from '$lib/server/db/schema';
import { easyLanguageAvailable } from '$lib/server/easy-language';
export const load = ({ locals }) => ({
user: locals.user!,
aiEasy: easyLanguageAvailable(),
unread: db.select({ n: sql<number>`count(*)` }).from(messages).where(eq(messages.read, false)).get()?.n ?? 0
});

View file

@ -5,12 +5,14 @@ import { fields, requireAdmin } from '$lib/server/forms';
import { cleanHtml } from '$lib/server/sanitize';
import { imprintTemplate, privacyTemplate } from '$lib/server/legal';
import type { AppSettings } from '$lib/settings';
import { easyLanguageAvailable } from '$lib/server/easy-language';
import { aiReady, keyHint, saveKey } from '$lib/server/ai';
import { dailyUsage } from '$lib/server/easy-auto';
import { AI_PROVIDERS, type AiProvider } from '$lib/settings';
export const load = ({ locals }) => {
requireAdmin(locals.user);
const s = getSettings();
return { settings: s, logo: getMedia(s.logoId), hero: getMedia(s.heroImageId), ai: easyLanguageAvailable() };
return { settings: s, logo: getMedia(s.logoId), hero: getMedia(s.heroImageId), ai: { ready: aiReady(), keyHint: keyHint(), usedToday: dailyUsage() } };
};
/** Liest alle Felder des Formulars – oder gibt eine Fehlermeldung zurück */
@ -44,6 +46,11 @@ function read(form: FormData): Partial<AppSettings> | string {
privacy: cleanHtml(f.html('privacy')),
require2faAdmins: f.bool('require2faAdmins'),
easyAddress: f.str('easyAddress') === 'Sie' ? 'Sie' : 'du',
aiEnabled: f.bool('aiEnabled'),
aiProvider: (f.str('aiProvider') in AI_PROVIDERS ? f.str('aiProvider') : 'anthropic') as AiProvider,
aiModel: f.str('aiModel', 120),
aiBaseUrl: f.str('aiBaseUrl', 300),
aiDailyLimit: Math.min(5000, Math.max(0, f.int('aiDailyLimit') ?? 100)),
homeNewsCount: Math.min(12, Math.max(0, f.int('homeNewsCount') ?? 4)),
homeEventsCount: Math.min(12, Math.max(0, f.int('homeEventsCount') ?? 4)),
legal: {
@ -73,8 +80,14 @@ function read(form: FormData): Partial<AppSettings> | string {
export const actions = {
save: async ({ request, locals }) => {
requireAdmin(locals.user);
const patch = read(await request.formData());
const form = await request.formData();
const patch = read(form);
if (typeof patch === 'string') return fail(400, { error: patch });
if (patch.aiBaseUrl && !/^https?:\/\//.test(patch.aiBaseUrl)) return fail(400, { error: 'Die KI-Adresse muss mit http:// oder https:// beginnen.' });
const f = fields(form);
// Schlüssel nur ändern, wenn ein neuer eingegeben oder Löschen gewählt wurde
if (f.bool('aiKeyDelete')) saveKey(null);
else if (f.str('aiKey', 500)) saveKey(f.str('aiKey', 500));
saveSettings(patch);
return { saved: true };
},

View file

@ -5,6 +5,7 @@
import ImageField from '$lib/admin/ImageField.svelte';
import RichEditor from '$lib/admin/RichEditor.svelte';
import Switch from '$lib/admin/Switch.svelte';
import AiSettings from '$lib/admin/AiSettings.svelte';
let { data } = $props();
const s = $derived(data.settings);
@ -93,20 +94,8 @@
</div>
</Panel>
<Panel title="Leichte Sprache mit KI" description="Erstellt per Knopfdruck einen Entwurf in Leichter Sprache aus dem normalen Text (Claude von Anthropic).">
{#if data.ai}
<p class="text-sm rounded-xl bg-surface-2 px-4 py-3">Eingerichtet. In Seiten und Meldungen gibt es bei „Leichte Sprache“ den Knopf <strong>„Mit KI erstellen“</strong>.</p>
{:else}
<p class="text-sm rounded-xl bg-accent-soft text-accent-ink px-4 py-3">Noch nicht eingerichtet: Auf dem Server fehlt <code>ANTHROPIC_API_KEY</code> in der <code>.env</code>.</p>
{/if}
<fieldset>
<legend class="label">Anrede in den Entwürfen</legend>
<div class="flex gap-4">
{#each ['du', 'Sie'] as a (a)}
<label class="inline-flex items-center gap-2 cursor-pointer"><input type="radio" name="easyAddress" value={a} checked={s.easyAddress === a} class="accent-[var(--brand)]" />„{a}“</label>
{/each}
</div>
</fieldset>
<Panel title="Leichte Sprache mit KI" description="Überträgt Texte ohne eigene Fassung automatisch für Leser in Leichte Sprache. Eigene Fassungen aus der Redaktion haben immer Vorrang.">
<AiSettings {s} ai={data.ai} />
</Panel>
<Panel title="Sicherheit">

View file

@ -5,6 +5,8 @@ import { posts } from '$lib/server/db/schema';
import { attachmentsOf, contactOptions as listContactOptions, getMedia, mediaByIds } from '$lib/server/content';
import { fields, parseId, uniqueSlug } from '$lib/server/forms';
import { cleanHtml } from '$lib/server/sanitize';
import { autoStatus, queueAuto } from '$lib/server/easy-auto';
import { getSettings } from '$lib/server/settings';
import { fromLocalInput, toLocalInput } from '$lib/dates';
import { sendDuePosts, subscriberCounts } from '$lib/server/push';
import type { MediaItem } from '$lib/types';
@ -16,6 +18,7 @@ export const load = ({ params }) => {
if (id === 'new') {
return {
isNew: true,
easyAuto: { enabled: getSettings().aiEnabled, html: '', fresh: false, at: null, model: '' } as ReturnType<typeof autoStatus>,
subscribers: subscriberCounts().byTopic.news,
contactOptions,
post: {
@ -31,6 +34,7 @@ export const load = ({ params }) => {
const gallery = mediaByIds(p.gallery);
return {
isNew: false,
easyAuto: autoStatus(p),
subscribers: subscriberCounts().byTopic.news,
contactOptions,
post: {
@ -72,11 +76,13 @@ export const actions = {
if (id === 'new') {
const created = db.insert(posts).values(values).returning({ id: posts.id }).get();
await sendDuePosts();
queueAuto('post', created.id);
redirect(303, `/admin/meldungen/${created.id}`);
}
db.update(posts).set(values).where(eq(posts.id, id)).run();
// Ist die Meldung jetzt erschienen und soll benachrichtigen? Dann sofort senden.
await sendDuePosts();
queueAuto('post', id);
return { saved: true };
},
delete: ({ params }) => {

View file

@ -37,7 +37,7 @@
<RichEditor name="content" value={p.content} label="Text" />
</Panel>
<EasyLanguageField value={p.contentEasy} />
<EasyLanguageField value={p.contentEasy} auto={data.easyAuto} />
<Panel title="Medien & Anhänge">
<GalleryField name="gallery" value={p.gallery} />

View file

@ -5,6 +5,8 @@ import { pages } from '$lib/server/db/schema';
import { attachmentsOf, contactOptions as listContactOptions, getMedia } from '$lib/server/content';
import { fields, parseId, uniqueSlug } from '$lib/server/forms';
import { cleanHtml } from '$lib/server/sanitize';
import { autoStatus, queueAuto } from '$lib/server/easy-auto';
import { getSettings } from '$lib/server/settings';
import { descendantsOf, pageTree } from '$lib/server/pageTree';
import { nextSortOrder } from '$lib/server/sorting';
import { isTone } from '$lib/palette';
@ -23,6 +25,7 @@ export const load = ({ params, url }) => {
const parent = Number(url.searchParams.get('parent')) || null;
return {
isNew: true, contactOptions, parentOptions,
easyAuto: { enabled: getSettings().aiEnabled, html: '', fresh: false, at: null, model: '' } as ReturnType<typeof autoStatus>,
page: {
id: 0, parentId: parent, title: '', slug: '', teaser: '', icon: 'file-text', color: 'sky', content: '', contentEasy: '',
published: true, cover: null as MediaItem | null, attachments: [] as ReturnType<typeof attachmentsOf>, contactIds: [] as number[]
@ -34,6 +37,7 @@ export const load = ({ params, url }) => {
if (!p) error(404, 'Seite nicht gefunden');
return {
isNew: false, contactOptions, parentOptions,
easyAuto: autoStatus(p),
page: {
id: p.id, parentId: p.parentId, title: p.title, slug: p.slug, teaser: p.teaser, icon: p.icon, color: p.color,
content: p.content, contentEasy: p.contentEasy, published: p.published,
@ -72,6 +76,7 @@ export const actions = {
if (id === 'new') {
const scope = parentId ? eq(pages.parentId, parentId) : isNull(pages.parentId);
const created = db.insert(pages).values({ ...values, sortOrder: nextSortOrder(pages, scope) }).returning({ id: pages.id }).get();
queueAuto('page', created.id);
redirect(303, `/admin/seiten/${created.id}`);
}
const before = db.select({ parentId: pages.parentId }).from(pages).where(eq(pages.id, id)).get();
@ -81,6 +86,7 @@ export const actions = {
.set(moved ? { ...values, sortOrder: nextSortOrder(pages, scope) } : values)
.where(eq(pages.id, id))
.run();
queueAuto('page', id);
return { saved: true };
},
delete: ({ params }) => {

View file

@ -45,7 +45,7 @@
<RichEditor name="content" value={p.content} label="Inhalt" hint="Darf leer bleiben, wenn die Seite nur Unterseiten zeigt." />
</Panel>
<EasyLanguageField value={p.contentEasy} />
<EasyLanguageField value={p.contentEasy} auto={data.easyAuto} />
<Panel title="Anhänge & Ansprechpartner">
<AttachmentsField name="attachments" value={p.attachments} />

View file

@ -0,0 +1,16 @@
import { currentConfig, type AiConfig } from '$lib/server/ai';
import { AI_PROVIDERS, type AiProvider } from '$lib/settings';
/** Konfiguration aus dem (noch ungespeicherten) Formular – ohne Schlüssel gilt der gespeicherte */
export function configFrom(body: Record<string, unknown> | null): AiConfig {
const stored = currentConfig();
const provider = (typeof body?.provider === 'string' && body.provider in AI_PROVIDERS ? body.provider : stored.provider) as AiProvider;
const p = AI_PROVIDERS[provider];
const str = (v: unknown) => (typeof v === 'string' ? v.trim() : '');
return {
provider,
model: str(body?.model) || p.defaultModel,
baseUrl: str(body?.baseUrl) || p.defaultBaseUrl,
apiKey: str(body?.apiKey) || stored.apiKey
};
}

View file

@ -0,0 +1,13 @@
import { error, json } from '@sveltejs/kit';
import { requireAdmin } from '$lib/server/forms';
import { AiError, listModels } from '$lib/server/ai';
import { configFrom } from '../config';
export const POST = async ({ request, locals }) => {
requireAdmin(locals.user);
try {
return json({ models: await listModels(configFrom(await request.json().catch(() => null))) });
} catch (e) {
error(400, e instanceof AiError ? e.message : 'Modelle konnten nicht geladen werden.');
}
};

View file

@ -0,0 +1,26 @@
import { error, json } from '@sveltejs/kit';
import { requireAdmin } from '$lib/server/forms';
import { AiError, streamText } from '$lib/server/ai';
import { allow } from '$lib/server/ratelimit';
import { configFrom } from '../config';
/** Kurzer Probelauf mit einem Satz – kostet nur Bruchteile eines Cents */
export const POST = async ({ request, locals }) => {
requireAdmin(locals.user);
if (!allow(`ki-test:${locals.user!.id}`, 20, 3600e3)) error(429, 'Zu viele Tests. Bitte warte etwas.');
const config = configFrom(await request.json().catch(() => null));
if (!config.model) error(400, 'Bitte zuerst ein Modell wählen.');
const started = Date.now();
try {
let out = '';
for await (const chunk of streamText(
config,
'Du überträgst Texte in Leichte Sprache. Antworte nur mit dem Ergebnis.',
'Übertrage in Leichte Sprache: „Aufgrund der Betriebsversammlung entfällt am Mittwoch die Frühstückspause.“'
))
out += chunk;
return json({ text: out.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 500), ms: Date.now() - started });
} catch (e) {
error(400, e instanceof AiError ? e.message : 'Der Test ist fehlgeschlagen.');
}
};

View file

@ -1,46 +0,0 @@
import { error } from '@sveltejs/kit';
import { allow } from '$lib/server/ratelimit';
import { STREAM_ERROR } from '$lib/easy-language';
import { EasyLanguageError, easyLanguageAvailable, streamEasyLanguage } from '$lib/server/easy-language';
export const POST = async ({ request, locals }) => {
if (!easyLanguageAvailable()) error(503, 'Die KI-Funktion ist nicht eingerichtet (ANTHROPIC_API_KEY fehlt).');
if (!allow(`ki-leichte-sprache:${locals.user!.id}`, 30, 3600e3)) error(429, 'Zu viele Anfragen. Bitte warte etwas.');
const body = await request.json().catch(() => null);
const title = typeof body?.title === 'string' ? body.title.slice(0, 300) : '';
const html = typeof body?.html === 'string' ? body.html : '';
const generator = streamEasyLanguage({ title, html }, request.signal);
// Ersten Abschnitt abwarten, damit Eingabefehler als normaler Fehler-Status ankommen
let first: IteratorResult<string>;
try {
first = await generator.next();
} catch (e) {
if (e instanceof EasyLanguageError) error(400, e.message);
throw e;
}
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
try {
if (!first.done) controller.enqueue(encoder.encode(first.value));
for await (const chunk of generator) controller.enqueue(encoder.encode(chunk));
} catch (e) {
const message = e instanceof EasyLanguageError ? e.message : 'Unerwarteter Fehler bei der KI.';
if (!(e instanceof EasyLanguageError)) console.error('[leichte-sprache]', e);
controller.enqueue(encoder.encode(STREAM_ERROR + message));
}
controller.close();
},
cancel() {
generator.return(undefined);
}
});
return new Response(stream, {
headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no' }
});
};

View file

@ -0,0 +1,59 @@
import { error, json } from '@sveltejs/kit';
import { and, eq, lte } from 'drizzle-orm';
import { db } from '$lib/server/db';
import { pages, posts } from '$lib/server/db/schema';
import { AiError } from '$lib/server/ai';
import { generate, isFresh, needsAuto, type EasyKind } from '$lib/server/easy-auto';
import { allow } from '$lib/server/ratelimit';
import { STREAM_ERROR } from '$lib/easy-language';
/** Veröffentlichten Text anhand der Adresse finden */
function find(kind: EasyKind, slug: string) {
if (kind === 'post')
return db
.select()
.from(posts)
.where(and(eq(posts.slug, slug), eq(posts.published, true), lte(posts.publishedAt, new Date())))
.get();
return db.select().from(pages).where(and(eq(pages.slug, slug), eq(pages.published, true))).get();
}
/**
* Leichte Sprache für Leser: vorhandene Fassung sofort, sonst live übertragen
* (Text wird gestreamt und für alle weiteren Leser gespeichert).
*/
export const POST = async ({ request, getClientAddress }) => {
const body = await request.json().catch(() => null);
const kind: EasyKind = body?.typ === 'page' ? 'page' : 'post';
const slug = typeof body?.slug === 'string' ? body.slug.slice(0, 200) : '';
const row = find(kind, slug);
if (!row) error(404, 'Text nicht gefunden.');
if (row.contentEasy.trim()) return json({ html: row.contentEasy, auto: false });
if (isFresh(row)) return json({ html: row.contentEasyAuto, auto: true });
if (!needsAuto(row)) error(503, 'Leichte Sprache ist für diesen Text gerade nicht verfügbar.');
// Kostenschutz: pro Gerät höchstens 20 neue Übertragungen pro Stunde
if (!allow(`ki-ip:${getClientAddress()}`, 20, 3600e3)) error(429, 'Bitte versuche es etwas später noch einmal.');
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
try {
// Läuft schon eine Übertragung (anderer Leser, Hintergrund), wird gewartet und das Ergebnis geschickt
let streamed = false;
const html = await generate(kind, row.id, (chunk) => {
streamed = true;
controller.enqueue(encoder.encode(chunk));
});
if (!streamed) controller.enqueue(encoder.encode(html));
} catch (e) {
const message = e instanceof AiError ? e.message : 'Leichte Sprache ist gerade nicht verfügbar.';
controller.enqueue(encoder.encode(STREAM_ERROR + message));
}
controller.close();
}
});
return new Response(stream, {
headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no' }
});
};