'use strict'; const conf = require('>/conf'); // Pull the first JSON object out of a model response( tolerates ```json fences / prose). function extractJSON(content){ let text = String(content).replace(/```json/gi, '').replace(/```/g, '').trim(); let start = text.indexOf('{'); let end = text.lastIndexOf('}'); if(start === -1 || end === -1) throw new Error('No JSON in model response'); return JSON.parse(text.slice(start, end + 1)); } // One-shot JSON chat against the Ollama cloud model. async function chatJSON(system, user){ let res = await fetch(`${conf.ollama.url}/api/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${conf.ollama.apiKey}`, }, body: JSON.stringify({ model: conf.ollama.model, stream: false, format: 'json', messages: [ { role: 'system', content: system }, { role: 'user', content: user }, ], }), }); if(!res.ok){ let error = new Error('OllamaError'); error.message = `Ollama chat failed( ${res.status})`; error.status = 502; throw error; } let data = await res.json(); return extractJSON(data.message && data.message.content); } module.exports = { chatJSON, extractJSON };