All files / api/src/middlewares/optimizer evaluations.ts

39.73% Statements 89/224
86.95% Branches 20/23
50% Functions 1/2
39.73% Lines 89/224

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 3141x 1x 1x             1x 1x             1x                                                                         14x 14x 14x 14x 14x 14x 14x 14x 14x 14x   14x 14x 14x 3x 2x   14x 1x 1x       13x 13x 13x   14x 4x 4x   9x     9x 9x   14x   1x 1x     8x 14x 3x 3x   3x 2x 2x 3x     6x 6x 6x 6x 6x 14x 1x 1x           5x 5x 5x   14x       5x     14x 1x 1x 1x 1x 1x       4x 4x   14x   14x 2x 2x     2x 2x 2x 2x 2x     14x   1x 1x 1x 1x 1x   1x 1x   1x   1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                 14x  
import { generateExampleConversations } from '@api/middlewares/optimizer/system-prompt';
import { regenerateEvaluationsWithExamples } from '@api/optimization/utils/evaluations';
import { generateSeedSystemPromptWithContext } from '@api/optimization/utils/system-prompt';
import type {
  EvaluationMethodConnector,
  LogsStorageConnector,
  UserDataStorageConnector,
} from '@api/types/connector';
import type { AppContext } from '@api/types/hono';
import { emitSSEEvent } from '@api/utils/sse-event-manager';
import { FunctionName } from '@shared/types/api/request';
import type {
  Skill,
  SkillOptimizationArm,
  SkillOptimizationEvaluationResult,
  SkillOptimizationEvaluationRunCreateParams,
} from '@shared/types/data';
import { SkillEventType } from '@shared/types/data/skill-event';
 
export async function addSkillOptimizationEvaluationRun(
  c: AppContext,
  userDataStorageConnector: UserDataStorageConnector,
  arm: SkillOptimizationArm,
  logId: string,
  evaluationResults: SkillOptimizationEvaluationResult[],
) {
  const createParams: SkillOptimizationEvaluationRunCreateParams = {
    agent_id: arm.agent_id,
    skill_id: arm.skill_id,
    cluster_id: arm.cluster_id,
    log_id: logId,
    results: evaluationResults,
  };
 
  const evaluationRun =
    await userDataStorageConnector.createSkillOptimizationEvaluationRun(
      c,
      createParams,
    );
 
  // Emit SSE event for evaluation run creation with full evaluation data
  emitSSEEvent('skill-optimization:evaluation-run-created', {
    evaluationRun: evaluationRun,
    agentId: arm.agent_id,
    skillId: arm.skill_id,
    clusterId: arm.cluster_id,
    logId: logId,
  });
}
 
/**
 * Checks if we should regenerate system prompts and evaluations with real examples.
 * This happens after the first 5 requests to use actual usage data.
 */
export async function checkAndRegenerateEvaluationsEarly(
  c: AppContext,
  functionName: FunctionName,
  userDataStorageConnector: UserDataStorageConnector,
  logsStorageConnector: LogsStorageConnector,
  skill: Skill,
  agentDescription: string,
  evaluationConnectorsMap: Record<string, EvaluationMethodConnector>,
): Promise<void> {
  try {
    // Only attempt to optimize for specific endpoints
    if (
      !(
        functionName === FunctionName.CHAT_COMPLETE ||
        functionName === FunctionName.STREAM_CHAT_COMPLETE ||
        functionName === FunctionName.CREATE_MODEL_RESPONSE
      )
    ) {
      return;
    }
 
    // Re-fetch skill to get latest metadata state (critical for lock check)
    // This ensures we see any locks or completion flags set by concurrent requests
    const latestSkills = await userDataStorageConnector.getSkills(c, {
      id: skill.id,
    });
 
    if (latestSkills.length === 0) {
      return;
    }
 
    const latestSkill = latestSkills[0];
 
    // Check if skill has evaluations_regenerated_at set
    const hasRegeneratedEvaluations =
      latestSkill.evaluations_regenerated_at !== null;
 
    if (hasRegeneratedEvaluations) {
      // Already regenerated once, skip
      return;
    }
 
    // Check if regeneration lock exists and is recent (< 5 minutes old)
    const lockTimestamp = latestSkill.evaluation_lock_acquired_at;
    if (lockTimestamp) {
      const lockAge = Date.now() - new Date(lockTimestamp).getTime();
      const LOCK_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
 
      if (lockAge < LOCK_TIMEOUT_MS) {
        return;
      }
    }
 
    // Try to acquire lock by updating the skill
    const lockTime = new Date().toISOString();
    try {
      await userDataStorageConnector.updateSkill(c, skill.id, {
        evaluation_lock_acquired_at: lockTime,
      });
    } catch (_error) {
      return;
    }
 
    // CRITICAL: Double-check the lock after acquisition to detect race conditions
    // Re-fetch the skill and verify:
    // 1. The lock we just set is still there (not overwritten by another process)
    // 2. No completion flag has been set (another process didn't complete while we were setting the lock)
    const postLockSkills = await userDataStorageConnector.getSkills(c, {
      id: skill.id,
    });
 
    if (postLockSkills.length === 0) {
      return;
    }
 
    const postLockSkill = postLockSkills[0];
 
    // Check if completion flag was set by another process
    if (postLockSkill.evaluations_regenerated_at !== null) {
      await userDataStorageConnector.updateSkill(c, skill.id, {
        evaluation_lock_acquired_at: null,
      });
      return;
    }
 
    // Check if our lock is still there (not overwritten by another process)
    // Compare as Date objects to handle different ISO string formats (Z vs +00:00)
    const postLockTime = postLockSkill.evaluation_lock_acquired_at
      ? new Date(postLockSkill.evaluation_lock_acquired_at).getTime()
      : null;
    const expectedLockTime = new Date(lockTime).getTime();
 
    if (postLockTime !== expectedLockTime) {
      return;
    }
 
    // Count total logs for this skill
    const logs = await logsStorageConnector.getLogs(c, {
      skill_id: skill.id,
      embedding_not_null: true,
      limit: 10, // Get a few more than needed
    });
 
    // Need at least 5 logs to regenerate
    if (logs.length < 5) {
      // Release lock
      await userDataStorageConnector.updateSkill(c, skill.id, {
        evaluation_lock_acquired_at: null,
      });
      return;
    }
 
    const exampleLogs = logs.slice(0, 5); // Use first 5 logs
    const examples = generateExampleConversations(exampleLogs);
 
    if (examples.length === 0) {
      // Release lock
      await userDataStorageConnector.updateSkill(c, skill.id, {
        evaluation_lock_acquired_at: null,
      });
      return;
    }
 
    // Extract response format from the first log that has one (needed for system prompt)
    let responseFormat: unknown;
    for (const log of exampleLogs) {
      const requestBody = log.ai_provider_request_log.request_body;
      if ('response_format' in requestBody && requestBody.response_format) {
        responseFormat = requestBody.response_format;
        break;
      }
    }
 
    // Generate new system prompt with schema and examples
    const newSystemPrompt = await generateSeedSystemPromptWithContext(
      c,
      agentDescription,
      skill.description,
      examples,
      userDataStorageConnector,
      responseFormat,
      skill.allowed_template_variables,
    );
 
    // Get existing evaluations to know which methods to regenerate
    const existingEvaluations =
      await userDataStorageConnector.getSkillOptimizationEvaluations(c, {
        skill_id: skill.id,
      });
    const existingEvaluationMethods = existingEvaluations.map(
      (e) => e.evaluation_method,
    );
 
    // Regenerate evaluations with real examples
    const newEvaluationParams = await regenerateEvaluationsWithExamples(
      c,
      skill,
      agentDescription,
      examples,
      evaluationConnectorsMap,
      existingEvaluationMethods,
      userDataStorageConnector,
    );
 
    // Update evaluations in-place to preserve their IDs and relationships
    // Match evaluations by method to ensure correct updates
    for (const evaluation of existingEvaluations) {
      const newParams = newEvaluationParams.find(
        (p) => p.evaluation_method === evaluation.evaluation_method,
      );
 
      if (newParams) {
        await userDataStorageConnector.updateSkillOptimizationEvaluation(
          c,
          evaluation.id,
          {
            params: newParams.params,
            weight: newParams.weight,
          },
        );
      }
    }
 
    // Update all arms in-place with new system prompts
    // This preserves arm IDs and cluster associations
    const allArms = await userDataStorageConnector.getSkillOptimizationArms(c, {
      skill_id: skill.id,
    });
 
    for (const arm of allArms) {
      await userDataStorageConnector.updateSkillOptimizationArm(c, arm.id, {
        params: {
          ...arm.params,
          system_prompt: newSystemPrompt,
        },
      });
    }
 
    // Reset all arm stats since we have new evaluations and system prompts
    // This forces Thompson Sampling to re-explore with the new configurations
    for (const arm of allArms) {
      await userDataStorageConnector.deleteSkillOptimizationArmStats(c, {
        arm_id: arm.id,
      });
    }
 
    // Reset all cluster total_steps to 0 for early regeneration
    // This restarts the exploration/exploitation balance
    const allClusters =
      await userDataStorageConnector.getSkillOptimizationClusters(c, {
        skill_id: skill.id,
      });
 
    for (const cluster of allClusters) {
      await userDataStorageConnector.updateSkillOptimizationCluster(
        c,
        cluster.id,
        {
          total_steps: 0,
        },
      );
    }
 
    // Mark completion and release lock atomically
    await userDataStorageConnector.updateSkill(c, skill.id, {
      evaluations_regenerated_at: new Date().toISOString(),
      evaluation_lock_acquired_at: null, // Release lock
    });
 
    // Create event for context generation
    await userDataStorageConnector.createSkillEvent(c, {
      agent_id: skill.agent_id,
      skill_id: skill.id,
      cluster_id: null, // Skill-wide event
      event_type: SkillEventType.CONTEXT_GENERATED,
      metadata: {
        log_count: exampleLogs.length,
      },
    });
 
    // Emit SSE event
    emitSSEEvent('skill-optimization:evaluations-regenerated', {
      skillId: skill.id,
      reason: 'early-regeneration',
      exampleCount: examples.length,
    });
  } catch (error) {
    console.error('[EARLY_EVAL_REGEN] Error during regeneration:', error);
    // Release lock on error
    try {
      await userDataStorageConnector.updateSkill(c, skill.id, {
        evaluation_lock_acquired_at: null,
      });
    } catch (unlockError) {
      console.error('[EARLY_EVAL_REGEN] Failed to release lock:', unlockError);
    }
    // Don't throw - we don't want to break the request flow
  }
}