* Fetch weekly token usage data from PostHog * * Queries PostHog for daily token usage per model over the last 7 days * and returns structured time-series data ready for charting
()
| 129 | * and returns structured time-series data ready for charting |
| 130 | */ |
| 131 | async function fetchWeeklyTokenUsage(): Promise<ModelChartDataUpdates> { |
| 132 | console.log('[sync-internal-data] Fetching weekly token usage data from PostHog...'); |
| 133 | |
| 134 | // Query PostHog for daily token usage by model over the last 7 days |
| 135 | // Explicitly select columns to avoid confusion from column order changes |
| 136 | const response = await posthogQuery( |
| 137 | 'sync-model-stats-weekly-tokens', |
| 138 | ` |
| 139 | select date, model, tokens |
| 140 | from models_usage_by_week |
| 141 | limit 100000 |
| 142 | ` |
| 143 | ); |
| 144 | |
| 145 | if (response.status === 'error') { |
| 146 | console.error('[sync-internal-data] PostHog weekly token query failed:', response.error); |
| 147 | throw new Error(`PostHog query failed: ${JSON.stringify(response.error)}`); |
| 148 | } |
| 149 | |
| 150 | const results = (response.body.results ?? []) as [string, string, number][]; // [date, model, tokens] |
| 151 | console.log(`[sync-internal-data] Received ${results.length} weekly token results from PostHog`); |
| 152 | |
| 153 | console.log('[sync-internal-data] Sample weekly token results:', results.slice(0, 10)); |
| 154 | |
| 155 | // Group results by model |
| 156 | const modelWeeklyData: Record<string, WeeklyTokenDataPoint[]> = {}; |
| 157 | |
| 158 | for (const [date, model, tokens] of results) { |
| 159 | if (!modelWeeklyData[model]) { |
| 160 | modelWeeklyData[model] = []; |
| 161 | } |
| 162 | modelWeeklyData[model].push({ date, tokens }); |
| 163 | } |
| 164 | |
| 165 | console.log( |
| 166 | `[sync-internal-data] Processed weekly token data for ${Object.keys(modelWeeklyData).length} unique models` |
| 167 | ); |
| 168 | |
| 169 | // Build the chart data updates object |
| 170 | const lastUpdated = new Date().toISOString(); |
| 171 | const chartDataUpdates: ModelChartDataUpdates = {}; |
| 172 | |
| 173 | for (const [normalizedModelName, dataPoints] of Object.entries(modelWeeklyData)) { |
| 174 | // Sort data points by date to ensure chronological order |
| 175 | dataPoints.sort((a, b) => a.date.localeCompare(b.date)); |
| 176 | |
| 177 | chartDataUpdates[normalizedModelName] = { |
| 178 | weeklyTokenUsage: { |
| 179 | dataPoints, |
| 180 | lastUpdated, |
| 181 | }, |
| 182 | }; |
| 183 | } |
| 184 | |
| 185 | return chartDataUpdates; |
| 186 | } |
| 187 | |
| 188 | /** |
no test coverage detected