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 | 1x 1x 1x 1x 1x 1x | import type {
LogsStorageConnector,
UserDataStorageConnector,
} from '@api/types/connector';
import type { AppContext } from '@api/types/hono';
import { calculateDistance, kMeansClustering } from '@api/utils/math';
import { emitSSEEvent } from '@api/utils/sse-event-manager';
import { error, info, success } from '@shared/console-logging';
import { FunctionName } from '@shared/types/api/request';
import type { Log, Skill } from '@shared/types/data';
import { SkillEventType } from '@shared/types/data/skill-event';
import type { SkillOptimizationClusterCreateParams } from '@shared/types/data/skill-optimization-cluster';
import type { ClusterResult } from '@shared/utils/math';
function extractEmbeddings(logs: Log[]): number[][] {
// Filter logs to only include those with embeddings
const logsWithEmbeddings = logs.filter(
(log) => log.embedding !== null && log.embedding.length > 0,
);
if (logsWithEmbeddings.length === 0) {
throw new Error(`[OPTIMIZER] No logs with embeddings found`);
}
// Extract embeddings
const embeddings = logsWithEmbeddings.map((log) => log.embedding as number[]);
// Validate that all embeddings have the same dimension
const firstDimension = embeddings[0].length;
if (!embeddings.every((embedding) => embedding.length === firstDimension)) {
throw new Error(`[OPTIMIZER] Inconsistent embedding dimensions`);
}
return embeddings;
}
export function getClusters(skill: Skill, logs: Log[]): ClusterResult | null {
const numberOfClusters = skill.configuration_count;
try {
const embeddings = extractEmbeddings(logs);
const embeddingsLogMap = new Map<number[], Log>();
embeddings.forEach((embedding, index) => {
embeddingsLogMap.set(embedding, logs[index]);
});
const result = kMeansClustering(embeddings, numberOfClusters);
return result;
} catch (e) {
error(`[OPTIMIZER] Error clustering logs for skill ${skill.id}:`, e);
return null;
}
}
export async function autoClusterSkill(
c: AppContext,
functionName: FunctionName,
userDataStorageConnector: UserDataStorageConnector,
logsStorageConnector: LogsStorageConnector,
skill: Skill,
) {
// Only attempt to optimize for specific endpoints
if (
!(
functionName === FunctionName.CHAT_COMPLETE ||
functionName === FunctionName.STREAM_CHAT_COMPLETE ||
functionName === FunctionName.CREATE_MODEL_RESPONSE
)
) {
return;
}
const interval = skill.clustering_interval;
const logs = await logsStorageConnector.getLogs(c, {
skill_id: skill.id,
after: skill.last_clustering_log_start_time ?? undefined,
// Since the embedding is not null, we can assume that the logs are valid
// and are for one of the allowed function names
embedding_not_null: true,
});
// Automatically cluster logs if there are enough logs
if (logs.length >= interval) {
info(
`[OPTIMIZER] Starting reclustering for skill ${skill.id} (${skill.name}) with ${logs.length} logs...`,
);
const startTime = Date.now();
try {
// Try to atomically acquire the reclustering lock
// This prevents race conditions where multiple requests try to recluster simultaneously
const lockThresholdMs = 60000; // 60 seconds
const lockedSkill =
await userDataStorageConnector.tryAcquireReclusteringLock(
c,
skill.id,
lockThresholdMs,
);
if (!lockedSkill) {
// Lock was not acquired - another request is already reclustering or did so recently
const currentTime = Date.now();
const lastClusteringTime = skill.last_clustering_at
? new Date(skill.last_clustering_at).getTime()
: 0;
info(
`[OPTIMIZER] Reclustering already in progress for skill ${skill.id} (last clustered ${Math.floor((currentTime - lastClusteringTime) / 1000)}s ago). Skipping.`,
);
return;
}
// Lock acquired successfully - update in-memory skill object
skill.last_clustering_at = lockedSkill.last_clustering_at;
const clusterStates =
await userDataStorageConnector.getSkillOptimizationClusters(c, {
skill_id: skill.id,
});
const clusterResult = getClusters(skill, logs);
if (!clusterResult) {
error(`[OPTIMIZER] Failed to cluster logs for skill ${skill.id}`);
return;
}
const newCentroids = clusterResult.centroids;
// Match old cluster centers to new cluster centers based on proximity
// Each old cluster gets matched to the closest new cluster
const used = new Set<number>();
const matches: Array<{ clusterStateId: string; newCenter: number[] }> =
[];
// Create new clusters
if (clusterStates.length === 0) {
const clusterParams: SkillOptimizationClusterCreateParams[] =
newCentroids.map((centroid, index) => ({
agent_id: skill.agent_id,
skill_id: skill.id,
name: `${index + 1}`,
total_steps: 0,
observability_total_requests: 0,
centroid,
}));
await userDataStorageConnector.createSkillOptimizationClusters(
c,
clusterParams,
);
// Emit SSE event for cluster updates
emitSSEEvent('skill-optimization:cluster-updated', {
skillId: skill.id,
});
}
// Update existing clusters
else {
for (const clusterState of clusterStates) {
let minDistance = Infinity;
let bestMatchIndex = -1;
// Find the closest unused new cluster center
for (let i = 0; i < newCentroids.length; i++) {
if (used.has(i)) continue;
const distance = calculateDistance(
clusterState.centroid,
newCentroids[i],
);
if (distance < minDistance) {
minDistance = distance;
bestMatchIndex = i;
}
}
if (bestMatchIndex !== -1) {
used.add(bestMatchIndex);
matches.push({
clusterStateId: clusterState.id,
newCenter: newCentroids[bestMatchIndex],
});
}
}
// Update all matched cluster states
await Promise.all(
matches.map((match) =>
userDataStorageConnector.updateSkillOptimizationCluster(
c,
match.clusterStateId,
{
centroid: match.newCenter,
},
),
),
);
// Emit SSE event for cluster updates
emitSSEEvent('skill-optimization:cluster-updated', {
skillId: skill.id,
});
}
// Logs are ordered by start_time desc, so logs[0] is the most recent
const mostRecentLog = logs[0];
// Update clustering state (last_clustering_at was already set as a lock)
await userDataStorageConnector.updateSkill(c, skill.id, {
last_clustering_log_start_time: mostRecentLog.start_time,
});
// Create reclustering event
await userDataStorageConnector.createSkillEvent(c, {
agent_id: skill.agent_id,
skill_id: skill.id,
cluster_id: null, // Skill-wide event
event_type: SkillEventType.CLUSTERS_UPDATED,
metadata: {
cluster_count:
clusterStates.length > 0
? clusterStates.length
: skill.configuration_count,
log_count: logs.length,
},
});
// Update the in-memory skill object (last_clustering_at already set when lock was acquired)
skill.last_clustering_log_start_time = mostRecentLog.start_time;
const duration = Date.now() - startTime;
success(
`[OPTIMIZER] Reclustering completed for skill ${skill.id} (${skill.name}) in ${duration}ms. Updated ${clusterStates.length > 0 ? clusterStates.length : skill.configuration_count} clusters.`,
);
} catch (e) {
const duration = Date.now() - startTime;
error(
`[OPTIMIZER] Error during reclustering for skill ${skill.id} after ${duration}ms:`,
e,
);
}
}
}
|