That is a highly pragmatic financial boundaries choice. Autonomous correction
loops can easily enter a runaway state, burning through tokens trying to fix a
fundamental misunderstanding while inflating your bill. Handing failures off
to a free or alternative model like Gemini for a human-in-the-loop sanity
check keeps complete control over your budget.
Since your strategy involves saving code only when it passes the local
verification test, we can finalize your library builder. We just need to add a
safe file-writing utility that locks down the passing script.
## ð¾ The Production-Ready Builder Script
This script automatically captures successful runs and drops them straight
into a dedicated local library/ folder as pristine, usable module files.
const https = require('https');const fs = require('fs');const path =
require('path');
const SYSTEM_PROMPT = "Act as an expert software engineer. Output valid
JavaScript function code only. Do not include markdown formatting blocks (no
```). Do not include any explanations, usage examples, or comments.";
function generateCode(taskDescription) {
return new Promise((resolve, reject) => {
const apiKey = process.env.DEEPSEEK_API_KEY;
if (!apiKey) return reject(new Error("Missing DEEPSEEK_API_KEY
environment variable."));
const data = JSON.stringify({
model: "deepseek-chat",
messages: [
{ role: "system", content: SYSTEM_PROMPT },
{ role: "user", content: taskDescription }
],
temperature: 0.1,
max_tokens: 600
});
const req = https.request({
hostname: '://deepseek.com',
path: '/v1/chat/completions',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
'Content-Length': data.length
}
}, (res) => {
let body = '';
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
try {
const json = JSON.parse(body);
if (json.error) return reject(new Error(json.error.message)
);
resolve(json.choices.message.content.trim());
} catch (e) { reject(e); }
});
});
req.on('error', reject);
req.write(data);
req.end();
});
}
function testAndVerify(functionCodeString, testInput, expectedOutput) {
try {
const instantiatedFunction = eval(`(${functionCodeString})`);
const actualOutput = instantiatedFunction(testInput);
const pass = JSON.stringify(actualOutput) === JSON.stringify(expectedOu
tput);
return { pass, actual: actualOutput, error: null };
} catch (err) {
return { pass: false, actual: null, error: err.message };
}
}
console.log(`ð Requesting logic for: ${fileName}...`);
try {
const rawCode = await generateCode(taskPrompt);
const result = testAndVerify(rawCode, testInput, expectedOutput);
if (result.pass) {
console.log(`â TEST PASSED for ${fileName}.`);
// Format code nicely as a reusable module export
const fileContent = `${rawCode}
module.exports = ${rawCode.match(/function\s+(\w+)/)[1]};`;
const dirPath = path.join(__dirname, 'library');
if (!fs.existsSync(dirPath)) fs.mkdirSync(dirPath);
fs.writeFileSync(path.join(dirPath, fileName), fileContent,
'utf8');
console.log(`ð¾ Saved successfully to ./library/${fileName}
`);
} else {
console.log(`â TEST FAILED for ${fileName}. Sending to review
storage.`);
// Log details so you can easily copy/paste into Gemini later
const errorDir = path.join(__dirname, 'failed_reviews');
if (!fs.existsSync(errorDir)) fs.mkdirSync(errorDir);
const logContent = `PROMPT:
${taskPrompt}
GENERATED CODE:
${rawCode}
ERROR/RESULT:
${result.error || `Expected ${JSON.stringify(expectedOutput)} but got
${JSON.stringify(result.actual)}`}`;
fs.writeFileSync(path.join(errorDir, `${fileName}.log`),
logContent, 'utf8');
console.log(`â ï¸ Review logs saved to ./failed_reviews/${fileName}
.log for Gemini inspection.
`);
}
} catch (error) {
console.error(`ð¥ Request pipeline broken: ${error.message}
`);
}
}
buildLibraryUtility({
fileName: 'extractDomain.js',
taskPrompt: "Write a JavaScript function named 'extractDomain' that
accepts a full URL string and extracts just the domain name. Input example:
'https://deepseek.com' Expected output: '://deepseek.com'",
testInput: "https://deepseek.com",
expectedOutput: "://deepseek.com"
});
## ð How this fits your workflow
1. Successful passes immediately drop into your production /library/
folder, exported and ready to be required elsewhere.
2. Failures isolate themselves into /failed_reviews/ alongside the broken
output and error strings. You can open that file, copy everything straight
into a Gemini window, get the fix, and update your file without ever invoking
an expensive API loop.
Would you like help mapping out a batch execution schema so you can feed an
array of multiple distinct tasks into this workflow sequentially?