|
| 1 | +import PQueue from 'p-queue'; |
| 2 | +import {GenkitRunner} from '../codegen/genkit/genkit-runner.js'; |
| 3 | +import {Environment} from '../configuration/environment.js'; |
| 4 | +import { |
| 5 | + AssessmentConfig, |
| 6 | + AssessmentResult, |
| 7 | + AttemptDetails, |
| 8 | + MultiStepPromptDefinition, |
| 9 | + PromptDefinition, |
| 10 | +} from '../shared-interfaces.js'; |
| 11 | +import {EvalID} from './executors/executor.js'; |
| 12 | +import {ProgressLogger} from '../progress/progress-logger.js'; |
| 13 | +import {resolveContextFiles, setupProjectStructure, writeResponseFiles} from './file-system.js'; |
| 14 | +import {generateInitialFiles} from './generate-initial-files.js'; |
| 15 | +import {generateUserJourneysForApp} from './user-journeys.js'; |
| 16 | +import {BrowserAgentTaskInput} from '../testing/browser-agent/models.js'; |
| 17 | +import {attemptBuildAndTest} from './build-serve-test-loop.js'; |
| 18 | +import {rateGeneratedCode} from '../ratings/rate-code.js'; |
| 19 | +import {DEFAULT_AUTORATER_MODEL_NAME} from '../configuration/constants.js'; |
| 20 | + |
| 21 | +/** |
| 22 | + * Creates and executes a task to generate or load code for a given prompt, |
| 23 | + * attempt to build it, repair it if necessary, and assess its quality. |
| 24 | + * |
| 25 | + * This function handles both online (AI-generated) and local (file-based) code retrieval. |
| 26 | + * It manages build attempts and AI-driven repair cycles. |
| 27 | + * |
| 28 | + * @param evalID ID of the evaluation task. |
| 29 | + * @param env Environment for this evaluation. |
| 30 | + * @param model Name of the LLM to use. |
| 31 | + * @param rootPromptDef Definition of the root prompt being processed. |
| 32 | + * @param localMode A boolean indicating whether to load code from local files instead of generating it. |
| 33 | + * @param skipScreenshots Whether to skip taking screenshot of a running application. |
| 34 | + * @param outputDirectory Directory in which to generate the output. Convenient for debugging. |
| 35 | + * @param abortSignal Abort signal for when the evaluation task should be aborted. |
| 36 | + * @param skipAxeTesting Whether or not to skip Axe testing of the app. |
| 37 | + * @param enableUserJourneyTesting Whether to enable user journey testing of generated apps. |
| 38 | + * @param workerConcurrencyQueue Concurrency queue for controlling parallelism of worker invocations (as they are more expensive than LLM calls). |
| 39 | + * @returns A Promise that resolves to an AssessmentResult object containing all details of the task's execution. |
| 40 | + */ |
| 41 | +export async function startEvaluationTask( |
| 42 | + config: AssessmentConfig, |
| 43 | + evalID: EvalID, |
| 44 | + env: Environment, |
| 45 | + ratingLlm: GenkitRunner, |
| 46 | + rootPromptDef: PromptDefinition | MultiStepPromptDefinition, |
| 47 | + abortSignal: AbortSignal, |
| 48 | + workerConcurrencyQueue: PQueue, |
| 49 | + progress: ProgressLogger, |
| 50 | +): Promise<AssessmentResult[]> { |
| 51 | + // Set up the project structure once for the root project. |
| 52 | + const {directory, cleanup} = await setupProjectStructure( |
| 53 | + env, |
| 54 | + rootPromptDef, |
| 55 | + progress, |
| 56 | + config.outputDirectory, |
| 57 | + ); |
| 58 | + |
| 59 | + const results: AssessmentResult[] = []; |
| 60 | + const defsToExecute = rootPromptDef.kind === 'single' ? [rootPromptDef] : rootPromptDef.steps; |
| 61 | + |
| 62 | + for (const promptDef of defsToExecute) { |
| 63 | + const [fullPromptText, systemInstructions] = await Promise.all([ |
| 64 | + env.getPrompt(promptDef.systemPromptType, promptDef.prompt, config.ragEndpoint), |
| 65 | + env.getPrompt(promptDef.systemPromptType, ''), |
| 66 | + ]); |
| 67 | + |
| 68 | + // Resolve the context files from the root. We need to do this after the project is set up |
| 69 | + // and for each sub-prompt, because the project will be augmented on each iteration. |
| 70 | + const contextFiles = await resolveContextFiles(promptDef.contextFilePatterns, directory); |
| 71 | + |
| 72 | + // Generate the initial set of files through the LLM. |
| 73 | + const initialResponse = await generateInitialFiles( |
| 74 | + config, |
| 75 | + evalID, |
| 76 | + env, |
| 77 | + promptDef, |
| 78 | + { |
| 79 | + directory, |
| 80 | + systemInstructions, |
| 81 | + combinedPrompt: fullPromptText, |
| 82 | + executablePrompt: promptDef.prompt, |
| 83 | + }, |
| 84 | + contextFiles, |
| 85 | + abortSignal, |
| 86 | + progress, |
| 87 | + ); |
| 88 | + |
| 89 | + const toolLogs = initialResponse.toolLogs ?? []; |
| 90 | + |
| 91 | + if (!initialResponse) { |
| 92 | + progress.log( |
| 93 | + promptDef, |
| 94 | + 'error', |
| 95 | + 'Failed to generate initial code using AI. Skipping this app.', |
| 96 | + ); |
| 97 | + await cleanup(); |
| 98 | + break; |
| 99 | + } |
| 100 | + |
| 101 | + try { |
| 102 | + // Write the generated files to disk. |
| 103 | + // Note: This can fail when the LLM e.g. produced a wrong file name that is too large, |
| 104 | + // and results in a file system error. Gracefully handle this so we can continue testing. |
| 105 | + // Write the generated files to disk within the project directory. |
| 106 | + await writeResponseFiles(directory, initialResponse.files, env, rootPromptDef.name); |
| 107 | + |
| 108 | + // If we're in a multi-step prompt, also write out to dedicated directories |
| 109 | + // for each sub-prompt so that we can inspect the output along the way. |
| 110 | + if (rootPromptDef.kind === 'multi-step') { |
| 111 | + await writeResponseFiles(directory, initialResponse.files, env, promptDef.name); |
| 112 | + } |
| 113 | + } catch (e) { |
| 114 | + let details = `Error: ${e}`; |
| 115 | + |
| 116 | + if ((e as Partial<Error>).stack) { |
| 117 | + details += (e as Error).stack; |
| 118 | + } |
| 119 | + |
| 120 | + progress.log( |
| 121 | + promptDef, |
| 122 | + 'error', |
| 123 | + 'Failed to generate initial code using AI. Skipping this app.', |
| 124 | + details, |
| 125 | + ); |
| 126 | + |
| 127 | + await cleanup(); |
| 128 | + break; |
| 129 | + } |
| 130 | + |
| 131 | + const userJourneys = config.enableUserJourneyTesting |
| 132 | + ? await generateUserJourneysForApp( |
| 133 | + ratingLlm, |
| 134 | + rootPromptDef.name, |
| 135 | + defsToExecute[0].prompt, |
| 136 | + initialResponse.files, |
| 137 | + abortSignal, |
| 138 | + ) |
| 139 | + : undefined; |
| 140 | + |
| 141 | + // TODO: Only execute the serve command on the "final working attempt". |
| 142 | + // TODO: Incorporate usage. |
| 143 | + const userJourneyAgentTaskInput: BrowserAgentTaskInput | undefined = userJourneys |
| 144 | + ? { |
| 145 | + userJourneys: userJourneys.result, |
| 146 | + appPrompt: defsToExecute[0].prompt, |
| 147 | + } |
| 148 | + : undefined; |
| 149 | + |
| 150 | + const attemptDetails: AttemptDetails[] = []; // Store details for assessment.json |
| 151 | + |
| 152 | + // Try to build the files in the root prompt directory. |
| 153 | + // This will also attempt to fix issues with the generated code. |
| 154 | + const attempt = await attemptBuildAndTest( |
| 155 | + config, |
| 156 | + evalID, |
| 157 | + env, |
| 158 | + rootPromptDef, |
| 159 | + directory, |
| 160 | + contextFiles, |
| 161 | + initialResponse, |
| 162 | + attemptDetails, |
| 163 | + abortSignal, |
| 164 | + workerConcurrencyQueue, |
| 165 | + progress, |
| 166 | + userJourneyAgentTaskInput, |
| 167 | + ); |
| 168 | + |
| 169 | + if (!attempt) { |
| 170 | + await cleanup(); |
| 171 | + break; |
| 172 | + } |
| 173 | + |
| 174 | + const score = await rateGeneratedCode( |
| 175 | + ratingLlm, |
| 176 | + env, |
| 177 | + promptDef, |
| 178 | + fullPromptText, |
| 179 | + attempt.outputFiles, |
| 180 | + attempt.buildResult, |
| 181 | + attempt.serveTestingResult, |
| 182 | + attempt.repairAttempts, |
| 183 | + attempt.axeRepairAttempts, |
| 184 | + abortSignal, |
| 185 | + progress, |
| 186 | + config.autoraterModel || DEFAULT_AUTORATER_MODEL_NAME, |
| 187 | + attempt.testResult ?? null, |
| 188 | + attempt.testRepairAttempts, |
| 189 | + ); |
| 190 | + |
| 191 | + results.push({ |
| 192 | + promptDef: { |
| 193 | + // Note: we don't pass the prompt def along directly, |
| 194 | + // because it can contain data that cannot be encoded. |
| 195 | + name: promptDef.name, |
| 196 | + prompt: promptDef.prompt, |
| 197 | + }, |
| 198 | + outputFiles: attempt.outputFiles, |
| 199 | + finalAttempt: attempt, |
| 200 | + score, |
| 201 | + repairAttempts: attempt.repairAttempts, |
| 202 | + attemptDetails, |
| 203 | + userJourneys: userJourneys, |
| 204 | + axeRepairAttempts: attempt.axeRepairAttempts, |
| 205 | + toolLogs, |
| 206 | + testResult: attempt.testResult ?? null, |
| 207 | + testRepairAttempts: attempt.testRepairAttempts, |
| 208 | + } satisfies AssessmentResult); |
| 209 | + } |
| 210 | + |
| 211 | + await cleanup(); |
| 212 | + return results; |
| 213 | +} |
0 commit comments