import { AgentCompletion, AgentArgs, SystemMessage, UserMessage } from './types'; export interface ExplainedAnswer { explanation: string; answer: string; } export interface ChainOfThoughtArgs extends AgentArgs { question: string; temperature?: number; instructions?: string; } export async function chainOfThought(args: ChainOfThoughtArgs): Promise> { const { completePrompt, question, temperature, instructions } = args; const systemContent = instructions ? `${instructions}\n\nYou must return your response as a JSON object with "explanation" and "answer" fields.` : 'You must return your response as a JSON object with "explanation" and "answer" fields.'; const system: SystemMessage = { role: 'system', content: systemContent }; const prompt: UserMessage = { role: 'user', content: question }; const result = await completePrompt({ prompt, system, temperature, jsonMode: true }); if (!result.completed || !result.value) { return { completed: false, error: result.error }; } if (typeof result.value === 'object') { const parsed = result.value as any; return { completed: true, value: { explanation: parsed.explanation ?? '', answer: parsed.answer ?? '', }, }; } const rawText = result.value as string; let text = rawText.replace(/^```(?:json)?\s*/i, '').replace(/\s*```\s*$/, ''); const start = text.indexOf('{'); const end = text.lastIndexOf('}'); if (start !== -1 && end > start) { const candidate = text.substring(start, end + 1); try { const parsed = JSON.parse(candidate); return { completed: true, value: { explanation: parsed.explanation ?? '', answer: parsed.answer ?? '', }, }; } catch (err) { console.error('chainOfThought: JSON.parse failed:', (err as Error).message); console.error('chainOfThought: raw response was:', rawText); } } else { console.error('chainOfThought: no JSON object found in response. Raw text:', rawText); } // Graceful fallback: model returned prose without parseable JSON. // Treat the full text as the answer so the user still sees something useful. const fallback = rawText.trim(); if (fallback) { return { completed: true, value: { explanation: '', answer: fallback } }; } return { completed: false, error: new Error('Empty response from model') }; }