@mupt-ai/dari-gateway 1.0.324 → 1.0.326
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/activity/conversation_detail.d.ts +2 -0
- package/dist/activity/conversation_detail.js +259 -0
- package/dist/activity/conversation_records.d.ts +129 -0
- package/dist/activity/conversation_records.js +318 -0
- package/dist/activity/conversations.d.ts +11 -0
- package/dist/activity/conversations.js +198 -0
- package/dist/activity/core.d.ts +13 -0
- package/dist/activity/core.js +613 -0
- package/dist/activity/filters.d.ts +71 -0
- package/dist/activity/filters.js +169 -0
- package/dist/activity/http.d.ts +37 -0
- package/dist/activity/http.js +109 -0
- package/dist/activity/params.d.ts +40 -0
- package/dist/activity/params.js +130 -0
- package/dist/activity/people.d.ts +3 -0
- package/dist/activity/people.js +413 -0
- package/dist/activity/routes.d.ts +2 -0
- package/dist/activity/routes.js +23 -0
- package/dist/activity/savings.d.ts +12 -0
- package/dist/activity/savings.js +102 -0
- package/dist/activity/shared.d.ts +15 -0
- package/dist/activity/shared.js +26 -0
- package/dist/activity/sql.d.ts +52 -0
- package/dist/activity/sql.js +124 -0
- package/dist/activity/tool_exchanges.d.ts +21 -0
- package/dist/activity/tool_exchanges.js +309 -0
- package/dist/activity/tool_skill_activity.d.ts +128 -0
- package/dist/activity/tool_skill_activity.js +280 -0
- package/dist/activity/tool_skill_identities.d.ts +25 -0
- package/dist/activity/tool_skill_identities.js +162 -0
- package/dist/activity/tools.d.ts +4 -0
- package/dist/activity/tools.js +68 -0
- package/dist/activity/values.d.ts +45 -0
- package/dist/activity/values.js +178 -0
- package/dist/context/interaction_fingerprint.js +11 -3
- package/dist/context/interaction_fingerprint_format.d.ts +2 -1
- package/dist/context/interaction_fingerprint_format.js +2 -0
- package/dist/http/handler.d.ts +2 -1
- package/dist/http/handler.js +6 -1
- package/dist/interaction/types.d.ts +17 -2
- package/dist/interaction/types.js +11 -0
- package/dist/link/endpoints.js +44 -53
- package/dist/platform/platform.d.ts +12 -0
- package/dist/protocol/input/anthropic_messages.js +63 -48
- package/dist/providers/pi.js +22 -3
- package/dist/providers/pi_context.js +15 -5
- package/dist/runtime/claude_code/auxiliary_routing.js +34 -3
- package/dist/runtime/prepare_routed_completion.d.ts +2 -0
- package/dist/runtime/prepare_routed_completion.js +42 -1
- package/dist/self_host/activity_store.d.ts +35 -0
- package/dist/self_host/activity_store.js +373 -0
- package/dist/self_host/main.d.ts +3 -2
- package/dist/self_host/main.js +8 -3
- package/dist/self_host/platform.d.ts +4 -2
- package/dist/self_host/platform.js +35 -3
- package/package.json +2 -2
- package/src/activity/conversation_detail.ts +283 -0
- package/src/activity/conversation_records.ts +403 -0
- package/src/activity/conversations.ts +218 -0
- package/src/activity/core.ts +678 -0
- package/src/activity/filters.ts +206 -0
- package/src/activity/http.ts +140 -0
- package/src/activity/params.ts +138 -0
- package/src/activity/people.ts +471 -0
- package/src/activity/routes.ts +26 -0
- package/src/activity/savings.ts +121 -0
- package/src/activity/shared.ts +36 -0
- package/src/activity/sql.ts +139 -0
- package/src/activity/tool_exchanges.ts +340 -0
- package/src/activity/tool_skill_activity.ts +314 -0
- package/src/activity/tool_skill_identities.ts +196 -0
- package/src/activity/tools.ts +76 -0
- package/src/activity/values.ts +197 -0
- package/src/context/interaction_fingerprint.ts +9 -3
- package/src/context/interaction_fingerprint_format.ts +6 -1
- package/src/http/handler.ts +5 -1
- package/src/interaction/types.ts +21 -11
- package/src/link/endpoints.ts +44 -54
- package/src/platform/platform.ts +12 -0
- package/src/protocol/input/anthropic_messages.ts +66 -53
- package/src/providers/pi.ts +22 -3
- package/src/providers/pi_context.ts +14 -7
- package/src/runtime/claude_code/auxiliary_routing.ts +33 -2
- package/src/runtime/prepare_routed_completion.ts +60 -2
- package/src/self_host/activity_store.ts +423 -0
- package/src/self_host/main.ts +17 -3
- package/src/self_host/platform.ts +38 -3
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
/* The Activity overview, series, routers, models, and filter options. */
|
|
2
|
+
import { baseCriteria, bucketIndex, bucketStart, criteria, identityCriteria, MODEL, readActivityQuery, readSourceScope, SELECTOR_UNRESOLVED_MODEL, sourceProtocols, validatedBucketFilters, validatedFilters, } from "./filters.js";
|
|
3
|
+
import { loadRouterSavings, loadSavings, routeKey } from "./savings.js";
|
|
4
|
+
import { and, sql } from "./sql.js";
|
|
5
|
+
import { CONVERSATION_ID, THINKING_LEVEL, thinkingLevelValue } from "./shared.js";
|
|
6
|
+
import { decimalText, formatInstant, parseDecimal, readInstant, readInt, readOptionalString, sumDecimalText, } from "./values.js";
|
|
7
|
+
const MAX_MODEL_TRANSITIONS = 200;
|
|
8
|
+
/** Read the filters, then admit the caller, then validate, as the API orders its checks. */
|
|
9
|
+
function readFilters(request, bucketed) {
|
|
10
|
+
const bucketSeconds = bucketed ? request.params.int("bucket_seconds", { ge: 60 }) : 0;
|
|
11
|
+
const scope = readSourceScope(request.params);
|
|
12
|
+
const query = readActivityQuery(request.params);
|
|
13
|
+
request.params.done();
|
|
14
|
+
const protocols = sourceProtocols(scope);
|
|
15
|
+
const organizationId = request.admitted();
|
|
16
|
+
const filters = bucketed
|
|
17
|
+
? validatedBucketFilters(query, protocols, bucketSeconds)
|
|
18
|
+
: validatedFilters(query, protocols);
|
|
19
|
+
return { organizationId, filters };
|
|
20
|
+
}
|
|
21
|
+
/** Steps, tokens, and spend: the totals the grouped reads select. Read with `usage`. */
|
|
22
|
+
const USAGE = sql `
|
|
23
|
+
count(*) as model_steps,
|
|
24
|
+
coalesce(sum(r.provider_input_tokens), 0) as input_tokens,
|
|
25
|
+
coalesce(sum(r.provider_cache_read_tokens), 0) as cache_read_tokens,
|
|
26
|
+
coalesce(sum(r.provider_cache_write_tokens), 0) as cache_write_tokens,
|
|
27
|
+
coalesce(sum(r.provider_output_tokens), 0) as output_tokens,
|
|
28
|
+
coalesce(sum(r.provider_total_tokens), 0) as total_tokens,
|
|
29
|
+
cast(sum(r.provider_total_cost_usd) as text) as provider_spend,
|
|
30
|
+
count(*) filter (
|
|
31
|
+
where r.provider_pricing_known is true and r.selected_model is not null and r.selected_provider is not null
|
|
32
|
+
) as priced_steps,
|
|
33
|
+
count(*) filter (
|
|
34
|
+
where r.provider_pricing_known is false and r.selected_model is not null and r.selected_provider is not null
|
|
35
|
+
) as unpriced_steps`;
|
|
36
|
+
function usage(row) {
|
|
37
|
+
return {
|
|
38
|
+
model_steps: readInt(row.model_steps),
|
|
39
|
+
provider_input_tokens: readInt(row.input_tokens),
|
|
40
|
+
provider_cache_read_tokens: readInt(row.cache_read_tokens),
|
|
41
|
+
provider_cache_write_tokens: readInt(row.cache_write_tokens),
|
|
42
|
+
provider_output_tokens: readInt(row.output_tokens),
|
|
43
|
+
provider_total_tokens: readInt(row.total_tokens),
|
|
44
|
+
provider_spend_usd: decimalText(row.provider_spend),
|
|
45
|
+
priced_model_steps: readInt(row.priced_steps),
|
|
46
|
+
unpriced_model_steps: readInt(row.unpriced_steps),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function compareText(a, b) {
|
|
50
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
51
|
+
}
|
|
52
|
+
function ratio(numerator, denominator) {
|
|
53
|
+
return denominator === 0 ? 0 : numerator / denominator;
|
|
54
|
+
}
|
|
55
|
+
async function loadSeries(db, filters, where) {
|
|
56
|
+
const rows = await db.all(sql `
|
|
57
|
+
select
|
|
58
|
+
${bucketIndex(db, filters)} as bucket_index,
|
|
59
|
+
${MODEL} as model,
|
|
60
|
+
${THINKING_LEVEL} as thinking_level,
|
|
61
|
+
r.selected_provider as provider,
|
|
62
|
+
count(*) filter (where r.request_kind = 'user_message') as messages_sent,
|
|
63
|
+
${USAGE},
|
|
64
|
+
count(*) filter (where r.prefix_warm_tokens > 0) as predicted_warm,
|
|
65
|
+
count(*) filter (
|
|
66
|
+
where r.prefix_warm_tokens > 0 and coalesce(r.provider_cache_read_tokens, 0) = 0
|
|
67
|
+
) as predicted_warm_without_read
|
|
68
|
+
from routing_requests r
|
|
69
|
+
where ${where}
|
|
70
|
+
group by 1, 2, 3, 4
|
|
71
|
+
order by 1, 2, 3 nulls last, 4 nulls last`);
|
|
72
|
+
return rows.map((row) => ({
|
|
73
|
+
bucket_start: bucketStart(filters, row.bucket_index),
|
|
74
|
+
model: String(row.model),
|
|
75
|
+
thinking_level: thinkingLevelValue(row.thinking_level),
|
|
76
|
+
provider: readOptionalString(row.provider),
|
|
77
|
+
messages_sent: readInt(row.messages_sent),
|
|
78
|
+
...usage(row),
|
|
79
|
+
predicted_warm_requests: readInt(row.predicted_warm),
|
|
80
|
+
predicted_warm_without_cache_read: readInt(row.predicted_warm_without_read),
|
|
81
|
+
}));
|
|
82
|
+
}
|
|
83
|
+
function summary(series, savings) {
|
|
84
|
+
const total = (pick) => series.reduce((sum, point) => sum + pick(point), 0);
|
|
85
|
+
return {
|
|
86
|
+
messages_sent: total((p) => p.messages_sent),
|
|
87
|
+
model_steps: total((p) => p.model_steps),
|
|
88
|
+
provider_input_tokens: total((p) => p.provider_input_tokens),
|
|
89
|
+
provider_cache_read_tokens: total((p) => p.provider_cache_read_tokens),
|
|
90
|
+
provider_cache_write_tokens: total((p) => p.provider_cache_write_tokens),
|
|
91
|
+
provider_output_tokens: total((p) => p.provider_output_tokens),
|
|
92
|
+
provider_total_tokens: total((p) => p.provider_total_tokens),
|
|
93
|
+
provider_spend_usd: sumDecimalText(series.map((p) => p.provider_spend_usd)),
|
|
94
|
+
priced_model_steps: total((p) => p.priced_model_steps),
|
|
95
|
+
unpriced_model_steps: total((p) => p.unpriced_model_steps),
|
|
96
|
+
predicted_warm_requests: total((p) => p.predicted_warm_requests),
|
|
97
|
+
predicted_warm_without_cache_read: total((p) => p.predicted_warm_without_cache_read),
|
|
98
|
+
savings_vs_most_expensive_usd: savings,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** A series point as the API writes one: without the warm-prefix counts. */
|
|
102
|
+
function seriesPointBody(point) {
|
|
103
|
+
const { predicted_warm_requests: _warm, predicted_warm_without_cache_read: _cold, ...body } = point;
|
|
104
|
+
return body;
|
|
105
|
+
}
|
|
106
|
+
function modelMix(series) {
|
|
107
|
+
const totals = new Map();
|
|
108
|
+
for (const point of series) {
|
|
109
|
+
const key = JSON.stringify([point.model, point.thinking_level, point.provider]);
|
|
110
|
+
const entry = totals.get(key);
|
|
111
|
+
if (entry)
|
|
112
|
+
entry.model_steps += point.model_steps;
|
|
113
|
+
else
|
|
114
|
+
totals.set(key, { model: point.model, thinking_level: point.thinking_level, provider: point.provider, model_steps: point.model_steps });
|
|
115
|
+
}
|
|
116
|
+
// Stable, as Python's `sorted`: steps descending, then model.
|
|
117
|
+
return [...totals.values()].sort((a, b) => b.model_steps - a.model_steps || compareText(a.model, b.model));
|
|
118
|
+
}
|
|
119
|
+
async function loadApiKeys(db, where) {
|
|
120
|
+
// A key's person is named only when all its traffic is one person's.
|
|
121
|
+
const rows = await db.all(sql `
|
|
122
|
+
select
|
|
123
|
+
r.api_key_id,
|
|
124
|
+
k.label,
|
|
125
|
+
k.key_prefix,
|
|
126
|
+
case when count(distinct coalesce(r.attributed_user_id, '__unassigned__')) = 1
|
|
127
|
+
then max(r.attributed_user_id) end as assigned_user_id,
|
|
128
|
+
case when count(distinct coalesce(r.attributed_user_id, '__unassigned__')) = 1
|
|
129
|
+
then max(coalesce(u.display_name, u.email)) else 'Multiple People' end as assigned_user_name,
|
|
130
|
+
count(*) filter (where r.request_kind = 'user_message') as messages_sent,
|
|
131
|
+
count(*) as model_steps,
|
|
132
|
+
coalesce(sum(r.provider_total_tokens), 0) as total_tokens,
|
|
133
|
+
cast(sum(r.provider_total_cost_usd) as text) as provider_spend,
|
|
134
|
+
count(*) filter (
|
|
135
|
+
where r.provider_pricing_known is true and r.selected_model is not null and r.selected_provider is not null
|
|
136
|
+
) as priced_steps,
|
|
137
|
+
count(*) filter (
|
|
138
|
+
where r.provider_pricing_known is false and r.selected_model is not null and r.selected_provider is not null
|
|
139
|
+
) as unpriced_steps,
|
|
140
|
+
cast(max(r.received_at) as text) as latest_at
|
|
141
|
+
from routing_requests r
|
|
142
|
+
left join organization_api_keys k on k.id = r.api_key_id
|
|
143
|
+
left join users u on u.id = r.attributed_user_id
|
|
144
|
+
where ${where}
|
|
145
|
+
group by r.api_key_id, k.label, k.key_prefix
|
|
146
|
+
order by messages_sent desc, sum(r.provider_total_cost_usd) desc nulls last, r.api_key_id nulls last`);
|
|
147
|
+
return rows.map((row) => ({
|
|
148
|
+
api_key_id: readOptionalString(row.api_key_id),
|
|
149
|
+
label: readOptionalString(row.label) || "Unattributed",
|
|
150
|
+
key_prefix: readOptionalString(row.key_prefix),
|
|
151
|
+
assigned_user_id: readOptionalString(row.assigned_user_id),
|
|
152
|
+
assigned_user_name: readOptionalString(row.assigned_user_name),
|
|
153
|
+
messages_sent: readInt(row.messages_sent),
|
|
154
|
+
model_steps: readInt(row.model_steps),
|
|
155
|
+
provider_total_tokens: readInt(row.total_tokens),
|
|
156
|
+
provider_spend_usd: decimalText(row.provider_spend),
|
|
157
|
+
priced_model_steps: readInt(row.priced_steps),
|
|
158
|
+
unpriced_model_steps: readInt(row.unpriced_steps),
|
|
159
|
+
latest_at: formatInstant(readInstant(row.latest_at)),
|
|
160
|
+
}));
|
|
161
|
+
}
|
|
162
|
+
async function loadKeySources(db, where) {
|
|
163
|
+
const rows = await db.all(sql `
|
|
164
|
+
select
|
|
165
|
+
r.provider_key_source as key_source,
|
|
166
|
+
${USAGE}
|
|
167
|
+
from routing_requests r
|
|
168
|
+
where ${where}
|
|
169
|
+
group by r.provider_key_source
|
|
170
|
+
order by sum(r.provider_total_cost_usd) desc nulls last, r.provider_key_source nulls last`);
|
|
171
|
+
return rows.map((row) => ({ key_source: readOptionalString(row.key_source), ...usage(row) }));
|
|
172
|
+
}
|
|
173
|
+
export const series = async (request) => {
|
|
174
|
+
const { organizationId, filters } = readFilters(request, true);
|
|
175
|
+
const points = await loadSeries(request.db, filters, criteria(request.db, organizationId, filters));
|
|
176
|
+
return {
|
|
177
|
+
from_at: formatInstant(filters.start),
|
|
178
|
+
to_at: formatInstant(filters.end),
|
|
179
|
+
bucket_seconds: filters.bucketSeconds,
|
|
180
|
+
summary: summary(points, null),
|
|
181
|
+
series: points.map(seriesPointBody),
|
|
182
|
+
};
|
|
183
|
+
};
|
|
184
|
+
export const overview = async (request) => {
|
|
185
|
+
const { organizationId, filters } = readFilters(request, true);
|
|
186
|
+
const db = request.db;
|
|
187
|
+
const where = criteria(db, organizationId, filters);
|
|
188
|
+
const points = await loadSeries(db, filters, where);
|
|
189
|
+
const savings = await loadSavings(db, where);
|
|
190
|
+
return {
|
|
191
|
+
from_at: formatInstant(filters.start),
|
|
192
|
+
to_at: formatInstant(filters.end),
|
|
193
|
+
bucket_seconds: filters.bucketSeconds,
|
|
194
|
+
summary: summary(points, savings.total),
|
|
195
|
+
series: points.map(seriesPointBody),
|
|
196
|
+
model_mix: modelMix(points),
|
|
197
|
+
api_keys: await loadApiKeys(db, where),
|
|
198
|
+
key_sources: await loadKeySources(db, where),
|
|
199
|
+
};
|
|
200
|
+
};
|
|
201
|
+
/* Routers. */
|
|
202
|
+
export const routers = async (request) => {
|
|
203
|
+
const { organizationId, filters } = readFilters(request, true);
|
|
204
|
+
const db = request.db;
|
|
205
|
+
const where = criteria(db, organizationId, filters);
|
|
206
|
+
const summaries = await db.all(sql `
|
|
207
|
+
select
|
|
208
|
+
r.router_id,
|
|
209
|
+
count(*) filter (where r.status = 'completed') as completed,
|
|
210
|
+
count(*) filter (where r.status = 'provider_error') as provider_error,
|
|
211
|
+
count(*) filter (where r.status = 'selector_error') as selector_error,
|
|
212
|
+
count(*) filter (where r.status = 'aborted') as aborted,
|
|
213
|
+
cast(sum(r.provider_total_cost_usd) as text) as provider_spend
|
|
214
|
+
from routing_requests r
|
|
215
|
+
where ${where}
|
|
216
|
+
and r.router_id is not null
|
|
217
|
+
group by r.router_id
|
|
218
|
+
order by r.router_id`);
|
|
219
|
+
const savings = await loadRouterSavings(db, where);
|
|
220
|
+
const seriesRows = await db.all(sql `
|
|
221
|
+
select
|
|
222
|
+
r.router_id,
|
|
223
|
+
${bucketIndex(db, filters)} as bucket_index,
|
|
224
|
+
count(*) filter (where r.request_kind = 'user_message') as messages_sent
|
|
225
|
+
from routing_requests r
|
|
226
|
+
where ${where}
|
|
227
|
+
and r.router_id is not null
|
|
228
|
+
group by 1, 2
|
|
229
|
+
order by 1, 2`);
|
|
230
|
+
const seriesByRouter = new Map();
|
|
231
|
+
for (const row of seriesRows) {
|
|
232
|
+
const routerId = String(row.router_id);
|
|
233
|
+
const points = seriesByRouter.get(routerId) ?? [];
|
|
234
|
+
points.push({ bucket_start: bucketStart(filters, row.bucket_index), messages_sent: readInt(row.messages_sent) });
|
|
235
|
+
seriesByRouter.set(routerId, points);
|
|
236
|
+
}
|
|
237
|
+
return {
|
|
238
|
+
from_at: formatInstant(filters.start),
|
|
239
|
+
to_at: formatInstant(filters.end),
|
|
240
|
+
bucket_seconds: filters.bucketSeconds,
|
|
241
|
+
routers: summaries.map((row) => {
|
|
242
|
+
const routerId = String(row.router_id);
|
|
243
|
+
const points = seriesByRouter.get(routerId) ?? [];
|
|
244
|
+
return {
|
|
245
|
+
router_id: routerId,
|
|
246
|
+
messages_sent: points.reduce((sum, point) => sum + point.messages_sent, 0),
|
|
247
|
+
completed_requests: readInt(row.completed),
|
|
248
|
+
provider_error_requests: readInt(row.provider_error),
|
|
249
|
+
selector_error_requests: readInt(row.selector_error),
|
|
250
|
+
aborted_requests: readInt(row.aborted),
|
|
251
|
+
provider_spend_usd: decimalText(row.provider_spend),
|
|
252
|
+
savings_vs_most_expensive_usd: savings.get(routerId) ?? null,
|
|
253
|
+
series: points,
|
|
254
|
+
};
|
|
255
|
+
}),
|
|
256
|
+
};
|
|
257
|
+
};
|
|
258
|
+
/* Models. */
|
|
259
|
+
/** The p95 provider latency per model, thinking level, and provider (`percentile_disc(0.95)`). */
|
|
260
|
+
async function loadLatencyP95(db, where) {
|
|
261
|
+
const rows = await db.all(sql `
|
|
262
|
+
select
|
|
263
|
+
${MODEL} as model,
|
|
264
|
+
${THINKING_LEVEL} as thinking_level,
|
|
265
|
+
r.selected_provider as provider,
|
|
266
|
+
r.provider_latency_ms as latency
|
|
267
|
+
from routing_requests r
|
|
268
|
+
where ${where}
|
|
269
|
+
and r.provider_latency_ms > 0`);
|
|
270
|
+
const grouped = new Map();
|
|
271
|
+
for (const row of rows) {
|
|
272
|
+
const key = JSON.stringify([String(row.model), thinkingLevelValue(row.thinking_level), readOptionalString(row.provider)]);
|
|
273
|
+
const values = grouped.get(key) ?? [];
|
|
274
|
+
values.push(readInt(row.latency));
|
|
275
|
+
grouped.set(key, values);
|
|
276
|
+
}
|
|
277
|
+
const p95 = new Map();
|
|
278
|
+
for (const [key, values] of grouped) {
|
|
279
|
+
values.sort((a, b) => a - b);
|
|
280
|
+
p95.set(key, values[Math.max(0, Math.ceil(values.length * 0.95) - 1)]);
|
|
281
|
+
}
|
|
282
|
+
return p95;
|
|
283
|
+
}
|
|
284
|
+
async function loadModelRows(db, where) {
|
|
285
|
+
const rows = await db.all(sql `
|
|
286
|
+
select
|
|
287
|
+
${MODEL} as model,
|
|
288
|
+
${THINKING_LEVEL} as thinking_level,
|
|
289
|
+
r.selected_provider as provider,
|
|
290
|
+
${USAGE},
|
|
291
|
+
count(*) filter (where r.status != 'completed') as non_completed_steps
|
|
292
|
+
from routing_requests r
|
|
293
|
+
where ${where}
|
|
294
|
+
group by 1, 2, 3
|
|
295
|
+
order by model_steps desc, 1, 2 nulls last, 3 nulls last`);
|
|
296
|
+
const latency = await loadLatencyP95(db, where);
|
|
297
|
+
return rows.map((row) => {
|
|
298
|
+
const model = String(row.model);
|
|
299
|
+
const thinkingLevel = thinkingLevelValue(row.thinking_level);
|
|
300
|
+
const provider = readOptionalString(row.provider);
|
|
301
|
+
const totals = usage(row);
|
|
302
|
+
const nonCompleted = readInt(row.non_completed_steps);
|
|
303
|
+
return {
|
|
304
|
+
model,
|
|
305
|
+
thinking_level: thinkingLevel,
|
|
306
|
+
provider,
|
|
307
|
+
...totals,
|
|
308
|
+
provider_latency_p95_ms: latency.get(JSON.stringify([model, thinkingLevel, provider])) ?? null,
|
|
309
|
+
non_completed_steps: nonCompleted,
|
|
310
|
+
savings_vs_most_expensive_usd: null,
|
|
311
|
+
provider_cost_per_step_usd: totals.provider_spend_usd === null || totals.model_steps === 0
|
|
312
|
+
? null
|
|
313
|
+
: divideFormat(parseDecimal(totals.provider_spend_usd), totals.model_steps),
|
|
314
|
+
non_completion_rate: ratio(nonCompleted, totals.model_steps),
|
|
315
|
+
};
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
/** The conversations with a step that reached a model. */
|
|
319
|
+
async function loadObservedConversations(db, where) {
|
|
320
|
+
const [row] = await db.all(sql `
|
|
321
|
+
select count(*) as count
|
|
322
|
+
from (
|
|
323
|
+
select distinct
|
|
324
|
+
r.router_id,
|
|
325
|
+
r.api_key_id,
|
|
326
|
+
r.attributed_user_id,
|
|
327
|
+
r.source_protocol,
|
|
328
|
+
${CONVERSATION_ID}
|
|
329
|
+
from routing_requests r
|
|
330
|
+
where ${where}
|
|
331
|
+
and ${CONVERSATION_ID} is not null
|
|
332
|
+
and r.selected_model is not null
|
|
333
|
+
and r.selected_provider is not null
|
|
334
|
+
) observed`);
|
|
335
|
+
return readInt(row?.count);
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Adjacent model, provider, or thinking-level changes within each
|
|
339
|
+
* conversation. Steps are ordered under the identity filters only; the
|
|
340
|
+
* model, provider, and status filters apply to the step switched to, and
|
|
341
|
+
* the key-source filter not at all.
|
|
342
|
+
*/
|
|
343
|
+
async function loadTransitions(db, organizationId, filters) {
|
|
344
|
+
const switchedTo = [];
|
|
345
|
+
if (filters.models.length > 0) {
|
|
346
|
+
const ids = filters.models.filter((model) => model !== SELECTOR_UNRESOLVED_MODEL);
|
|
347
|
+
switchedTo.push(ids.length > 0 ? sql `o.to_model in (${ids})` : sql `o.to_model is null`);
|
|
348
|
+
}
|
|
349
|
+
if (filters.provider)
|
|
350
|
+
switchedTo.push(sql `o.to_provider = ${filters.provider}`);
|
|
351
|
+
if (filters.status)
|
|
352
|
+
switchedTo.push(sql `o.to_status = ${filters.status}`);
|
|
353
|
+
const rows = await db.all(sql `
|
|
354
|
+
with ordered as (
|
|
355
|
+
select
|
|
356
|
+
r.router_id,
|
|
357
|
+
r.api_key_id,
|
|
358
|
+
r.attributed_user_id,
|
|
359
|
+
r.source_protocol,
|
|
360
|
+
${CONVERSATION_ID} as conversation_id,
|
|
361
|
+
r.selected_model as to_model,
|
|
362
|
+
${THINKING_LEVEL} as to_thinking_level,
|
|
363
|
+
r.selected_provider as to_provider,
|
|
364
|
+
r.request_kind as to_kind,
|
|
365
|
+
r.status as to_status,
|
|
366
|
+
lag(r.selected_model) over w as from_model,
|
|
367
|
+
lag(${THINKING_LEVEL}) over w as from_thinking_level,
|
|
368
|
+
lag(r.selected_provider) over w as from_provider
|
|
369
|
+
from routing_requests r
|
|
370
|
+
where ${baseCriteria(db, organizationId, filters)}
|
|
371
|
+
and ${identityCriteria(filters)}
|
|
372
|
+
and ${CONVERSATION_ID} is not null
|
|
373
|
+
and r.selected_model is not null
|
|
374
|
+
and r.selected_provider is not null
|
|
375
|
+
window w as (
|
|
376
|
+
partition by r.router_id, r.api_key_id, r.attributed_user_id, r.source_protocol, ${CONVERSATION_ID}
|
|
377
|
+
order by r.received_at, r.id
|
|
378
|
+
)
|
|
379
|
+
),
|
|
380
|
+
per_conversation as materialized (
|
|
381
|
+
select
|
|
382
|
+
o.from_model, o.from_thinking_level, o.from_provider,
|
|
383
|
+
o.to_model, o.to_thinking_level, o.to_provider,
|
|
384
|
+
o.router_id, o.api_key_id, o.attributed_user_id, o.source_protocol, o.conversation_id,
|
|
385
|
+
count(*) as occurrences,
|
|
386
|
+
count(*) filter (where o.to_kind = 'tool_continuation') as tool_continuations
|
|
387
|
+
from ordered o
|
|
388
|
+
where o.from_model is not null
|
|
389
|
+
and o.from_provider is not null
|
|
390
|
+
and (
|
|
391
|
+
o.from_model != o.to_model
|
|
392
|
+
or o.from_provider != o.to_provider
|
|
393
|
+
or o.from_thinking_level is distinct from o.to_thinking_level
|
|
394
|
+
)
|
|
395
|
+
and ${and(switchedTo)}
|
|
396
|
+
group by
|
|
397
|
+
o.from_model, o.from_thinking_level, o.from_provider,
|
|
398
|
+
o.to_model, o.to_thinking_level, o.to_provider,
|
|
399
|
+
o.router_id, o.api_key_id, o.attributed_user_id, o.source_protocol, o.conversation_id
|
|
400
|
+
),
|
|
401
|
+
grouped as (
|
|
402
|
+
select
|
|
403
|
+
t.from_model, t.from_thinking_level, t.from_provider,
|
|
404
|
+
t.to_model, t.to_thinking_level, t.to_provider,
|
|
405
|
+
sum(t.occurrences) as occurrences,
|
|
406
|
+
count(*) as conversations,
|
|
407
|
+
sum(t.tool_continuations) as tool_continuations
|
|
408
|
+
from per_conversation t
|
|
409
|
+
group by
|
|
410
|
+
t.from_model, t.from_thinking_level, t.from_provider,
|
|
411
|
+
t.to_model, t.to_thinking_level, t.to_provider
|
|
412
|
+
)
|
|
413
|
+
select
|
|
414
|
+
g.*,
|
|
415
|
+
sum(case when g.from_model = g.to_model and g.from_provider = g.to_provider
|
|
416
|
+
then 0 else g.occurrences end) over () as model_switches,
|
|
417
|
+
sum(case when g.from_model = g.to_model and g.from_provider = g.to_provider
|
|
418
|
+
then g.occurrences else 0 end) over () as thinking_level_switches,
|
|
419
|
+
sum(case when g.from_provider != g.to_provider then g.occurrences else 0 end) over () as cross_provider_switches,
|
|
420
|
+
(
|
|
421
|
+
select count(*)
|
|
422
|
+
from (
|
|
423
|
+
select distinct t.router_id, t.api_key_id, t.attributed_user_id, t.source_protocol, t.conversation_id
|
|
424
|
+
from per_conversation t
|
|
425
|
+
) switched
|
|
426
|
+
) as switched_conversations
|
|
427
|
+
from grouped g
|
|
428
|
+
order by g.occurrences desc, g.from_model, g.from_thinking_level nulls last, g.to_model, g.to_thinking_level nulls last
|
|
429
|
+
limit ${MAX_MODEL_TRANSITIONS}`);
|
|
430
|
+
const first = rows[0];
|
|
431
|
+
return {
|
|
432
|
+
modelSwitches: readInt(first?.model_switches),
|
|
433
|
+
thinkingLevelSwitches: readInt(first?.thinking_level_switches),
|
|
434
|
+
crossProviderSwitches: readInt(first?.cross_provider_switches),
|
|
435
|
+
switchedConversations: readInt(first?.switched_conversations),
|
|
436
|
+
transitions: rows.map((row) => ({
|
|
437
|
+
from_model: String(row.from_model),
|
|
438
|
+
from_thinking_level: thinkingLevelValue(row.from_thinking_level),
|
|
439
|
+
from_provider: String(row.from_provider),
|
|
440
|
+
to_model: String(row.to_model),
|
|
441
|
+
to_thinking_level: thinkingLevelValue(row.to_thinking_level),
|
|
442
|
+
to_provider: String(row.to_provider),
|
|
443
|
+
occurrences: readInt(row.occurrences),
|
|
444
|
+
conversations: readInt(row.conversations),
|
|
445
|
+
tool_continuations: readInt(row.tool_continuations),
|
|
446
|
+
})),
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
export const models = async (request) => {
|
|
450
|
+
const { organizationId, filters } = readFilters(request, false);
|
|
451
|
+
const db = request.db;
|
|
452
|
+
const where = criteria(db, organizationId, filters);
|
|
453
|
+
const modelRows = await loadModelRows(db, where);
|
|
454
|
+
const switches = await loadTransitions(db, organizationId, filters);
|
|
455
|
+
const savings = await loadSavings(db, where);
|
|
456
|
+
for (const model of modelRows) {
|
|
457
|
+
if (model.provider !== null) {
|
|
458
|
+
model.savings_vs_most_expensive_usd = savings.byModel.get(routeKey(model.model, model.thinking_level, model.provider)) ?? null;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
const observed = await loadObservedConversations(db, where);
|
|
462
|
+
const totalSwitches = switches.modelSwitches + switches.thinkingLevelSwitches;
|
|
463
|
+
const transitions = switches.transitions.map((item) => ({ ...item, switch_share: ratio(item.occurrences, totalSwitches) }));
|
|
464
|
+
return {
|
|
465
|
+
from_at: formatInstant(filters.start),
|
|
466
|
+
to_at: formatInstant(filters.end),
|
|
467
|
+
summary: {
|
|
468
|
+
model_steps: modelRows.reduce((sum, model) => sum + model.model_steps, 0),
|
|
469
|
+
observed_conversations: observed,
|
|
470
|
+
switched_conversations: switches.switchedConversations,
|
|
471
|
+
model_switches: switches.modelSwitches,
|
|
472
|
+
thinking_level_switches: switches.thinkingLevelSwitches,
|
|
473
|
+
cross_provider_switches: switches.crossProviderSwitches,
|
|
474
|
+
savings_vs_most_expensive_usd: savings.total,
|
|
475
|
+
switched_conversation_rate: ratio(switches.switchedConversations, observed),
|
|
476
|
+
cross_provider_switch_rate: ratio(switches.crossProviderSwitches, switches.modelSwitches),
|
|
477
|
+
},
|
|
478
|
+
models: modelRows,
|
|
479
|
+
transitions,
|
|
480
|
+
transitions_truncated: transitions.reduce((sum, item) => sum + item.occurrences, 0) < totalSwitches,
|
|
481
|
+
};
|
|
482
|
+
};
|
|
483
|
+
const PRECISION = 28;
|
|
484
|
+
/**
|
|
485
|
+
* Python's `format(Decimal(value) / divisor, "f")` under the default context:
|
|
486
|
+
* 28 significant digits, rounded half-even, and an exact quotient kept as
|
|
487
|
+
* close to the dividend's exponent as it allows.
|
|
488
|
+
*/
|
|
489
|
+
export function divideFormat(value, divisor) {
|
|
490
|
+
const negative = (value.coefficient < 0n) !== (divisor < 0);
|
|
491
|
+
const a = value.coefficient < 0n ? -value.coefficient : value.coefficient;
|
|
492
|
+
const b = BigInt(Math.abs(divisor));
|
|
493
|
+
let exponent = value.exponent;
|
|
494
|
+
let coefficient = 0n;
|
|
495
|
+
if (a !== 0n) {
|
|
496
|
+
const shift = b.toString().length - a.toString().length + PRECISION + 1;
|
|
497
|
+
exponent -= shift;
|
|
498
|
+
const [numerator, denominator] = shift >= 0 ? [a * 10n ** BigInt(shift), b] : [a, b * 10n ** BigInt(-shift)];
|
|
499
|
+
coefficient = numerator / denominator;
|
|
500
|
+
if (numerator % denominator !== 0n) {
|
|
501
|
+
// Inexact: make sure a dropped half is never a tie.
|
|
502
|
+
if (coefficient % 5n === 0n)
|
|
503
|
+
coefficient += 1n;
|
|
504
|
+
}
|
|
505
|
+
else {
|
|
506
|
+
while (exponent < value.exponent && coefficient % 10n === 0n) {
|
|
507
|
+
coefficient /= 10n;
|
|
508
|
+
exponent += 1;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
const excess = coefficient.toString().length - PRECISION;
|
|
512
|
+
if (excess > 0) {
|
|
513
|
+
coefficient = roundHalfEven(coefficient, excess);
|
|
514
|
+
exponent += excess;
|
|
515
|
+
if (coefficient.toString().length > PRECISION) {
|
|
516
|
+
coefficient /= 10n;
|
|
517
|
+
exponent += 1;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
const digits = coefficient.toString();
|
|
522
|
+
let text;
|
|
523
|
+
if (exponent >= 0)
|
|
524
|
+
text = digits + "0".repeat(exponent);
|
|
525
|
+
else if (digits.length > -exponent)
|
|
526
|
+
text = `${digits.slice(0, digits.length + exponent)}.${digits.slice(digits.length + exponent)}`;
|
|
527
|
+
else
|
|
528
|
+
text = `0.${"0".repeat(-exponent - digits.length)}${digits}`;
|
|
529
|
+
return negative && coefficient !== 0n ? `-${text}` : text;
|
|
530
|
+
}
|
|
531
|
+
function roundHalfEven(value, drop) {
|
|
532
|
+
const divisor = 10n ** BigInt(drop);
|
|
533
|
+
let quotient = value / divisor;
|
|
534
|
+
const remainder = value % divisor;
|
|
535
|
+
const half = divisor / 2n;
|
|
536
|
+
if (remainder > half || (remainder === half && quotient % 2n === 1n))
|
|
537
|
+
quotient += 1n;
|
|
538
|
+
return quotient;
|
|
539
|
+
}
|
|
540
|
+
/* Filter options. */
|
|
541
|
+
export const filterOptions = async (request) => {
|
|
542
|
+
const { organizationId, filters } = readFilters(request, false);
|
|
543
|
+
const db = request.db;
|
|
544
|
+
const where = baseCriteria(db, organizationId, filters);
|
|
545
|
+
const routerRows = await db.all(sql `
|
|
546
|
+
select distinct
|
|
547
|
+
r.router_id,
|
|
548
|
+
m.name
|
|
549
|
+
from routing_requests r
|
|
550
|
+
left join model_routers m on m.id = r.router_id
|
|
551
|
+
where ${where}
|
|
552
|
+
and r.router_id is not null
|
|
553
|
+
order by m.name nulls last, r.router_id`);
|
|
554
|
+
const keyRows = await db.all(sql `
|
|
555
|
+
select distinct
|
|
556
|
+
k.id,
|
|
557
|
+
k.label,
|
|
558
|
+
k.key_prefix,
|
|
559
|
+
coalesce(k.created_for_user_id, k.attributed_to_user_id) as assigned_user_id,
|
|
560
|
+
u.display_name,
|
|
561
|
+
u.email
|
|
562
|
+
from organization_api_keys k
|
|
563
|
+
join routing_requests r on r.api_key_id = k.id
|
|
564
|
+
left join users u on u.id = coalesce(k.created_for_user_id, k.attributed_to_user_id)
|
|
565
|
+
where ${where}
|
|
566
|
+
and k.organization_id = ${organizationId}
|
|
567
|
+
order by k.label, k.id`);
|
|
568
|
+
const userRows = await db.all(sql `
|
|
569
|
+
select distinct
|
|
570
|
+
r.attributed_user_id,
|
|
571
|
+
u.display_name,
|
|
572
|
+
u.email
|
|
573
|
+
from routing_requests r
|
|
574
|
+
join users u on u.id = r.attributed_user_id
|
|
575
|
+
where ${where}
|
|
576
|
+
and r.attributed_user_id is not null
|
|
577
|
+
order by u.display_name nulls last, u.email, r.attributed_user_id`);
|
|
578
|
+
const modelRows = await db.all(sql `
|
|
579
|
+
select distinct
|
|
580
|
+
${MODEL} as model,
|
|
581
|
+
r.selected_provider
|
|
582
|
+
from routing_requests r
|
|
583
|
+
where ${where}`);
|
|
584
|
+
const providersByModel = new Map();
|
|
585
|
+
const providers = new Set();
|
|
586
|
+
for (const row of modelRows) {
|
|
587
|
+
const model = String(row.model);
|
|
588
|
+
const modelProviders = providersByModel.get(model) ?? new Set();
|
|
589
|
+
providersByModel.set(model, modelProviders);
|
|
590
|
+
if (row.selected_provider !== null && row.selected_provider !== undefined) {
|
|
591
|
+
modelProviders.add(String(row.selected_provider));
|
|
592
|
+
providers.add(String(row.selected_provider));
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
const sorted = (values) => [...values].sort(compareText);
|
|
596
|
+
return {
|
|
597
|
+
routers: routerRows.map((row) => ({ id: String(row.router_id), name: readOptionalString(row.name) || String(row.router_id) })),
|
|
598
|
+
api_keys: keyRows.map((row) => ({
|
|
599
|
+
id: String(row.id),
|
|
600
|
+
label: String(row.label),
|
|
601
|
+
key_prefix: String(row.key_prefix),
|
|
602
|
+
assigned_user_id: readOptionalString(row.assigned_user_id),
|
|
603
|
+
assigned_user_name: readOptionalString(row.display_name) || readOptionalString(row.email),
|
|
604
|
+
})),
|
|
605
|
+
users: userRows.map((row) => ({
|
|
606
|
+
id: String(row.attributed_user_id),
|
|
607
|
+
name: readOptionalString(row.display_name) || String(row.email),
|
|
608
|
+
email: String(row.email),
|
|
609
|
+
})),
|
|
610
|
+
models: sorted(providersByModel.keys()).map((model) => ({ id: model, providers: sorted(providersByModel.get(model)) })),
|
|
611
|
+
providers: sorted(providers),
|
|
612
|
+
};
|
|
613
|
+
};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { type Params } from "./params.js";
|
|
2
|
+
import { type ActivityDb, type Sql } from "./sql.js";
|
|
3
|
+
import { type Instant } from "./values.js";
|
|
4
|
+
/** The source protocols Activity reads, in display order. */
|
|
5
|
+
export declare const SUPPORTED_SOURCE_PROTOCOLS: readonly ["openai_chat", "openai_responses", "anthropic_messages"];
|
|
6
|
+
export type SourceProtocol = (typeof SUPPORTED_SOURCE_PROTOCOLS)[number];
|
|
7
|
+
/** Stands for the steps whose selector chose no model. */
|
|
8
|
+
export declare const SELECTOR_UNRESOLVED_MODEL = "selector-unresolved";
|
|
9
|
+
/** A step's model, under the alias `r`: `SELECTOR_UNRESOLVED_MODEL` when its selector chose none. */
|
|
10
|
+
export declare const MODEL: Sql;
|
|
11
|
+
export declare const REQUEST_STATUSES: readonly ["completed", "provider_error", "selector_error", "aborted"];
|
|
12
|
+
export declare const KEY_SOURCES: readonly ["user", "managed", "subscription"];
|
|
13
|
+
/** The filters as the query gave them, before validation. */
|
|
14
|
+
export type ActivityQuery = {
|
|
15
|
+
from: {
|
|
16
|
+
instant: Instant;
|
|
17
|
+
naive: boolean;
|
|
18
|
+
};
|
|
19
|
+
to: {
|
|
20
|
+
instant: Instant;
|
|
21
|
+
naive: boolean;
|
|
22
|
+
};
|
|
23
|
+
routerId?: string;
|
|
24
|
+
apiKeyIds: string[];
|
|
25
|
+
userIds: string[];
|
|
26
|
+
models: string[];
|
|
27
|
+
provider?: string;
|
|
28
|
+
status?: (typeof REQUEST_STATUSES)[number];
|
|
29
|
+
keySource?: (typeof KEY_SOURCES)[number];
|
|
30
|
+
};
|
|
31
|
+
export declare function readActivityQuery(params: Params): ActivityQuery;
|
|
32
|
+
/** `source_scope`: protocols, comma-separated, or `all` or `none`; absent is all. */
|
|
33
|
+
export declare function readSourceScope(params: Params): string | undefined;
|
|
34
|
+
export declare function sourceProtocols(scope: string | undefined): SourceProtocol[];
|
|
35
|
+
/** Validated filters. `bucketSeconds` is 0 for reads without time buckets. */
|
|
36
|
+
export type ActivityFilters = {
|
|
37
|
+
start: Instant;
|
|
38
|
+
end: Instant;
|
|
39
|
+
bucketSeconds: number;
|
|
40
|
+
protocols: SourceProtocol[];
|
|
41
|
+
routerId?: string;
|
|
42
|
+
apiKeyIds: string[];
|
|
43
|
+
userIds: string[];
|
|
44
|
+
models: string[];
|
|
45
|
+
provider?: string;
|
|
46
|
+
status?: string;
|
|
47
|
+
keySource?: string;
|
|
48
|
+
};
|
|
49
|
+
export declare function validatedRange(query: ActivityQuery): {
|
|
50
|
+
start: Instant;
|
|
51
|
+
end: Instant;
|
|
52
|
+
};
|
|
53
|
+
/** The range and dimensions, for reads without time buckets. */
|
|
54
|
+
export declare function validatedFilters(query: ActivityQuery, protocols: SourceProtocol[]): ActivityFilters;
|
|
55
|
+
/** The range, dimensions, and a bucket size giving at most 1,000 buckets. */
|
|
56
|
+
export declare function validatedBucketFilters(query: ActivityQuery, protocols: SourceProtocol[], bucketSeconds: number): ActivityFilters;
|
|
57
|
+
/** Received in the filters' time range. */
|
|
58
|
+
export declare function timeRange(db: ActivityDb, filters: ActivityFilters, alias?: string): Sql;
|
|
59
|
+
/** The organization, time range, and source protocols. */
|
|
60
|
+
export declare function baseCriteria(db: ActivityDb, organizationId: string, filters: ActivityFilters): Sql;
|
|
61
|
+
/** Router and identity: API keys or attributed people. Empty values filter nothing. */
|
|
62
|
+
export declare function identityCriteria(filters: ActivityFilters, alias?: string): Sql;
|
|
63
|
+
/** Model, provider, status, and key source. */
|
|
64
|
+
export declare function routeCriteria(filters: ActivityFilters, alias?: string): Sql;
|
|
65
|
+
export declare function dimensionCriteria(filters: ActivityFilters, alias?: string): Sql;
|
|
66
|
+
/** Base and dimension criteria: what most reads filter by. */
|
|
67
|
+
export declare function criteria(db: ActivityDb, organizationId: string, filters: ActivityFilters): Sql;
|
|
68
|
+
/** The zero-based time bucket of a request row. */
|
|
69
|
+
export declare function bucketIndex(db: ActivityDb, filters: ActivityFilters): Sql;
|
|
70
|
+
/** The start of a time bucket, as the API writes it. */
|
|
71
|
+
export declare function bucketStart(filters: ActivityFilters, index: unknown): string;
|