156 lines
6.8 KiB
TypeScript
156 lines
6.8 KiB
TypeScript
import "server-only";
|
|
import type pg from "pg";
|
|
import { z } from "zod";
|
|
import type { RawRecipe } from "./recipe-import";
|
|
import { isRouterAlias, isRouterUrl, ROUTER_MODEL, routerEndpoint } from "./olares-router";
|
|
import { unseal } from "./vault";
|
|
|
|
// AI über einen OpenAI-kompatiblen Endpunkt. Standard ist der Olares Router der
|
|
// eigenen Box (lib/olares-router.ts), ein eigener Endpunkt ist optional. Regeln
|
|
// (CLAUDE.md, „AI“): die App kennt nur Modellnamen, kein stilles Ausweichen in
|
|
// die Cloud, das Ergebnis ist ein Entwurf, den ein Mensch prüft und speichert.
|
|
|
|
export type AiSettings = {
|
|
endpoint: string;
|
|
textModel: string | null;
|
|
visionModel: string | null;
|
|
apiKeyEnc: Buffer | null;
|
|
source?: "router" | "manual";
|
|
};
|
|
|
|
export class AiNotConfigured extends Error {}
|
|
export class AiUnavailable extends Error {}
|
|
|
|
export async function loadAi(client: pg.PoolClient | pg.Client): Promise<AiSettings | null> {
|
|
const row = (
|
|
await client.query(
|
|
`select endpoint, text_model as "textModel", vision_model as "visionModel", api_key_enc as "apiKeyEnc" from household_ai`,
|
|
)
|
|
).rows[0];
|
|
return row ?? null;
|
|
}
|
|
|
|
/** Die geltende Einstellung: ein eigener Endpunkt, sonst der Router der Box
|
|
* (auch, wenn früher der Router gespeichert wurde — dann mit der aktuellen Adresse).
|
|
* `origin` ist die eigene Adresse aus der Tabelle `instance`. */
|
|
export function effectiveAi(stored: AiSettings | null, origin: string | null): AiSettings | null {
|
|
if (stored && !isRouterUrl(stored.endpoint)) return { ...stored, source: "manual" };
|
|
const endpoint = origin ? routerEndpoint(origin) : null;
|
|
if (!endpoint) return stored ? { ...stored, source: "router" } : null;
|
|
return { endpoint, textModel: ROUTER_MODEL, visionModel: ROUTER_MODEL, apiKeyEnc: null, source: "router" };
|
|
}
|
|
|
|
const base = (endpoint: string) => endpoint.replace(/\/+$/, "");
|
|
|
|
async function headers(settings: AiSettings): Promise<Record<string, string>> {
|
|
const h: Record<string, string> = { "content-type": "application/json" };
|
|
if (settings.apiKeyEnc) h.authorization = `Bearer ${await unseal(settings.apiKeyEnc)}`;
|
|
return h;
|
|
}
|
|
|
|
export type ConnectionCheck =
|
|
| { ok: true; models: string[]; textFound: boolean | null; visionFound: boolean | null }
|
|
| { ok: false; reason: "unreachable" | "key" | "status" | "login" };
|
|
|
|
/** „Verbindung prüfen“: GET /models — erreichbar, Schlüssel angenommen, Modelle vorhanden? */
|
|
export async function checkConnection(settings: AiSettings): Promise<ConnectionCheck> {
|
|
let res: Response;
|
|
try {
|
|
res = await fetch(`${base(settings.endpoint)}/models`, {
|
|
headers: await headers(settings),
|
|
redirect: "manual",
|
|
signal: AbortSignal.timeout(10_000),
|
|
});
|
|
} catch {
|
|
return { ok: false, reason: "unreachable" };
|
|
}
|
|
// Eine Weiterleitung oder eine HTML-Seite heißt: Vor dem Dienst sitzt eine
|
|
// Anmeldung (bei Olares der Zugang von außen statt der Adresse für Apps).
|
|
if (res.status >= 300 && res.status < 400) return { ok: false, reason: "login" };
|
|
if (res.status === 401 || res.status === 403) return { ok: false, reason: "key" };
|
|
if (!res.ok) return { ok: false, reason: "status" };
|
|
if (!/json/.test(res.headers.get("content-type") ?? "")) return { ok: false, reason: "login" };
|
|
const data = (await res.json().catch(() => ({}))) as { data?: { id?: string }[] };
|
|
const models = (data.data ?? []).map((m) => m.id ?? "").filter(Boolean);
|
|
const has = (m: string | null) => (m ? models.includes(m) || isRouterAlias(m) : null);
|
|
return { ok: true, models, textFound: has(settings.textModel), visionFound: has(settings.visionModel) };
|
|
}
|
|
|
|
type Content = string | ({ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } })[];
|
|
|
|
/** Modellantwort → JSON-Objekt. Nachdenk-Blöcke und Code-Zäune fallen weg. */
|
|
export function parseJsonReply(text: string): unknown {
|
|
const cleaned = text.replace(/<think>[\s\S]*?<\/think>/g, "").replace(/```(?:json)?/g, "");
|
|
const start = cleaned.indexOf("{");
|
|
const end = cleaned.lastIndexOf("}");
|
|
if (start < 0 || end <= start) return null;
|
|
try {
|
|
return JSON.parse(cleaned.slice(start, end + 1));
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Eine Frage an das Text- oder Bildmodell; die Antwort muss JSON sein. */
|
|
export async function askJson(settings: AiSettings, kind: "text" | "vision", system: string, user: Content): Promise<unknown> {
|
|
const model = kind === "vision" ? settings.visionModel : settings.textModel;
|
|
if (!model) throw new AiNotConfigured(kind);
|
|
let res: Response;
|
|
try {
|
|
res = await fetch(`${base(settings.endpoint)}/chat/completions`, {
|
|
method: "POST",
|
|
headers: await headers(settings),
|
|
signal: AbortSignal.timeout(120_000),
|
|
body: JSON.stringify({
|
|
model,
|
|
temperature: 0,
|
|
// Ein nachdenkendes Modell braucht Platz, sonst kommt nur das Nachdenken an (Rocket).
|
|
max_tokens: 6000,
|
|
messages: [
|
|
{ role: "system", content: system },
|
|
{ role: "user", content: user },
|
|
],
|
|
}),
|
|
});
|
|
} catch {
|
|
throw new AiUnavailable("network");
|
|
}
|
|
if (!res.ok) throw new AiUnavailable(`status ${res.status}`);
|
|
const data = (await res.json().catch(() => null)) as { choices?: { message?: { content?: string } }[] } | null;
|
|
return parseJsonReply(data?.choices?.[0]?.message?.content ?? "");
|
|
}
|
|
|
|
export const RECIPE_PROMPT = `You read recipes. Answer with one JSON object only, no prose:
|
|
{"title": string, "portions": number|null, "minutes": number|null, "ingredients": string[], "steps": string[]}
|
|
Rules: copy every ingredient line exactly as printed, with amount and unit, one line per ingredient.
|
|
Copy the steps in order, one entry per step, in the language of the recipe. Do not translate, do not invent
|
|
amounts, do not convert units. If something is missing, use null or an empty list.
|
|
If there is no recipe, answer {"title": "", "portions": null, "minutes": null, "ingredients": [], "steps": []}.`;
|
|
|
|
const recipeReply = z.object({
|
|
title: z.string().catch(""),
|
|
portions: z.number().nullable().catch(null),
|
|
minutes: z.number().nullable().catch(null),
|
|
ingredients: z.array(z.string()).catch([]),
|
|
steps: z.array(z.string()).catch([]),
|
|
});
|
|
|
|
/** Antwort des Modells → dieselbe Form wie der JSON-LD-Import, oder null ohne Rezept. */
|
|
export function recipeFromReply(reply: unknown): RawRecipe | null {
|
|
const parsed = recipeReply.safeParse(reply);
|
|
if (!parsed.success) return null;
|
|
const r = parsed.data;
|
|
const title = r.title.trim().slice(0, 120);
|
|
const ingredients = r.ingredients.map((l) => l.trim()).filter(Boolean).slice(0, 60);
|
|
if (!title || !ingredients.length) return null;
|
|
const whole = (n: number | null, max: number) => (n && n > 0 && n <= max ? Math.round(n) : null);
|
|
return {
|
|
title,
|
|
yield: whole(r.portions, 30),
|
|
totalMinutes: whole(r.minutes, 1440),
|
|
ingredients,
|
|
steps: r.steps.map((s) => s.trim()).filter(Boolean).slice(0, 40),
|
|
image: null,
|
|
};
|
|
}
|