import { completeText } from "./llm"; import { validateLegalAnswer } from "./legalValidator"; import { REWRITE_PROMPT } from "../prompts/repair/legal-answer-rewrite"; import type { UserApiKeys } from "./llm/types"; export async function validateAndRewrite( draft: string, model: string, apiKeys?: UserApiKeys ): Promise { let currentText = draft; let attempts = 0; const maxAttempts = 2; while (attempts < maxAttempts) { const result = validateLegalAnswer(currentText); if (result.passed) { break; } const issueDescriptions = result.issues.map(i => `- [${i.code}] ${i.message}\n Suggested fix: ${i.suggestedFix || "Rewrite"}`).join("\n"); const prompt = REWRITE_PROMPT.replace("{{issues}}", issueDescriptions).replace("{{answer}}", currentText); try { const rewritten = await completeText({ model, user: prompt, temperature: 0, apiKeys, featureId: "python-review", }); if (rewritten && rewritten.trim()) { currentText = rewritten.trim(); } else { break; // if model fails, stick with what we have } } catch (err) { console.error("[validateAndRewrite] rewrite failed", err); break; } attempts++; } // Final check - if it still fails after max attempts, we could forcibly downgrade confidence, but the prompt says just return it. return currentText; }