69 lines
1.9 KiB
JavaScript
69 lines
1.9 KiB
JavaScript
import { SYSTEM_PROMPT } from '../prompts/extractRecipe.js';
|
|
|
|
const GROQ_API_KEY = process.env.GROQ_API_KEY;
|
|
const GROQ_MODEL = process.env.GROQ_MODEL || 'llama-3.1-8b-instant';
|
|
const GROQ_URL = 'https://api.groq.com/openai/v1/chat/completions';
|
|
|
|
export async function isAiAvailable() {
|
|
if (!GROQ_API_KEY) return false;
|
|
try {
|
|
const res = await fetch(GROQ_URL, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${GROQ_API_KEY}`,
|
|
},
|
|
body: JSON.stringify({
|
|
model: GROQ_MODEL,
|
|
messages: [{ role: 'user', content: 'ping' }],
|
|
max_tokens: 1,
|
|
}),
|
|
signal: AbortSignal.timeout(10000),
|
|
});
|
|
return res.ok;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function extractRecipe(description) {
|
|
const response = await fetch(GROQ_URL, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${GROQ_API_KEY}`,
|
|
},
|
|
body: JSON.stringify({
|
|
model: GROQ_MODEL,
|
|
messages: [
|
|
{ role: 'system', content: SYSTEM_PROMPT },
|
|
{ role: 'user', content: `Extrahiere ein Rezept aus dieser TikTok-Videobeschreibung:\n\n${description}` },
|
|
],
|
|
temperature: 0.1,
|
|
max_tokens: 2048,
|
|
}),
|
|
signal: AbortSignal.timeout(30000),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const err = await response.text();
|
|
throw new Error(`Groq Fehler: ${response.status} - ${err}`);
|
|
}
|
|
|
|
const data = await response.json();
|
|
let text = data.choices[0].message.content.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);
|
|
}
|