All files / api/src/optimization skill-optimizations.ts

55.45% Statements 117/211
56% Branches 14/25
100% Functions 1/1
55.45% Lines 117/211

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 2941x 1x 1x 1x                               4x 4x 4x 4x 4x 4x 4x 4x 4x   4x       4x     4x 4x     4x 4x   4x                     4x                                                                                                         4x       4x 4x 4x     4x       4x                     4x 4x 4x 4x 4x       4x 8x 8x 8x 8x 4x   4x   4x   4x         4x                     4x 4x                                                   4x   4x 4x 4x 4x 4x 4x     4x 4x 16x 4x 4x 16x 16x     4x 4x 4x   4x 8x   8x   8x   8x 12x 48x 48x 48x 48x 48x     48x   48x   16x 16x 16x 16x 16x 16x 16x   16x 16x 16x 16x 16x 16x 48x   32x 8x 8x 32x 32x 32x     32x 32x 32x 32x 32x 32x 32x 32x 48x 12x 8x     4x 3x 3x 3x 3x 3x 3x     4x 16x           16x   4x 4x  
import { generateExampleConversations } from '@api/middlewares/optimizer/system-prompt';
import { BaseArmsParams } from '@api/optimization/base-arms';
import { regenerateEvaluationsWithExamples } from '@api/optimization/utils/evaluations';
import {
  generateSeedSystemPromptForSkill,
  generateSeedSystemPromptWithContext,
} from '@api/optimization/utils/system-prompt';
import type {
  EvaluationMethodConnector,
  LogsStorageConnector,
  UserDataStorageConnector,
} from '@api/types/connector';
import type { AppContext } from '@api/types/hono';
import type {
  SkillOptimizationArmCreateParams,
  SkillOptimizationArmParams,
} from '@shared/types/data/skill-optimization-arm';
import type { EvaluationMethodName } from '@shared/types/evaluations';
 
export async function handleGenerateArms(
  c: AppContext,
  userStorageConnector: UserDataStorageConnector,
  skillId: string,
  clusterId?: string, // Optional: if provided, only regenerate arms for this cluster
) {
  const skills = await userStorageConnector.getSkills(c, {
    id: skillId,
  });
 
  if (skills.length === 0) {
    return c.json({ error: 'Skill not found' }, 404);
  }
 
  const skill = skills[0];
 
  // Get logs storage connector and evaluation connectors from context
  const logsStorageConnector = c.get('logs_storage_connector');
  const evaluationConnectorsMap = c.get('evaluation_connectors_map');
 
  // Check if we have at least 5 logs with embeddings to use context-aware generation
  let hasEnoughLogsForContext = false;
  let logs: Awaited<ReturnType<LogsStorageConnector['getLogs']>> = [];
 
  if (logsStorageConnector) {
    logs = await logsStorageConnector.getLogs(c, {
      skill_id: skill.id,
      embedding_not_null: true,
      limit: 5,
    });
    hasEnoughLogsForContext = logs.length >= 5;
  }
 
  // If we have enough logs, regenerate evaluations with context before creating arms
  // Only do this for skill-wide regeneration (not cluster-specific)
  if (hasEnoughLogsForContext && !clusterId) {
    const exampleLogs = logs.slice(0, 5);
    const examples = generateExampleConversations(exampleLogs);
 
    // Get existing evaluations
    const existingEvaluations =
      await userStorageConnector.getSkillOptimizationEvaluations(c, {
        skill_id: skill.id,
      });
 
    if (existingEvaluations.length > 0 && examples.length > 0) {
      // Get agent description for context
      const agents = await userStorageConnector.getAgents(c, {
        id: skill.agent_id,
      });
 
      if (agents.length > 0) {
        const agent = agents[0];
 
        // Extract existing evaluation methods
        const existingMethods = existingEvaluations.map(
          (e) => e.evaluation_method,
        );
 
        // Regenerate evaluations with context
        const regeneratedEvaluationParams =
          await regenerateEvaluationsWithExamples(
            c,
            skill,
            agent.description,
            examples,
            evaluationConnectorsMap as Record<
              string,
              EvaluationMethodConnector
            >,
            existingMethods as EvaluationMethodName[],
            userStorageConnector,
          );
 
        // Delete old evaluations and create new ones
        await userStorageConnector.deleteSkillOptimizationEvaluationsForSkill(
          c,
          skill.id,
        );
        await userStorageConnector.createSkillOptimizationEvaluations(
          c,
          regeneratedEvaluationParams,
        );
      }
    }
  }
 
  // Get existing arms - either for specific cluster or entire skill
  const existingArms = clusterId
    ? await userStorageConnector.getSkillOptimizationArms(c, {
        cluster_id: clusterId,
      })
    : await userStorageConnector.getSkillOptimizationArms(c, {
        skill_id: skill.id,
      });
 
  // Reset cluster step count - either specific cluster or all clusters
  let clusters: Awaited<
    ReturnType<UserDataStorageConnector['getSkillOptimizationClusters']>
  >;
 
  if (clusterId) {
    clusters = await userStorageConnector.getSkillOptimizationClusters(c, {
      id: clusterId,
    });
    if (clusters.length === 0) {
      return c.json({ error: 'Cluster not found' }, 404);
    }
    // Only reset the specific cluster (already done in caller, but ensure consistency)
    await userStorageConnector.updateSkillOptimizationCluster(c, clusterId, {
      total_steps: 0,
    });
  } else {
    clusters = await userStorageConnector.getSkillOptimizationClusters(c, {
      skill_id: skill.id,
    });
    if (!clusters) {
      return c.json({ error: 'Clusters not found' }, 404);
    }
    // Reset all clusters
    for (const cluster of clusters) {
      await userStorageConnector.updateSkillOptimizationCluster(c, cluster.id, {
        total_steps: 0,
      });
    }
  }
 
  const skillModels = await userStorageConnector.getSkillModels(c, skill.id);
  // Use the clusters we already fetched (either specific one or all)
  const skillClusters = clusters;
 
  if (!skillModels || !skillClusters) {
    return c.json({ error: 'Skill models or clusters not found' }, 404);
  }
 
  // We don't need to create arms if there are no models or clusters
  if (skillModels.length === 0 || skillClusters.length === 0) {
    // Delete existing arms if any
    for (const arm of existingArms) {
      await userStorageConnector.deleteSkillOptimizationArmStats(c, {
        arm_id: arm.id,
      });
    }
    return c.json({ updatedArms: [] }, 200);
  }
 
  // Generate system prompt based on whether we have enough context
  let systemPrompt: string;
  if (hasEnoughLogsForContext) {
    const exampleLogs = logs.slice(0, 5);
    const examples = generateExampleConversations(exampleLogs);
 
    // Get agent description for context
    const agents = await userStorageConnector.getAgents(c, {
      id: skill.agent_id,
    });
 
    if (agents.length > 0 && examples.length > 0) {
      const agent = agents[0];
      systemPrompt = await generateSeedSystemPromptWithContext(
        c,
        agent.description,
        skill.description,
        examples,
        userStorageConnector,
      );
    } else {
      // Fallback to no-context generation
      systemPrompt = await generateSeedSystemPromptForSkill(
        c,
        skill,
        userStorageConnector,
      );
    }
  } else {
    // Use no-context generation for initial setup
    systemPrompt = await generateSeedSystemPromptForSkill(
      c,
      skill,
      userStorageConnector,
    );
  }
 
  // Build a map of existing arms by cluster_id -> list of arms (not just IDs)
  const existingArmsByCluster = new Map<string, (typeof existingArms)[0][]>();
  for (const arm of existingArms) {
    if (!existingArmsByCluster.has(arm.cluster_id)) {
      existingArmsByCluster.set(arm.cluster_id, []);
    }
    existingArmsByCluster.get(arm.cluster_id)!.push(arm);
  }
 
  // Process each cluster independently to ensure arms are named 1-n per cluster
  const updatedArms: string[] = [];
  const armsToCreate: SkillOptimizationArmCreateParams[] = [];
  const matchedArmIds = new Set<string>();
 
  for (const cluster of skillClusters) {
    const availableArms = existingArmsByCluster.get(cluster.id) || [];
    // Track used names in this cluster to avoid conflicts
    const usedNames = new Set<string>();
    // Track next available name counter for new arms
    let nextNameCounter = 1;
 
    for (const model of skillModels) {
      for (const baseArm of BaseArmsParams) {
        const armParams: SkillOptimizationArmParams = {
          ...baseArm,
          model_id: model.id,
          system_prompt: systemPrompt,
        };
 
        // Try to reuse an existing arm for this cluster
        const existingArm = availableArms.shift();
 
        if (existingArm) {
          // Update existing arm in-place, keeping its original name
          await userStorageConnector.updateSkillOptimizationArm(
            c,
            existingArm.id,
            {
              params: armParams,
            },
          );
          // Delete arm stats to reset performance history
          await userStorageConnector.deleteSkillOptimizationArmStats(c, {
            arm_id: existingArm.id,
          });
          updatedArms.push(existingArm.id);
          matchedArmIds.add(existingArm.id);
          usedNames.add(existingArm.name);
        } else {
          // Find next available name that doesn't conflict with existing arms
          while (usedNames.has(`${nextNameCounter}`)) {
            nextNameCounter++;
          }
          const newName = `${nextNameCounter}`;
          usedNames.add(newName);
          nextNameCounter++;
 
          // Need to create new arm
          armsToCreate.push({
            agent_id: skill.agent_id,
            skill_id: skill.id,
            cluster_id: cluster.id,
            name: newName,
            params: armParams,
          });
        }
      }
    }
  }
 
  // Create any new arms needed
  if (armsToCreate.length > 0) {
    const createdArms = await userStorageConnector.createSkillOptimizationArms(
      c,
      armsToCreate,
    );
    updatedArms.push(...createdArms.map((a) => a.id));
  }
 
  // Delete any orphaned arms that don't match expected structure
  for (const arm of existingArms) {
    if (!matchedArmIds.has(arm.id)) {
      await userStorageConnector.deleteSkillOptimizationArmStats(c, {
        arm_id: arm.id,
      });
      await userStorageConnector.deleteSkillOptimizationArm(c, arm.id);
    }
  }
 
  return c.json({ updatedArms }, 200);
}