okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-022-toks: one answer-speed definition everywhere (engine decode figures)656478c68

main
2.2 KiB41 linesraw
1/**
2 * The engine's own answer speed for one assistant turn: every token its requests produced (thinking, answer and tool calls; with
3 * MTP drafting only the tokens it kept) over the time they spent decoding. These are the numbers the Monitor and `/metrics` show,
4 * so the chat footer reads the same. Nothing here is a guess from the stream: it returns null when the engine does not say.
5 */
6
7/** Sum the engine's finished requests that began at or after `since` (ms). `attempts` is how many model requests the turn made:
8 *  when the engine lists more (another chat ran at the same time), only the newest `attempts` are the turn's. */
9export function sumEngineRequests(requests, { since, attempts = Infinity } = {}) {
10  if (!Array.isArray(requests)) return null;
11  const mine = requests
12    .filter(r => Number.isFinite(r?.time) && r.time * 1000 >= since - 1500)
13    .sort((a, b) => a.time - b.time)
14    .slice(-Math.max(1, attempts));
15  let tokens = 0, decodeMs = 0, promptRead = 0, promptMs = 0;
16  for (const r of mine) {
17    const made = Number.isFinite(r.engine_generated) ? r.engine_generated : r.output_tokens;
18    if (!(made > 0) || !(r.decode_ms > 0)) continue;
19    tokens += made; decodeMs += r.decode_ms;
20    const read = Number.isFinite(r.prompt_read) ? r.prompt_read : (r.prompt_tokens ?? 0) - (r.reused ?? 0);
21    if (read > 0 && r.prompt_ms > 0) { promptRead += read; promptMs += r.prompt_ms; }
22  }
23  if (!(tokens > 0 && decodeMs > 0)) return null;
24  return {
25    tokens, decodeMs, tps: Number((tokens / (decodeMs / 1000)).toFixed(1)),
26    promptTps: promptRead > 0 && promptMs > 0 ? Number((promptRead / (promptMs / 1000)).toFixed(1)) : null,
27  };
28}
29
30/** Ask a local engine for its request history. Any failure is null: the caller keeps the stream's own estimate. */
31export async function turnEngineSpeed({ baseUrl, key, since, attempts, fetcher = fetch, timeoutMs = 1500 }) {
32  try {
33    const origin = new URL(baseUrl).origin;
34    const res = await fetcher(`${origin}/metrics?requests=all`, {
35      signal: AbortSignal.timeout(timeoutMs),
36      headers: key ? { authorization: `Bearer ${key}` } : undefined,
37    });
38    if (!res.ok) return null;
39    return sumEngineRequests((await res.json())?.requests, { since, attempts });
40  } catch { return null; }
41}