Lesson 20: Advanced Code Generation
This lesson shows how to perform sophisticated "fill-in-the-middle" code generation by providing the Task API with a prefix and a suffix.
Code: lesson_20_advanced_code_generation.mjs
This script defines a `prefix` (the start of a class) and a `suffix` (the end of a class) and instructs the `code-generate:default` task to write the code that completes the class definition.
// lesson_20_advanced_code_generation.mjs
// Merci SDK Tutorial: Lesson 20 - Advanced Code Generation with the Task API
// --- IMPORTS ---
import { MerciClient } from '../lib/merci.2.14.0.mjs';
import { token } from '../secret/token.mjs';
const TASK_ID = 'code-generate:default';
async function main() {
console.log(`--- Merci SDK Tutorial: Lesson 20 - Advanced Code Generation (Task: ${TASK_ID}) ---`);
try {
// --- STEP 1: INITIALIZE THE CLIENT ---
console.log('[STEP 1] Initializing MerciClient...');
const client = new MerciClient({ token });
// --- STEP 2: DEFINE THE CODE CONTEXT (PREFIX & SUFFIX) ---
console.log('
[STEP 2] Defining the context for code generation...');
const prefix = `
class DataProcessor {
constructor(data) {
this.data = data;
}
// TODO: Implement the 'calculate_average' method
`;
const suffix = `
}
`;
// The task is to generate the code that fits between the prefix and suffix.
const instructions = "Implement the 'calculate_average' method. It should take a 'column_name' string as an argument, access the data via 'this.data', and return the average of the values in that column. The data is an array of objects. Include JSDoc comments.";
const taskParameters = {
instructions,
language: "javascript",
prefix,
suffix
};
console.log('Instructions:', instructions);
// --- STEP 3: EXECUTE THE TASK ---
console.log(`\n[STEP 3] Executing task "${TASK_ID}" with .execute() to get the full result...`);
const result = await client.tasks.execute(TASK_ID, taskParameters);
console.log('[INFO] Task execution finished.');
// --- STEP 4: ASSEMBLE AND DISPLAY THE FINAL CODE ---
console.log('
[STEP 4] Assembling the final code...');
const generatedCode = result.content;
const finalCode = prefix + generatedCode + suffix;
console.log('
--- FINAL RESULT ---');
console.log('The Task API successfully generated the missing method within the class structure:\n');
console.log('-------------------- CODE START --------------------');
console.log(finalCode);
console.log('--------------------- CODE END ---------------------');
} catch (error) {
console.error('
[FATAL ERROR] An error occurred during the operation.');
console.error(' Message:', error.message);
if (error.status) {
console.error(' API Status:', error.status);
}
if (error.details) {
console.error(' Details:', JSON.stringify(error.details, null, 2));
}
if (error.stack) {
console.error(' Stack:', error.stack);
}
console.error('
Possible causes: Invalid token, network issues, or an API service problem.');
process.exit(1); // Exit with a non-zero code to indicate failure.
}
}
main().catch(console.error);
Expected Output
The output shows the fully assembled code, with the AI-generated `calculate_average` method correctly inserted between the prefix and suffix, demonstrating the power of context-aware code generation.
--- Merci SDK Tutorial: Lesson 20 - Advanced Code Generation (Task: code-generate:default) ---
[STEP 1] Initializing MerciClient...
[STEP 2] Defining the context for code generation...
Instructions: Implement the 'calculate_average' method. It should take a 'column_name' string as an argument, access the data via 'this.data', and return the average of the values in that column. The data is an array of objects. Include JSDoc comments.
[STEP 3] Executing task "code-generate:default" with .execute() to get the full result...
[INFO] Task execution finished.
[STEP 4] Assembling the final code...
--- FINAL RESULT ---
The Task API successfully generated the missing method within the class structure:
-------------------- CODE START --------------------
class DataProcessor {
constructor(data) {
this.data = data;
}
// TODO: Implement the 'calculate_average' method
/**
* Calculates the average of a given column.
* @param {string} column_name The name of the column to calculate the average of.
* @returns {number} The average of the values in the column.
*/
calculate_average(column_name) {
const values = this.data.map(item => item[column_name]);
const sum = values.reduce((a, b) => a + b, 0);
return sum / values.length;
}
}
--------------------- CODE END ---------------------