import { completePrompt, ContentBlock } from '../models'; import { getTransformInstr } from '../service/transformPage'; import { parseBuilderResponse } from './anthropic'; import { Builder, BuilderResult, OPENAI_CHANGE_OPS_SCHEMA } from './types'; /** * Create an OpenAI-tuned builder. * Uses OpenAI structured outputs (json_schema) for reliable JSON responses. */ export function createOpenAIBuilder(complete: completePrompt, userInstructions?: string, productName?: string): Builder { const name = productName ?? 'SynthOS'; return { async run(currentPage, additionalSections, userMessage, newBuild, attachments?): Promise { try { // -- System message -- const systemParts: string[] = [ `${currentPage.title}\n${currentPage.content}`, ]; for (const section of additionalSections) { if (section.content) { systemParts.push(`${section.title}\n${section.content}`); } } const systemContent = systemParts.join('\n\n'); // -- User message -- const instructionParts: string[] = []; if (userInstructions?.trim()) { instructionParts.push(userInstructions); } for (const section of additionalSections) { if (section.instructions?.trim()) { instructionParts.push(section.instructions); } } instructionParts.push(getTransformInstr(name)); const instructions = instructionParts.filter(s => s.trim() !== '').join('\n'); const promptText = `\n${userMessage}\n\n\n${instructions}`; // Build prompt content — multimodal when image attachments are present const imageAttachments = (attachments ?? []).filter(a => a.mediaType.startsWith('image/')); let promptContent: string | ContentBlock[]; if (imageAttachments.length > 0) { const blocks: ContentBlock[] = [{ type: 'text', text: promptText }]; for (const att of imageAttachments) { blocks.push({ type: 'image', mediaType: att.mediaType, data: att.data }); } promptContent = blocks; } else { promptContent = promptText; } const result = await complete({ system: { role: 'system', content: systemContent }, prompt: { role: 'user', content: promptContent }, jsonSchema: OPENAI_CHANGE_OPS_SCHEMA, }); if (!result.completed) { return { kind: 'error', error: result.error ?? new Error('Model call failed') }; } // Unwrap the { changes: [...] } envelope from structured output return parseOpenAIResponse(result.value!); } catch (err: unknown) { return { kind: 'error', error: err instanceof Error ? err : new Error(String(err)) }; } } }; } /** * Parse the OpenAI structured output response. * The schema wraps the array in { changes: [...] }, so unwrap before * delegating to the shared parser. */ function parseOpenAIResponse(raw: string): BuilderResult { try { const parsed = JSON.parse(raw); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && Array.isArray(parsed.changes)) { const message = typeof parsed.message === 'string' ? parsed.message : undefined; return { kind: 'transforms', changes: parsed.changes, message }; } } catch { // fall through to shared parser } return parseBuilderResponse(raw); }