Files
Tiktok-Rezepte/backend/services/ai.js
2026-08-26 19:05:33 +02:00

52 lines
1.4 KiB
JavaScript

import { SYSTEM_PROMPT } from '../prompts/extractRecipe.js';
const OLLAMA_URL = process.env.OLLAMA_URL || 'http://localhost:11434';
const MODEL = process.env.OLLAMA_MODEL || 'mistral';
export async function isOllamaAvailable() {
try {
const res = await fetch(`${OLLAMA_URL}/api/tags`, { signal: AbortSignal.timeout(3000) });
return res.ok;
} catch {
return false;
}
}
export async function extractRecipe(description) {
const response = await fetch(`${OLLAMA_URL}/api/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: MODEL,
system: SYSTEM_PROMPT,
prompt: `Extrahiere ein Rezept aus dieser TikTok-Videobeschreibung:\n\n${description}`,
stream: false,
options: {
num_ctx: 2048,
temperature: 0.1,
},
}),
signal: AbortSignal.timeout(240000),
});
if (!response.ok) {
throw new Error(`Ollama Fehler: ${response.status}`);
}
const data = await response.json();
let text = data.response.trim();
if (text.startsWith('```')) {
text = text.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '');
}
const jsonStart = text.indexOf('{');
const jsonEnd = text.lastIndexOf('}');
if (jsonStart === -1 || jsonEnd === -1 || jsonEnd <= jsonStart) {
throw new Error('Kein valides JSON in der Modell-Antwort');
}
text = text.slice(jsonStart, jsonEnd + 1);
return JSON.parse(text);
}