aiinfra-tools 0.2.0 → 0.3.0
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/CHANGELOG.md +210 -0
- package/README.md +14 -3
- package/bin/aiinfra.mjs +5 -2
- package/bin/report.mjs +177 -0
- package/fleetops/README.md +33 -1
- package/fleetops/deploy/shadow-gate/argo-analysistemplate.yaml +34 -0
- package/fleetops/deploy/shadow-gate/argo-rollout-example.yaml +38 -0
- package/fleetops/deploy/shadow-gate/flagger-canary.yaml +34 -0
- package/fleetops/deploy/shadow-gate/judge.yaml +51 -0
- package/fleetops/deploy/shadow-gate/llmd-canary-example.yaml +35 -0
- package/fleetops/deploy/shadow-gate/podmonitor-vllm.yaml +20 -0
- package/fleetops/deploy/shadow-live/README.md +33 -0
- package/fleetops/deploy/shadow-live/kit.yaml +121 -0
- package/fleetops/deploy/shadow-live/load-canary.yaml +26 -0
- package/fleetops/deploy/shadow-live/run.sh +48 -0
- package/fleetops/docs/ADMISSION.md +9 -9
- package/fleetops/docs/FABRIC-STORAGE.md +1 -1
- package/fleetops/docs/SERVING.md +11 -1
- package/fleetops/docs/SHADOW.md +250 -0
- package/fleetops/docs/SIGNALS.md +5 -2
- package/fleetops/docs/WORKLOADS.md +1 -1
- package/fleetops/package.json +7 -4
- package/fleetops/src/adapters/fabric.mjs +19 -7
- package/fleetops/src/adapters/live.mjs +38 -5
- package/fleetops/src/adapters/logs.mjs +10 -7
- package/fleetops/src/adapters/nvsentinel.mjs +95 -0
- package/fleetops/src/adapters/topology.mjs +53 -1
- package/fleetops/src/admission.mjs +26 -18
- package/fleetops/src/api.mjs +2 -1
- package/fleetops/src/bundle.mjs +3 -0
- package/fleetops/src/calibrate.mjs +1 -1
- package/fleetops/src/detect.mjs +1 -1
- package/fleetops/src/export.mjs +5 -1
- package/fleetops/src/goodput.mjs +0 -2
- package/fleetops/src/incidents.mjs +1 -2
- package/fleetops/src/ingest.mjs +1 -1
- package/fleetops/src/inject.mjs +2 -2
- package/fleetops/src/live.mjs +2 -1
- package/fleetops/src/llmd.mjs +7 -3
- package/fleetops/src/optimize.mjs +1 -1
- package/fleetops/src/power.mjs +7 -7
- package/fleetops/src/procure.mjs +67 -0
- package/fleetops/src/rca.mjs +1 -1
- package/fleetops/src/rollout.mjs +1 -1
- package/fleetops/src/schema.mjs +3 -2
- package/fleetops/src/security.mjs +1 -1
- package/fleetops/src/serving.mjs +21 -9
- package/fleetops/src/shadow-canary.mjs +74 -0
- package/fleetops/src/shadow-gate.mjs +49 -0
- package/fleetops/src/shadow-prom.mjs +205 -0
- package/fleetops/src/shadow-replay.mjs +147 -0
- package/fleetops/src/shadow.mjs +291 -0
- package/fleetops/src/stats.mjs +14 -0
- package/fleetops/src/traces.mjs +0 -5
- package/fleetops/tests/fixtures/real/README.md +5 -0
- package/fleetops/tools/admit-node.sh +51 -16
- package/fleetops/tools/amd-admit.py +111 -0
- package/fleetops/tools/cmd/calibrate.mjs +61 -0
- package/fleetops/tools/cmd/capacity.mjs +116 -0
- package/fleetops/tools/cmd/common.mjs +32 -0
- package/fleetops/tools/cmd/data.mjs +343 -0
- package/fleetops/tools/cmd/help.mjs +243 -0
- package/fleetops/tools/cmd/incidents.mjs +216 -0
- package/fleetops/tools/cmd/rollout.mjs +122 -0
- package/fleetops/tools/cmd/server.mjs +122 -0
- package/fleetops/tools/cmd/serving.mjs +95 -0
- package/fleetops/tools/cmd/shadow.mjs +204 -0
- package/fleetops/tools/cmd/training.mjs +79 -0
- package/fleetops/tools/collect.sh +6 -1
- package/fleetops/tools/fleetops.mjs +18 -1308
- package/fleetops/tools/loop-demo.mjs +1 -1
- package/fleetops/tools/workload-profile.mjs +0 -1
- package/fleetscope/README.md +5 -1
- package/fleetscope/build.mjs +1 -0
- package/fleetscope/dist/index.html +295 -26
- package/fleetscope/docs/AGENTIC.md +89 -0
- package/fleetscope/docs/PLANNING.md +4 -2
- package/fleetscope/docs/VALIDATION-AGENTIC.md +37 -0
- package/fleetscope/package.json +4 -3
- package/fleetscope/src/agentic.js +288 -0
- package/fleetscope/src/ask.js +0 -1
- package/fleetscope/src/cluster-ui.js +1 -0
- package/fleetscope/src/engine.js +10 -11
- package/fleetscope/src/index.src.html +9 -5
- package/fleetscope/src/inference-ui.js +1 -0
- package/fleetscope/src/ingest.js +89 -3
- package/fleetscope/src/optimize.js +11 -5
- package/fleetscope/src/plan.js +1 -1
- package/fleetscope/src/training-ui.js +1 -0
- package/fleetscope/tools/agentic.mjs +148 -0
- package/fleetscope/tools/tracelab-data.mjs +27 -0
- package/gpu-health/README.md +13 -2
- package/gpu-health/docs/CONFIG.md +29 -1
- package/gpu-health/package.json +7 -4
- package/gpu-health/src/actions.mjs +16 -3
- package/gpu-health/src/analyze.mjs +3 -0
- package/gpu-health/src/config.mjs +3 -0
- package/gpu-health/src/executors.mjs +9 -4
- package/gpu-health/src/health.mjs +1 -1
- package/gpu-health/src/ingest.mjs +27 -3
- package/gpu-health/src/platforms.mjs +109 -0
- package/gpu-health/src/vendors.mjs +12 -5
- package/gpu-health/tools/gpu-health.mjs +6 -4
- package/gpu-ledger/README.md +3 -1
- package/gpu-ledger/package.json +12 -4
- package/gpu-ledger/src/adapters.mjs +3 -2
- package/gpu-ledger/src/cloud.mjs +104 -0
- package/gpu-ledger/src/core.mjs +12 -10
- package/gpu-ledger/tools/ledger.mjs +8 -2
- package/harness-ledger/README.md +152 -0
- package/harness-ledger/docs/FORMATS.md +114 -0
- package/harness-ledger/docs/METHOD.md +133 -0
- package/harness-ledger/docs/VALIDATION-ECONOMICS.md +59 -0
- package/harness-ledger/docs/VALIDATION-SWEBENCH.md +26 -0
- package/harness-ledger/docs/VALIDATION-TRACELAB.md +56 -0
- package/harness-ledger/package.json +19 -0
- package/harness-ledger/src/demo.mjs +115 -0
- package/harness-ledger/src/economics.mjs +184 -0
- package/harness-ledger/src/gpu.mjs +80 -0
- package/harness-ledger/src/html.mjs +63 -0
- package/harness-ledger/src/importers.mjs +247 -0
- package/harness-ledger/src/ledger.mjs +128 -0
- package/harness-ledger/src/opencost.mjs +55 -0
- package/harness-ledger/src/outcomes.mjs +67 -0
- package/harness-ledger/src/prices.mjs +75 -0
- package/harness-ledger/src/record.mjs +52 -0
- package/harness-ledger/src/waste.mjs +136 -0
- package/harness-ledger/tools/harness-ledger.mjs +199 -0
- package/harness-ledger/tools/validate-economics.mjs +69 -0
- package/harness-ledger/tools/validate-swebench.mjs +57 -0
- package/harness-ledger/tools/validate-tracelab.mjs +74 -0
- package/hybrid-tracing/package.json +4 -3
- package/hybrid-tracing/tools/fix-skew.mjs +1 -1
- package/inference-sizer/README.md +5 -1
- package/inference-sizer/build.mjs +1 -0
- package/inference-sizer/dist/index.html +205 -22
- package/inference-sizer/docs/ACCELERATORS.md +62 -0
- package/inference-sizer/docs/VALIDATION-INFERENCEX.md +37 -0
- package/inference-sizer/package.json +4 -3
- package/inference-sizer/src/accelerators.js +172 -0
- package/inference-sizer/src/catalog.js +7 -20
- package/inference-sizer/src/fit-ui.js +1 -1
- package/inference-sizer/src/index.src.html +3 -0
- package/inference-sizer/src/model.js +22 -1
- package/inference-sizer/tools/validate-agentx.mjs +110 -0
- package/inference-sizer/tools/validate-inferencex.mjs +132 -0
- package/mcp/README.md +6 -1
- package/mcp/server.mjs +34 -0
- package/package.json +9 -4
- package/schemas/README.md +3 -0
- package/schemas/aiinfra.report.schema.json +474 -0
- package/schemas/commands.mjs +14 -0
- package/schemas/fleetops.shadow.canary.schema.json +96 -0
- package/schemas/fleetops.shadow.compare.schema.json +266 -0
- package/schemas/fleetops.shadow.prom.schema.json +354 -0
- package/schemas/harness-ledger.economics.schema.json +567 -0
- package/schemas/sizer.list.schema.json +15 -2
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
// Harness logs → llm_call records. One importer per harness; the waste checks downstream only see llm_call.
|
|
2
|
+
//
|
|
3
|
+
// claudeCode Claude Code transcripts (~/.claude/projects/<project>/<session>.jsonl, subagents/agent-*.jsonl)
|
|
4
|
+
// codex Codex CLI / IDE rollouts (~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl)
|
|
5
|
+
// otel OpenTelemetry GenAI spans and OpenInference spans (OTLP JSON, or one span per line): any harness
|
|
6
|
+
// instrumented with OTel (Copilot, Gemini CLI, Claude Code's telemetry, LangGraph, OpenAI Agents SDK,
|
|
7
|
+
// CrewAI, LlamaIndex, Strands, Pydantic AI…)
|
|
8
|
+
// langfuse Langfuse observation exports (GENERATION, TOOL, AGENT observations)
|
|
9
|
+
//
|
|
10
|
+
// Token meanings differ by source; every importer converts to llm_call's (input includes cached tokens):
|
|
11
|
+
// Anthropic usage (Claude Code): input_tokens excludes cache reads and writes → input = sum of the three.
|
|
12
|
+
// Codex (OpenAI): input_tokens includes cached_input_tokens.
|
|
13
|
+
// OTel GenAI: gen_ai.usage.input_tokens SHOULD include cache_read/cache_write; OpenInference: llm.token_count.prompt
|
|
14
|
+
// includes prompt_details.cache_read/cache_write.
|
|
15
|
+
// Langfuse: canonical usage keys are exclusive (input + input_cached_tokens + input_cache_creation); OpenAI-style
|
|
16
|
+
// prompt_tokens is inclusive.
|
|
17
|
+
import { call, dedupe, num, hash, estTokens, toSec } from './record.mjs';
|
|
18
|
+
|
|
19
|
+
const lines = text => { const out = []; for (const l of String(text).split(/\r?\n/)) { if (!l.trim()) continue; try { out.push(JSON.parse(l)); } catch { /* partial line while the harness writes */ } } return out; };
|
|
20
|
+
const textOf = c => (typeof c === 'string' ? c : Array.isArray(c) ? c.map(x => (typeof x === 'string' ? x : x && (x.text ?? x.content ?? (x.type === 'image' ? '[image]' : JSON.stringify(x))))).join('') : c == null ? '' : JSON.stringify(c));
|
|
21
|
+
|
|
22
|
+
// ---------- Claude Code ----------
|
|
23
|
+
export function claudeCode(text, { file } = {}) {
|
|
24
|
+
const out = [], byToolId = new Map();
|
|
25
|
+
for (const o of lines(text)) {
|
|
26
|
+
const m = o.message || {};
|
|
27
|
+
if (o.type === 'assistant' && m.usage && m.model !== '<synthetic>') {
|
|
28
|
+
const u = m.usage, cr = num(u.cache_read_input_tokens), cw = num(u.cache_creation_input_tokens);
|
|
29
|
+
const sid = o.sessionId || (file && file.replace(/^.*[\\/]|\.jsonl$/g, '')) || 'unknown';
|
|
30
|
+
const side = o.isSidechain ? (o.agentId || 'subagent') : null;
|
|
31
|
+
const toolCalls = (Array.isArray(m.content) ? m.content : []).filter(b => b && b.type === 'tool_use').map(b => {
|
|
32
|
+
const tc = { name: b.name, id: b.id, argHash: hash(b.input) }; if (b.id) byToolId.set(b.id, tc); return tc; });
|
|
33
|
+
out.push(call({ t: toSec(o.timestamp), harness: 'claude-code', session: side ? `${sid}:${side}` : sid, parent: side ? sid : null, agent: side || 'main',
|
|
34
|
+
id: `${m.id || o.uuid}|${o.requestId || ''}`, model: m.model, provider: 'anthropic',
|
|
35
|
+
input: (num(u.input_tokens) || 0) + (cr || 0) + (cw || 0), cacheRead: cr ?? 0, cacheWrite: cw ?? 0, output: num(u.output_tokens) || 0,
|
|
36
|
+
toolCalls, finish: m.stop_reason, costUSD: num(o.costUSD), source: 'claude-code-jsonl' }));
|
|
37
|
+
} else if (o.type === 'assistant' && o.isApiErrorMessage) {
|
|
38
|
+
out.push(call({ t: toSec(o.timestamp), harness: 'claude-code', session: o.sessionId || 'unknown', id: o.uuid, model: null, error: 'api_error', agent: o.isSidechain ? (o.agentId || 'subagent') : 'main', source: 'claude-code-jsonl' }));
|
|
39
|
+
} else if (o.type === 'user' && Array.isArray(m.content)) {
|
|
40
|
+
for (const b of m.content) if (b && b.type === 'tool_result') {
|
|
41
|
+
const tc = byToolId.get(b.tool_use_id); if (!tc) continue;
|
|
42
|
+
tc.resultTokens = estTokens(textOf(b.content)); if (b.is_error) tc.error = true;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return dedupe(out);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ---------- Codex ----------
|
|
50
|
+
const CODEX_TOOL_ITEMS = new Set(['function_call', 'custom_tool_call', 'local_shell_call', 'web_search_call', 'tool_search_call']);
|
|
51
|
+
const CODEX_OUTPUT_ITEMS = new Set(['function_call_output', 'custom_tool_call_output', 'local_shell_call_output', 'tool_search_call_output']);
|
|
52
|
+
function codexToolError(output) {
|
|
53
|
+
let o = output; if (typeof o === 'string') { try { o = JSON.parse(o); } catch { return /\b(exit code|exit_code)[:= ]+[1-9]/i.test(output) ? true : undefined; } }
|
|
54
|
+
if (o && typeof o === 'object') { if (o.success === false) return true; const ec = o.metadata && o.metadata.exit_code; if (ec != null && Number(ec) !== 0) return true; }
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
export function codex(text, { file } = {}) {
|
|
58
|
+
const rows = lines(text);
|
|
59
|
+
let session = (file && (file.match(/rollout-[\dT:-]+-(.+)\.jsonl$/) || [])[1]) || null, parent = null, sub = false, model = null;
|
|
60
|
+
const out = [], byCallId = new Map(); let pending = [], prevTotal = null;
|
|
61
|
+
const hasRecords = rows.some(o => o.type === 'token_usage_record');
|
|
62
|
+
const emit = (t, id, u, extra = {}) => {
|
|
63
|
+
out.push(call({ t, harness: 'codex', session: session || 'unknown', parent, agent: sub ? 'subagent' : 'main', id, model: extra.model || model, provider: 'openai',
|
|
64
|
+
input: num(u.input_tokens) || 0, cacheRead: num(u.cached_input_tokens) ?? 0, cacheWrite: num(u.cache_creation_input_tokens) ?? 0, output: num(u.output_tokens) || 0,
|
|
65
|
+
reasoning: num(u.reasoning_output_tokens), toolCalls: pending, source: 'codex-rollout' }));
|
|
66
|
+
pending = [];
|
|
67
|
+
};
|
|
68
|
+
for (const o of rows) {
|
|
69
|
+
const p = o.payload || {}, t = toSec(o.timestamp);
|
|
70
|
+
if (o.type === 'session_meta') {
|
|
71
|
+
session = p.id || session; const sp = p.source && p.source.subagent && p.source.subagent.thread_spawn;
|
|
72
|
+
sub = !!(p.source && p.source.subagent); parent = (sp && sp.parent_thread_id) || p.forked_from_id || parent;
|
|
73
|
+
} else if (o.type === 'turn_context') model = p.model || model;
|
|
74
|
+
else if (o.type === 'response_item' && CODEX_TOOL_ITEMS.has(p.type)) {
|
|
75
|
+
const tc = { name: p.name || p.type, id: p.call_id || p.id, argHash: hash(p.arguments ?? p.input ?? p.action ?? null) };
|
|
76
|
+
if (tc.id) byCallId.set(tc.id, tc); pending.push(tc);
|
|
77
|
+
} else if (o.type === 'response_item' && CODEX_OUTPUT_ITEMS.has(p.type)) {
|
|
78
|
+
const tc = byCallId.get(p.call_id); if (!tc) continue;
|
|
79
|
+
const res = p.output && typeof p.output === 'object' && 'content' in p.output ? p.output.content : p.output;
|
|
80
|
+
tc.resultTokens = estTokens(textOf(res)); if (codexToolError(p.output)) tc.error = true;
|
|
81
|
+
} else if (o.type === 'token_usage_record' && hasRecords) {
|
|
82
|
+
if (p.thread_id && session && p.thread_id !== session) continue; // lines a fork copied from its parent
|
|
83
|
+
emit(t, p.response_id || `${t}`, p.usage || {}, { model: p.model });
|
|
84
|
+
} else if (o.type === 'event_msg' && p.type === 'token_count' && !hasRecords) {
|
|
85
|
+
const info = p.info || {}, last = info.last_token_usage, total = info.total_token_usage;
|
|
86
|
+
if (!last) continue;
|
|
87
|
+
const tot = total ? `${total.input_tokens}|${total.output_tokens}` : null;
|
|
88
|
+
if (tot && tot === prevTotal) continue; // the same snapshot repeated
|
|
89
|
+
if (prevTotal == null && parent && total && last.input_tokens === total.input_tokens && last.output_tokens === total.output_tokens && pending.length === 0 && out.length === 0 && rows.some(r => r.type === 'session_meta' && r.payload && r.payload.forked_from_id)) { prevTotal = tot; continue; } // a fork's inherited history
|
|
90
|
+
prevTotal = tot; emit(t, tot || `${t}`, last, { model: info.model });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return dedupe(out);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ---------- OpenTelemetry GenAI / OpenInference ----------
|
|
97
|
+
const anyVal = v => (v == null ? null : 'stringValue' in v ? v.stringValue : 'intValue' in v ? Number(v.intValue) : 'doubleValue' in v ? v.doubleValue : 'boolValue' in v ? v.boolValue
|
|
98
|
+
: 'arrayValue' in v ? (v.arrayValue.values || []).map(anyVal) : 'kvlistValue' in v ? Object.fromEntries((v.kvlistValue.values || []).map(x => [x.key, anyVal(x.value)])) : null);
|
|
99
|
+
const attrsOf = a => (Array.isArray(a) ? Object.fromEntries(a.map(x => [x.key, anyVal(x.value)])) : a || {});
|
|
100
|
+
// OTLP JSON bodies, arrays of spans, or one span per line → flat spans
|
|
101
|
+
export function flattenSpans(input) {
|
|
102
|
+
const docs = typeof input === 'string' ? (() => { try { return [JSON.parse(input)]; } catch { return lines(input); } })() : Array.isArray(input) ? input : [input];
|
|
103
|
+
const out = [];
|
|
104
|
+
const flat = (sp, res = {}) => {
|
|
105
|
+
const a = attrsOf(sp.attributes);
|
|
106
|
+
const t = toSec(sp.startTimeUnixNano ?? sp.startTime ?? sp.start_time ?? sp.timestamp), end = toSec(sp.endTimeUnixNano ?? sp.endTime ?? sp.end_time);
|
|
107
|
+
const st = sp.status || {}; const code = st.code ?? st.status_code;
|
|
108
|
+
out.push({ traceId: sp.traceId || sp.trace_id || (sp.context && sp.context.trace_id), spanId: sp.spanId || sp.span_id || (sp.context && sp.context.span_id),
|
|
109
|
+
parentSpanId: sp.parentSpanId || sp.parent_span_id || sp.parentId || null, name: sp.name, t: t ?? end, end: end ?? t, attrs: a, service: res['service.name'],
|
|
110
|
+
error: code === 2 || code === 'STATUS_CODE_ERROR' || code === 'ERROR' || a['error.type'] != null });
|
|
111
|
+
};
|
|
112
|
+
for (const d of docs.flat()) {
|
|
113
|
+
if (!d || typeof d !== 'object') continue;
|
|
114
|
+
if (d.resourceSpans) for (const rs of d.resourceSpans) { const res = attrsOf((rs.resource || {}).attributes); for (const ss of rs.scopeSpans || rs.instrumentationLibrarySpans || []) for (const sp of ss.spans || []) flat(sp, res); }
|
|
115
|
+
else if (d.spans) for (const sp of d.spans) flat(sp, attrsOf((d.resource || {}).attributes));
|
|
116
|
+
else if (d.name || d.attributes) flat(d, attrsOf((d.resource || {}).attributes));
|
|
117
|
+
}
|
|
118
|
+
return out.filter(s => s.traceId && s.spanId && s.t != null);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const LLM_OPS = new Set(['chat', 'text_completion', 'generate_content', 'responses', 'completion']);
|
|
122
|
+
const isLLM = a => LLM_OPS.has(a['gen_ai.operation.name']) || a['openinference.span.kind'] === 'LLM';
|
|
123
|
+
const isTool = a => a['gen_ai.operation.name'] === 'execute_tool' || a['openinference.span.kind'] === 'TOOL';
|
|
124
|
+
const isAgent = a => a['gen_ai.operation.name'] === 'invoke_agent' || a['gen_ai.operation.name'] === 'create_agent' || a['openinference.span.kind'] === 'AGENT';
|
|
125
|
+
function toolDefs(a) {
|
|
126
|
+
let defs = a['gen_ai.tool.definitions'];
|
|
127
|
+
if (typeof defs === 'string') { try { defs = JSON.parse(defs); } catch { defs = null; } }
|
|
128
|
+
if (Array.isArray(defs)) return { names: defs.map(d => d && (d.name || (d.function && d.function.name))).filter(Boolean), tokens: estTokens(defs) };
|
|
129
|
+
const names = [], schemas = []; // OpenInference: llm.tools.<i>.tool.name / .tool.json_schema
|
|
130
|
+
for (const [k, v] of Object.entries(a)) { const m = k.match(/^llm\.tools\.(\d+)\.tool\.(name|json_schema)$/); if (!m) continue;
|
|
131
|
+
if (m[2] === 'name') names[m[1]] = v; else { schemas[m[1]] = v; if (names[m[1]] == null) { try { const j = JSON.parse(v); names[m[1]] = j.name || (j.function && j.function.name); } catch { /* not JSON */ } } } }
|
|
132
|
+
return names.length ? { names: names.filter(Boolean), tokens: schemas.length ? estTokens(schemas.join('')) : null } : null;
|
|
133
|
+
}
|
|
134
|
+
export function otel(input, { harness } = {}) {
|
|
135
|
+
const spans = flattenSpans(input), byId = new Map(spans.map(s => [s.spanId, s]));
|
|
136
|
+
const agentOf = s => { for (let p = s, i = 0; p && i < 50; p = byId.get(p.parentSpanId), i++) { const n = p.attrs['gen_ai.agent.name'] || p.attrs['agent.name']; if (n && (isAgent(p.attrs) || p === s)) return n; } return null; };
|
|
137
|
+
const calls = [], byTrace = new Map();
|
|
138
|
+
for (const s of spans.filter(x => isLLM(x.attrs))) {
|
|
139
|
+
const a = s.attrs, oi = a['openinference.span.kind'] === 'LLM' && a['gen_ai.usage.input_tokens'] == null;
|
|
140
|
+
const g = k => num(a[k]);
|
|
141
|
+
const input = oi ? g('llm.token_count.prompt') : g('gen_ai.usage.input_tokens') ?? g('gen_ai.usage.prompt_tokens');
|
|
142
|
+
const cacheRead = oi ? g('llm.token_count.prompt_details.cache_read') : g('gen_ai.usage.cache_read.input_tokens') ?? g('gen_ai.usage.cache_read_input_tokens');
|
|
143
|
+
const cacheWrite = oi ? g('llm.token_count.prompt_details.cache_write') : g('gen_ai.usage.cache_write.input_tokens') ?? g('gen_ai.usage.cache_creation.input_tokens') ?? g('gen_ai.usage.cache_creation_input_tokens');
|
|
144
|
+
const defs = toolDefs(a), fr = a['gen_ai.response.finish_reasons'];
|
|
145
|
+
const c = call({ t: s.t, harness: harness || s.service || (oi ? 'openinference' : 'otel'), session: a['gen_ai.conversation.id'] || a['session.id'] || s.traceId,
|
|
146
|
+
agent: agentOf(s), id: s.spanId, traceId: s.traceId, spanId: s.spanId, model: a['gen_ai.response.model'] || a['gen_ai.request.model'] || a['llm.model_name'],
|
|
147
|
+
provider: a['gen_ai.provider.name'] || a['gen_ai.system'] || a['llm.provider'], input: input || 0, cacheRead, cacheWrite,
|
|
148
|
+
output: (oi ? g('llm.token_count.completion') : g('gen_ai.usage.output_tokens') ?? g('gen_ai.usage.completion_tokens')) || 0,
|
|
149
|
+
reasoning: oi ? g('llm.token_count.completion_details.reasoning') : g('gen_ai.usage.reasoning.output_tokens'),
|
|
150
|
+
toolsOffered: defs && defs.names, toolDefTokens: defs && defs.tokens, finish: Array.isArray(fr) ? fr.join(',') : fr,
|
|
151
|
+
error: s.error ? (a['error.type'] || 'error') : null, durS: s.end != null && s.t != null ? s.end - s.t : null, costUSD: g('llm.cost.total'), source: oi ? 'openinference' : 'otel-genai' });
|
|
152
|
+
calls.push(c); if (!byTrace.has(s.traceId)) byTrace.set(s.traceId, []); byTrace.get(s.traceId).push({ s, c });
|
|
153
|
+
}
|
|
154
|
+
// A tool span belongs to the latest model call in its trace that ended before it started (the call that asked for it).
|
|
155
|
+
for (const s of spans.filter(x => isTool(x.attrs)).sort((x, y) => x.t - y.t)) {
|
|
156
|
+
const a = s.attrs, cands = (byTrace.get(s.traceId) || []).filter(x => x.s.end <= s.t + 1e-6);
|
|
157
|
+
if (!cands.length) continue;
|
|
158
|
+
const owner = cands.reduce((b, x) => (x.s.end > b.s.end ? x : b)).c;
|
|
159
|
+
const result = a['gen_ai.tool.call.result'] ?? a['output.value'];
|
|
160
|
+
const tc = { name: a['gen_ai.tool.name'] || a['tool.name'] || s.name, id: a['gen_ai.tool.call.id'] || a['tool_call.id'] || s.spanId,
|
|
161
|
+
argHash: hash(a['gen_ai.tool.call.arguments'] ?? a['input.value'] ?? a['tool.parameters'] ?? null) };
|
|
162
|
+
if (result != null) tc.resultTokens = estTokens(result);
|
|
163
|
+
if (s.error) tc.error = true;
|
|
164
|
+
owner.toolCalls.push(tc);
|
|
165
|
+
}
|
|
166
|
+
return dedupe(calls);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ---------- Langfuse ----------
|
|
170
|
+
function langfuseUsage(o) {
|
|
171
|
+
const d = o.usageDetails || o.usage_details || {}, u = o.usage || {};
|
|
172
|
+
const g = (...ks) => { for (const k of ks) { const v = num(d[k] ?? u[k]); if (v != null) return v; } return null; };
|
|
173
|
+
const cacheRead = g('input_cached_tokens', 'cache_read_input_tokens', 'input_cache_read', 'cached_tokens', 'input_cached') ?? 0;
|
|
174
|
+
const cacheWrite = g('input_cache_creation', 'cache_creation_input_tokens', 'input_cache_write', 'cache_write_tokens') ?? 0;
|
|
175
|
+
const inclusive = g('prompt_tokens', 'promptTokens');
|
|
176
|
+
const input = inclusive != null ? inclusive : (g('input') || 0) + cacheRead + cacheWrite;
|
|
177
|
+
return { input, cacheRead, cacheWrite, output: g('output', 'completion_tokens', 'completionTokens') || 0, reasoning: g('output_reasoning_tokens', 'output_reasoning', 'reasoning_tokens') };
|
|
178
|
+
}
|
|
179
|
+
export function langfuse(input, { harness = 'langfuse' } = {}) {
|
|
180
|
+
let docs = typeof input === 'string' ? (() => { try { return JSON.parse(input); } catch { return lines(input); } })() : input;
|
|
181
|
+
if (docs && !Array.isArray(docs)) docs = docs.data || docs.observations || [docs];
|
|
182
|
+
const obs = [];
|
|
183
|
+
for (const d of docs.flat()) { if (!d) continue; if (Array.isArray(d.observations)) for (const o of d.observations) obs.push({ ...o, sessionId: o.sessionId ?? d.sessionId, traceId: o.traceId ?? d.id }); else obs.push(d); }
|
|
184
|
+
const calls = [], gens = obs.filter(o => o.type === 'GENERATION').map(o => {
|
|
185
|
+
const u = langfuseUsage(o), t = toSec(o.startTime), end = toSec(o.endTime) ?? t;
|
|
186
|
+
const toolCalls = (((o.output && (o.output.tool_calls || o.output.toolCalls)) || [])).map(tc => ({ name: tc.name || (tc.function && tc.function.name), id: tc.id, argHash: hash(tc.arguments || (tc.function && tc.function.arguments) || null) }));
|
|
187
|
+
const tools = (o.modelParameters && o.modelParameters.tools) || (o.input && o.input.tools);
|
|
188
|
+
const c = call({ t, harness: (o.metadata && o.metadata.harness) || harness, session: o.sessionId || o.traceId, id: o.id, traceId: o.traceId, model: o.model || o.providedModelName,
|
|
189
|
+
...u, toolCalls, toolsOffered: Array.isArray(tools) ? tools.map(x => x.name || (x.function && x.function.name)).filter(Boolean) : null, toolDefTokens: Array.isArray(tools) ? estTokens(tools) : null,
|
|
190
|
+
error: o.level === 'ERROR' ? (o.statusMessage ? 'error' : 'error') : null, durS: end != null && t != null ? end - t : null,
|
|
191
|
+
costUSD: num(o.calculatedTotalCost ?? (o.costDetails && o.costDetails.total) ?? o.totalCost), agent: o.agentName || null, source: 'langfuse' });
|
|
192
|
+
calls.push(c); return { o, c, end };
|
|
193
|
+
});
|
|
194
|
+
for (const o of obs.filter(x => x.type === 'TOOL').sort((x, y) => toSec(x.startTime) - toSec(y.startTime))) {
|
|
195
|
+
const t = toSec(o.startTime), cands = gens.filter(g => g.o.traceId === o.traceId && g.end <= t + 1e-6);
|
|
196
|
+
if (!cands.length) continue;
|
|
197
|
+
const owner = cands.reduce((b, x) => (x.end > b.end ? x : b)).c;
|
|
198
|
+
const existing = owner.toolCalls.find(x => x.name === o.name && x.resultTokens == null);
|
|
199
|
+
const tc = existing || { name: o.name, id: o.id, argHash: hash(o.input ?? null) };
|
|
200
|
+
if (o.output != null) tc.resultTokens = estTokens(o.output); if (o.level === 'ERROR') tc.error = true;
|
|
201
|
+
if (!existing) owner.toolCalls.push(tc);
|
|
202
|
+
}
|
|
203
|
+
return dedupe(calls);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ---------- TraceLab ----------
|
|
207
|
+
// The UW SyFI coding-agent trace (github.com/uw-syfi/TraceLab, CC BY 4.0): one model call per line from Claude Code and
|
|
208
|
+
// Codex, with the provider's cache accounting, timing events and tool calls (names, result sizes, errors; no content,
|
|
209
|
+
// no arguments, so repeats can't be checked).
|
|
210
|
+
export function tracelab(text) {
|
|
211
|
+
const out = [];
|
|
212
|
+
for (const o of lines(text)) {
|
|
213
|
+
if (!o || o.input_tokens_total == null || !o.timing_events) continue;
|
|
214
|
+
out.push(tracelabCall(o));
|
|
215
|
+
}
|
|
216
|
+
return dedupe(out.filter(Boolean));
|
|
217
|
+
}
|
|
218
|
+
export function tracelabCall(o) {
|
|
219
|
+
const ts = (o.timing_events || []).map(e => toSec(e.timestamp)).filter(Number.isFinite);
|
|
220
|
+
if (!ts.length) return null;
|
|
221
|
+
const claude = o.provider === 'claude' || o.claude_cache_read_input_tokens != null;
|
|
222
|
+
const inT = (o.timing_events || []).filter(e => /user_message|tool_result/.test(e.event_type)).map(e => toSec(e.timestamp)).filter(Number.isFinite);
|
|
223
|
+
const t = inT.length ? Math.max(...inT) : Math.min(...ts), end = Math.max(...ts);
|
|
224
|
+
return call({ t, harness: claude ? 'claude-code' : 'codex', session: o.session_id, id: o.round_id || o.trace_key, model: o.model, provider: claude ? 'anthropic' : 'openai',
|
|
225
|
+
input: num(o.input_tokens_total) || 0, cacheRead: claude ? (num(o.claude_cache_read_input_tokens) ?? 0) : (num(o.prefix_tokens) ?? 0), cacheWrite: claude ? (num(o.claude_cache_creation_input_tokens) ?? 0) : 0,
|
|
226
|
+
output: num(o.output_tokens) || 0, reasoning: num(o.reasoning_output_tokens),
|
|
227
|
+
toolCalls: (o.tools || []).map(x => { const tc = { name: x.tool_name, id: x.tool_call_id }; if (x.result_chars != null) tc.resultTokens = Math.ceil(x.result_chars / 4); if (x.is_error) tc.error = true; return tc; }),
|
|
228
|
+
durS: Math.max(0, end - t), source: 'tracelab' });
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Which importer reads this file? By name first, then by content.
|
|
232
|
+
export function detect(text, file = '') {
|
|
233
|
+
if (/rollout-.*\.jsonl$/.test(file)) return 'codex';
|
|
234
|
+
const head = String(text).slice(0, 20000);
|
|
235
|
+
if (/"input_tokens_total"/.test(head) && /"timing_events"/.test(head)) return 'tracelab';
|
|
236
|
+
if (/"resourceSpans"|"gen_ai\.|"openinference\.span\.kind"|"llm\.token_count\./.test(head)) return 'otel';
|
|
237
|
+
if (/"type"\s*:\s*"(session_meta|turn_context|event_msg|response_item)"/.test(head)) return 'codex';
|
|
238
|
+
if (/"sessionId"\s*:/.test(head) && /"type"\s*:\s*"(assistant|user|summary|system)"/.test(head)) return 'claude-code';
|
|
239
|
+
if (/"type"\s*:\s*"GENERATION"|"usageDetails"/.test(head)) return 'langfuse';
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
export const IMPORTERS = { 'claude-code': claudeCode, codex, otel, openinference: otel, langfuse, tracelab };
|
|
243
|
+
export function importText(text, { kind, file, harness } = {}) {
|
|
244
|
+
const k = kind || detect(text, file); const f = IMPORTERS[k];
|
|
245
|
+
if (!f) throw new Error(`can't tell what ${file || 'this input'} is; pass --format ${Object.keys(IMPORTERS).join('|')}`);
|
|
246
|
+
return f(text, { file, harness });
|
|
247
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// The whole pass: llm_call records → priced (list prices, recorded cost, or GPU time) → waste findings → a report
|
|
2
|
+
// that reads as a funnel: tokens processed → served from cache → processed at full price → avoidable, by cause; and
|
|
3
|
+
// dollars: total → avoidable → cost per successful task.
|
|
4
|
+
import { sessionsOf, fresh } from './record.mjs';
|
|
5
|
+
import { priceTable, priceCalls, DEFAULT_PRICES } from './prices.mjs';
|
|
6
|
+
import { engineRequests, replicaRates, joinGpu } from './gpu.mjs';
|
|
7
|
+
import { analyze, DEFAULTS } from './waste.mjs';
|
|
8
|
+
|
|
9
|
+
export const CAUSES = {
|
|
10
|
+
'cache-miss': 'Context re-sent without a cache hit',
|
|
11
|
+
'cache-expired': 'Cache expired during a pause',
|
|
12
|
+
'cache-write-unread': 'Cache writes nobody read',
|
|
13
|
+
'tool-output-bloat': 'Oversized tool output carried forward',
|
|
14
|
+
'repeated-tool-call': 'Same tool call repeated',
|
|
15
|
+
'error-loop': 'Retrying a failing tool',
|
|
16
|
+
'failed-call': 'Failed model calls',
|
|
17
|
+
'unused-tools': 'Tool definitions never used',
|
|
18
|
+
'model-tier': 'Routing calls on a large model (candidate)',
|
|
19
|
+
};
|
|
20
|
+
export const FIXES = {
|
|
21
|
+
'cache-miss': 'Keep the prompt prefix byte-stable: no timestamps or per-call IDs in the system prompt, a fixed tool order, append-only history; mark the prefix cacheable (cache_control) where the provider needs it.',
|
|
22
|
+
'cache-expired': 'Use a longer cache lifetime (1-hour cache writes) for sessions with long tool runs or human pauses, or send a cheap keep-alive before the TTL lapses.',
|
|
23
|
+
'cache-write-unread': 'Don\'t mark the last turn cacheable when nothing will follow it (one-shot subagents, final answers).',
|
|
24
|
+
'tool-output-bloat': 'Cap or summarize tool output (head/tail, grep instead of cat, paginate), or have a subagent read it and return a summary.',
|
|
25
|
+
'repeated-tool-call': 'Give the agent the earlier result (memoize read-only tools within a session) or tell it the state hasn\'t changed.',
|
|
26
|
+
'error-loop': 'Stop after two identical failures and surface the error; fix the tool\'s error message so the model can act on it.',
|
|
27
|
+
'failed-call': 'Look at the errors: oversized requests, rate limits and timeouts are often fixable in the harness configuration.',
|
|
28
|
+
'unused-tools': 'Offer fewer tools per task (load MCP servers and tool groups on demand, use tool search).',
|
|
29
|
+
'model-tier': 'Route short tool-selection steps to the cheaper model named in the price file; check task success before switching.',
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const sum = (xs, f) => xs.reduce((s, x) => s + (f(x) || 0), 0);
|
|
33
|
+
const group = (xs, k) => { const m = new Map(); for (const x of xs) { const v = k(x); if (!m.has(v)) m.set(v, []); m.get(v).push(x); } return m; };
|
|
34
|
+
|
|
35
|
+
export function loadOutcomes(text) {
|
|
36
|
+
if (!text) return new Map();
|
|
37
|
+
// { session: outcome }, [{ session, outcome }], or SWE-bench per_instance_details.json ({ instance: { resolved, … } })
|
|
38
|
+
try { const j = JSON.parse(text); return new Map(Array.isArray(j) ? j.map(r => [String(r.session ?? r.task), norm(r.outcome ?? r.resolved)]) : Object.entries(j).map(([k, v]) => [k, norm(v && typeof v === 'object' ? v.resolved ?? v.outcome : v)])); }
|
|
39
|
+
catch { return new Map(String(text).split(/\r?\n/).slice(1).filter(Boolean).map(l => l.split(',')).map(([s, o]) => [s.trim(), norm(o)])); }
|
|
40
|
+
}
|
|
41
|
+
const norm = v => (/^(1|true|pass|passed|ok|success|succeeded|resolved|done)$/i.test(String(v).trim()) ? 'success' : /^(0|false|fail|failed|failure|error|unresolved|abandoned)$/i.test(String(v).trim()) ? 'failure' : 'unknown');
|
|
42
|
+
|
|
43
|
+
export function ledger(calls, { prices = DEFAULT_PRICES, engineSpans = null, replicas = null, gpuPrices = {}, outcomes = new Map(), ...opts } = {}) {
|
|
44
|
+
const table = priceTable(prices);
|
|
45
|
+
let gpu = null, gpuPrice = new Map();
|
|
46
|
+
if (engineSpans) {
|
|
47
|
+
const reqs = engineRequests(engineSpans), j = joinGpu(calls, reqs, replicaRates(replicas || {}, gpuPrices));
|
|
48
|
+
gpuPrice = j.prices; gpu = { requests: j.requests, matched: j.matched, priced: gpuPrice.size, replicas: j.replicas };
|
|
49
|
+
}
|
|
50
|
+
// relative units and dollars don't mix: in relative mode GPU time is reported but every call is priced in units
|
|
51
|
+
priceCalls(calls, table, table.relative ? new Map() : gpuPrice);
|
|
52
|
+
for (const c of calls) { const o = outcomes.get(c.session) || outcomes.get(c.parent) || c.outcome; if (o) c.outcome = o; }
|
|
53
|
+
const findings = analyze(calls, opts);
|
|
54
|
+
return { calls, findings, report: summarize(calls, findings, { table, gpu, opts: { ...DEFAULTS, ...opts } }) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function summarize(calls, findings, { table, gpu, opts } = {}) {
|
|
58
|
+
const real = findings.filter(f => !f.candidate), cand = findings.filter(f => f.candidate);
|
|
59
|
+
const priced = calls.filter(c => c.cost != null);
|
|
60
|
+
const totals = { calls: calls.length, sessions: sessionsOf(calls).size, harnesses: [...new Set(calls.map(c => c.harness))],
|
|
61
|
+
input: sum(calls, c => c.input), cacheRead: sum(calls, c => c.cacheRead), cacheWrite: sum(calls, c => c.cacheWrite), fresh: sum(calls, fresh), output: sum(calls, c => c.output),
|
|
62
|
+
cost: sum(priced, c => c.cost), pricedCalls: priced.length, unpricedCalls: calls.length - priced.length,
|
|
63
|
+
unpricedModels: [...new Set(calls.filter(c => c.cost == null).map(c => c.model || '(none)'))].slice(0, 12),
|
|
64
|
+
cacheReported: calls.filter(c => c.cacheRead != null).length };
|
|
65
|
+
totals.tokens = totals.input + totals.output;
|
|
66
|
+
totals.avoidableTokens = sum(real, f => f.tokens); totals.avoidableFullPrice = sum(real, f => f.fullPrice); totals.avoidableCost = sum(real, f => f.cost); totals.candidateCost = sum(cand, f => f.cost);
|
|
67
|
+
totals.avoidableShare = totals.cost > 0 ? totals.avoidableCost / totals.cost : null;
|
|
68
|
+
const funnel = [
|
|
69
|
+
{ stage: 'Tokens processed', tokens: totals.tokens },
|
|
70
|
+
{ stage: 'Input served from cache', tokens: totals.cacheRead },
|
|
71
|
+
{ stage: 'Input processed at full price', tokens: totals.fresh + totals.cacheWrite },
|
|
72
|
+
{ stage: 'Output generated', tokens: totals.output },
|
|
73
|
+
{ stage: 'Avoidable work at full price', tokens: totals.avoidableFullPrice },
|
|
74
|
+
{ stage: 'Avoidable context re-read from cache', tokens: Math.max(0, totals.avoidableTokens - totals.avoidableFullPrice) },
|
|
75
|
+
];
|
|
76
|
+
const byCause = [...group(findings, f => f.cause)].map(([cause, fs]) => ({ cause, label: CAUSES[cause] || cause, findings: fs.length, tokens: sum(fs, f => f.tokens), fullPrice: sum(fs, f => f.fullPrice), cost: sum(fs, f => f.cost),
|
|
77
|
+
candidate: fs.every(f => f.candidate), fix: FIXES[cause], sessions: new Set(fs.map(f => `${f.harness}|${f.session}`)).size })).sort((a, b) => a.candidate - b.candidate || b.cost - a.cost || b.tokens - a.tokens);
|
|
78
|
+
const outcomeOf = new Map([...sessionsOf(calls)].map(([k, cs]) => [k, (cs.find(c => c.outcome) || {}).outcome || 'unknown']));
|
|
79
|
+
const harnessRows = [...group(calls, c => c.harness)].map(([harness, cs]) => {
|
|
80
|
+
const fs = real.filter(f => f.harness === harness), sess = sessionsOf(cs), succ = [...sess.keys()].filter(k => outcomeOf.get(k) === 'success').length;
|
|
81
|
+
const inTot = sum(cs, c => c.input), cr = sum(cs, c => c.cacheRead);
|
|
82
|
+
return { harness, sessions: sess.size, calls: cs.length, tokens: inTot + sum(cs, c => c.output), cost: sum(cs, c => c.cost), avoidableCost: sum(fs, f => f.cost), avoidableTokens: sum(fs, f => f.tokens),
|
|
83
|
+
cacheHit: cs.some(c => c.cacheRead != null) && inTot > 0 ? cr / inTot : null, successes: succ, costPerSuccess: succ ? sum(cs, c => c.cost) / succ : null,
|
|
84
|
+
models: [...new Set(cs.map(c => c.model).filter(Boolean))].slice(0, 6) };
|
|
85
|
+
}).sort((a, b) => b.cost - a.cost);
|
|
86
|
+
const sessions = [...sessionsOf(calls)].map(([k, cs]) => {
|
|
87
|
+
const fs = real.filter(f => `${f.harness}|${f.session}` === k), top = [...group(fs, f => f.cause)].map(([c, x]) => [c, sum(x, f => f.cost)]).sort((a, b) => b[1] - a[1])[0];
|
|
88
|
+
return { harness: cs[0].harness, session: cs[0].session, agent: cs[0].agent, calls: cs.length, from: cs[0].t, to: cs.at(-1).t, tokens: sum(cs, c => c.input + c.output), cost: sum(cs, c => c.cost),
|
|
89
|
+
avoidableCost: sum(fs, f => f.cost), avoidableTokens: sum(fs, f => f.tokens), topCause: top && top[0], outcome: outcomeOf.get(k) };
|
|
90
|
+
}).sort((a, b) => b.avoidableCost - a.avoidableCost || b.avoidableTokens - a.avoidableTokens);
|
|
91
|
+
const byTool = [...group(real.filter(f => f.tool), f => `${f.tool}|${f.cause}`)].map(([k, fs]) => ({ tool: fs[0].tool, cause: fs[0].cause, count: fs.length, tokens: sum(fs, f => f.tokens), cost: sum(fs, f => f.cost) }))
|
|
92
|
+
.sort((a, b) => b.cost - a.cost || b.tokens - a.tokens);
|
|
93
|
+
const byModel = [...group(calls, c => c.model || '(none)')].map(([model, cs]) => ({ model, calls: cs.length, tokens: sum(cs, c => c.input + c.output), cost: cs.some(c => c.cost != null) ? sum(cs, c => c.cost) : null,
|
|
94
|
+
cacheHit: sum(cs, c => c.input) > 0 && cs.some(c => c.cacheRead != null) ? sum(cs, c => c.cacheRead) / sum(cs, c => c.input) : null })).sort((a, b) => (b.cost ?? -1) - (a.cost ?? -1) || b.tokens - a.tokens);
|
|
95
|
+
const out = { succ: 0, fail: 0, unknown: 0, costSuccess: 0, costFailure: 0, costUnknown: 0 };
|
|
96
|
+
for (const s of sessions) { const o = s.outcome === 'success' ? 'Success' : s.outcome === 'failure' ? 'Failure' : 'Unknown'; out[o === 'Success' ? 'succ' : o === 'Failure' ? 'fail' : 'unknown']++; out[`cost${o}`] += s.cost; }
|
|
97
|
+
const outcomes = { successes: out.succ, failures: out.fail, unknown: out.unknown, costOnSuccess: out.costSuccess, costOnFailure: out.costFailure, costUnknown: out.costUnknown,
|
|
98
|
+
costPerSuccess: out.succ ? totals.cost / out.succ : null, known: out.succ + out.fail > 0 };
|
|
99
|
+
const top = real.slice().sort((a, b) => b.cost - a.cost || b.tokens - a.tokens).slice(0, 25).map(f => ({ ...f, label: CAUSES[f.cause] }));
|
|
100
|
+
return { totals, funnel, byCause, byHarness: harnessRows, byModel, byTool: byTool.slice(0, 20), sessions: sessions.slice(0, 30), outcomes, top, gpu,
|
|
101
|
+
pricing: table ? { source: table.source, asOf: table.asOf, currency: table.currency } : null, settings: opts };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const fmtN = n => (n == null ? '–' : n >= 1e9 ? (n / 1e9).toFixed(2) + 'B' : n >= 1e6 ? (n / 1e6).toFixed(2) + 'M' : n >= 1e4 ? (n / 1e3).toFixed(1) + 'k' : String(Math.round(n)));
|
|
105
|
+
const fmt$ = n => (n == null ? '–' : n >= 100 ? '$' + n.toFixed(0) : n >= 1 ? '$' + n.toFixed(2) : n > 0 ? '$' + n.toFixed(4) : '$0');
|
|
106
|
+
const pct = x => (x == null ? '–' : (100 * x).toFixed(x < 0.1 ? 1 : 0) + '%');
|
|
107
|
+
// relative units (--prices relative): the same numbers without a currency sign
|
|
108
|
+
const fmtU = n => (n == null ? '–' : (n >= 100 ? n.toFixed(0) : n >= 1 ? n.toFixed(2) : n > 0 ? n.toFixed(4) : '0') + ' u');
|
|
109
|
+
export const moneyFor = r => (r && r.pricing && r.pricing.currency === 'units' ? fmtU : fmt$);
|
|
110
|
+
export { fmtN, fmt$, fmtU, pct };
|
|
111
|
+
|
|
112
|
+
export function text(r) {
|
|
113
|
+
const t = r.totals, L = [], $ = moneyFor(r);
|
|
114
|
+
L.push(`harness-ledger: ${t.calls} model calls in ${t.sessions} sessions from ${t.harnesses.join(', ') || 'no harness'}`);
|
|
115
|
+
L.push(` tokens ${fmtN(t.tokens)} (input ${fmtN(t.input)}, of which from cache ${fmtN(t.cacheRead)} = ${pct(t.input ? t.cacheRead / t.input : null)}; output ${fmtN(t.output)})`);
|
|
116
|
+
L.push(` cost ${$(t.cost)} (${t.pricedCalls}/${t.calls} calls priced; ${r.pricing ? r.pricing.source : ''}${r.gpu ? `; ${r.gpu.priced} by GPU time` : ''})`);
|
|
117
|
+
if (t.unpricedCalls) L.push(` unpriced models: ${t.unpricedModels.join(', ')} (add them to --prices)`);
|
|
118
|
+
L.push(` avoidable ${$(t.avoidableCost)}${t.avoidableShare != null ? ` (${pct(t.avoidableShare)} of cost)` : ''}: ${fmtN(t.avoidableFullPrice)} tokens of work at full price, ${fmtN(t.avoidableTokens - t.avoidableFullPrice)} of context re-read from cache${t.candidateCost ? `; plus ${$(t.candidateCost)} in model-tier candidates` : ''}`);
|
|
119
|
+
if (r.outcomes.known) L.push(` outcomes: ${r.outcomes.successes} succeeded, ${r.outcomes.failures} failed (${$(r.outcomes.costOnFailure)} spent on failed tasks); cost per successful task ${$(r.outcomes.costPerSuccess)}`);
|
|
120
|
+
L.push('', 'Where it goes, by cause:');
|
|
121
|
+
L.push(` ${'cost'.padStart(9)} ${'full-price'.padStart(10)} ${'re-read'.padStart(8)} ${'count'.padStart(5)}`);
|
|
122
|
+
for (const c of r.byCause) L.push(` ${$(c.cost).padStart(9)} ${fmtN(c.fullPrice).padStart(10)} ${fmtN(c.tokens - c.fullPrice).padStart(8)} ${String(c.findings).padStart(5)} ${c.label}`);
|
|
123
|
+
if (!r.byCause.length) L.push(' nothing found');
|
|
124
|
+
if (r.byHarness.length > 1) { L.push('', 'By harness:'); for (const h of r.byHarness) L.push(` ${h.harness.padEnd(14)} ${String(h.sessions).padStart(4)} sessions ${$(h.cost).padStart(9)} avoidable ${$(h.avoidableCost).padStart(8)} cache hit ${pct(h.cacheHit)}`); }
|
|
125
|
+
if (r.byTool.length) { L.push('', 'Tools behind the waste:'); for (const x of r.byTool.slice(0, 8)) L.push(` ${x.tool.padEnd(22)} ${x.cause.padEnd(20)} ${String(x.count).padStart(4)}× ${fmtN(x.tokens).padStart(8)} tok ${$(x.cost)}`); }
|
|
126
|
+
L.push('', 'Fix first:'); for (const c of r.byCause.filter(c => c.cost > 0 || c.tokens > 0).slice(0, 3)) L.push(` ${c.label}: ${c.fix}`);
|
|
127
|
+
return L.join('\n') + '\n';
|
|
128
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// What self-hosting costs per token, measured: OpenCost's inference cost tracking (INFERENCE_COST_ENABLED=true) for vLLM
|
|
2
|
+
// and llm-d deployments. Two sources, same numbers:
|
|
3
|
+
// REST GET <opencost>/inferenceCost/total?window=7d&aggregate=model_name,namespace&costBasis=allocation
|
|
4
|
+
// → data.inferenceCosts["<model>:<namespace>"] { inputCostPerMillionTokens, outputCostPerMillionTokens,
|
|
5
|
+
// cacheSavingsFraction, promptTokens, generationTokens, totalCost, allocationMethod, costBasis }
|
|
6
|
+
// Prometheus llm_cost_per_million_tokens{phase="prompt"|"generation", cost_basis, model_name, namespace} and
|
|
7
|
+
// llm_cache_savings_fraction{model_name, namespace}
|
|
8
|
+
// The allocation basis (the default) includes idle and shared infrastructure and reconciles to the bill.
|
|
9
|
+
//
|
|
10
|
+
// OpenCost's prompt price is per delivered input token (cached ones included), so it already carries that model's own
|
|
11
|
+
// cache hit rate. Applied to a workload whose cache hit rate differs, it is turned into a price per prefilled token:
|
|
12
|
+
// prompt price / (1 − cacheSavingsFraction), charged on the workload's fresh input only (cache hits cost ~no compute).
|
|
13
|
+
|
|
14
|
+
export function fromRest(json, { model = null, namespace = null } = {}) {
|
|
15
|
+
const d = (json && json.data) || json || {}, costs = d.inferenceCosts || (Array.isArray(d.inferenceCostSets) && d.inferenceCostSets.at(-1) && d.inferenceCostSets.at(-1).inferenceCosts) || {};
|
|
16
|
+
const rows = Object.entries(costs).map(([key, v]) => {
|
|
17
|
+
const [m, ns] = key.includes(':') ? [key.slice(0, key.lastIndexOf(':')), key.slice(key.lastIndexOf(':') + 1)] : [key, null];
|
|
18
|
+
return { key, model: (v.properties && v.properties.modelName) || m, namespace: (v.properties && v.properties.namespace) || ns, costBasis: v.costBasis || 'allocation', input: v.inputCostPerMillionTokens, output: v.outputCostPerMillionTokens,
|
|
19
|
+
blended: v.costPerMillionTokens, cacheSavings: v.cacheSavingsFraction ?? null, promptTokens: v.promptTokens, generationTokens: v.generationTokens, totalCost: v.totalCost, allocationMethod: v.allocationMethod || '' };
|
|
20
|
+
});
|
|
21
|
+
return pick(rows, { model, namespace });
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function pick(rows, { model, namespace }) {
|
|
25
|
+
const match = r => (!model || r.model === model || String(r.model).split('/').pop() === String(model).split('/').pop()) && (!namespace || r.namespace === namespace);
|
|
26
|
+
const ok = rows.filter(r => match(r) && Number.isFinite(r.input) && Number.isFinite(r.output) && (r.input > 0 || r.output > 0));
|
|
27
|
+
if (!ok.length) {
|
|
28
|
+
const zero = rows.filter(match);
|
|
29
|
+
throw new Error(zero.length ? `OpenCost has ${zero.map(r => r.key).join(', ')} but no cost on it (allocationMethod "${zero[0].allocationMethod}"): check the pod's model label matches vLLM's model_name` : `no OpenCost inference cost${model ? ` for ${model}` : ''}${namespace ? ` in ${namespace}` : ''}; have: ${rows.map(r => r.key).join(', ') || 'nothing'}`);
|
|
30
|
+
}
|
|
31
|
+
if (ok.length > 1 && !model) throw new Error(`OpenCost has several models (${ok.map(r => r.key).join(', ')}): pass --opencost-model`);
|
|
32
|
+
// several namespaces of one model: token-weighted
|
|
33
|
+
if (ok.length === 1) return ok[0];
|
|
34
|
+
const w = r => (r.promptTokens || 0) + (r.generationTokens || 0) || 1, W = ok.reduce((a, r) => a + w(r), 0);
|
|
35
|
+
const avg = k => ok.reduce((a, r) => a + (r[k] ?? 0) * w(r), 0) / W;
|
|
36
|
+
return { key: ok.map(r => r.key).join('+'), model: ok[0].model, namespace: ok.map(r => r.namespace).join(','), costBasis: ok[0].costBasis, input: avg('input'), output: avg('output'), cacheSavings: avg('cacheSavings'), allocationMethod: ok[0].allocationMethod };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Prometheus instant queries (the gauges OpenCost exports every collection interval; averaged over `window`)
|
|
40
|
+
export async function fromPrometheus(prom, { model = null, namespace = null, costBasis = 'allocation', window = '24h', fetcher = fetch, headers } = {}) {
|
|
41
|
+
const sel = [`cost_basis="${costBasis}"`, model ? `model_name="${String(model).replace(/"/g, '')}"` : null, namespace ? `namespace="${String(namespace).replace(/"/g, '')}"` : null].filter(Boolean).join(',');
|
|
42
|
+
const q = async expr => { const r = await fetcher(`${prom.replace(/\/$/, '')}/api/v1/query?query=${encodeURIComponent(expr)}`, { headers }); if (!r.ok) throw new Error(`prometheus: HTTP ${r.status}`); const j = await r.json(); if (j.status !== 'success') throw new Error(`prometheus: ${j.error || j.status}`); return j.data.result; };
|
|
43
|
+
const price = await q(`avg_over_time(llm_cost_per_million_tokens{${sel},phase=~"prompt|generation"}[${window}])`);
|
|
44
|
+
const cache = await q(`avg_over_time(llm_cache_savings_fraction{${sel.replace(/cost_basis="[^"]*",?/, '')}}[${window}])`);
|
|
45
|
+
const rows = new Map();
|
|
46
|
+
for (const s of price) { const k = `${s.metric.model_name}:${s.metric.namespace}`; if (!rows.has(k)) rows.set(k, { key: k, model: s.metric.model_name, namespace: s.metric.namespace, costBasis, allocationMethod: s.metric.allocation_method || '' }); rows.get(k)[s.metric.phase === 'prompt' ? 'input' : 'output'] = +s.value[1]; }
|
|
47
|
+
for (const s of cache) { const r = rows.get(`${s.metric.model_name}:${s.metric.namespace}`); if (r) r.cacheSavings = +s.value[1]; }
|
|
48
|
+
return pick([...rows.values()], { model, namespace });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// → economics' selfHostPrice: $ per million fresh (prefilled) input tokens, cache reads free, output as measured
|
|
52
|
+
export function toSelfHostPrice(r) {
|
|
53
|
+
const f = Number.isFinite(r.cacheSavings) ? Math.min(0.99, Math.max(0, r.cacheSavings)) : 0;
|
|
54
|
+
return { input: r.input / (1 - f), cacheRead: 0, output: r.output, source: `OpenCost ${r.costBasis} cost for ${r.model}${r.namespace ? ` in ${r.namespace}` : ''} (${r.allocationMethod || 'split unknown'}; its own cache hit ${(100 * f).toFixed(0)}%)`, opencost: r };
|
|
55
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Outcome-labelled task runs: what an agent spent per task and whether the task succeeded. From these: cost per
|
|
2
|
+
// successful task, the share of spend that went to tasks that failed, and what a step or spend cap would have saved
|
|
3
|
+
// against the successes it would have cost.
|
|
4
|
+
//
|
|
5
|
+
// A task: { task, run, model, cost, calls, outcome: 'success'|'failure' }.
|
|
6
|
+
// Inputs: SWE-bench per_instance_details.json ({ instance: { cost, api_calls, resolved } }, as in the SWE-bench
|
|
7
|
+
// experiments repository), or a JSON array / CSV of tasks.
|
|
8
|
+
|
|
9
|
+
export function tasksFromSwebench(json, { run = 'run', model = null } = {}) {
|
|
10
|
+
return Object.entries(json || {}).filter(([, v]) => v && typeof v === 'object').map(([task, v]) => ({
|
|
11
|
+
task, run, model, cost: Number(v.cost ?? v.instance_cost ?? 0) || 0, calls: Number(v.api_calls ?? v.calls ?? 0) || 0, outcome: v.resolved ? 'success' : 'failure' }));
|
|
12
|
+
}
|
|
13
|
+
export function tasksFromRows(rows, { run = 'run' } = {}) {
|
|
14
|
+
return rows.map(r => ({ task: String(r.task ?? r.session ?? r.instance ?? r.id), run: r.run || run, model: r.model || null, cost: Number(r.cost ?? r.costUSD ?? 0) || 0,
|
|
15
|
+
calls: Number(r.calls ?? r.api_calls ?? r.steps ?? 0) || 0, outcome: /^(1|true|success|resolved|pass(ed)?)$/i.test(String(r.outcome ?? r.resolved)) ? 'success' : 'failure' }));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const sum = (xs, f) => xs.reduce((a, x) => a + (f(x) || 0), 0);
|
|
19
|
+
const mean = (xs, f) => (xs.length ? sum(xs, f) / xs.length : null);
|
|
20
|
+
const q = (a, p) => { const s = [...a].sort((x, y) => x - y); return s.length ? s[Math.min(s.length - 1, Math.floor(p * (s.length - 1)))] : null; };
|
|
21
|
+
|
|
22
|
+
// Stop every task at `cap` calls. Assumes each call costs the task's average (a task's later calls carry more context,
|
|
23
|
+
// so real savings are larger: this is the conservative estimate) and that a success needing more calls is lost.
|
|
24
|
+
export function capAt(tasks, cap) {
|
|
25
|
+
let cost = 0, succ = 0;
|
|
26
|
+
for (const t of tasks) { const f = t.calls > 0 ? Math.min(1, cap / t.calls) : 1; cost += t.cost * f; if (t.outcome === 'success' && t.calls <= cap) succ++; }
|
|
27
|
+
return { cap, cost, successes: succ };
|
|
28
|
+
}
|
|
29
|
+
export function capCurve(tasks, caps) {
|
|
30
|
+
const base = { cost: sum(tasks, t => t.cost), successes: tasks.filter(t => t.outcome === 'success').length };
|
|
31
|
+
return caps.map(c => { const r = capAt(tasks, c); return { cap: c, saved: base.cost ? 1 - r.cost / base.cost : 0, successesLost: base.successes - r.successes,
|
|
32
|
+
rateLossPts: tasks.length ? 100 * (base.successes - r.successes) / tasks.length : 0, costPerSuccess: r.successes ? r.cost / r.successes : null }; });
|
|
33
|
+
}
|
|
34
|
+
// The cap that saves the most while losing at most `maxLossPts` points of success rate.
|
|
35
|
+
export function bestCap(curve, maxLossPts = 1) { return curve.filter(c => c.rateLossPts <= maxLossPts).sort((a, b) => b.saved - a.saved)[0] || null; }
|
|
36
|
+
|
|
37
|
+
export function runSummary(tasks, { caps } = {}) {
|
|
38
|
+
const succ = tasks.filter(t => t.outcome === 'success'), fail = tasks.filter(t => t.outcome === 'failure'), cost = sum(tasks, t => t.cost);
|
|
39
|
+
const maxCalls = Math.max(1, ...tasks.map(t => t.calls));
|
|
40
|
+
const cs = caps || [10, 15, 20, 25, 30, 40, 50, 60, 75, 100, 125, 150, 200, 250].filter(c => c < maxCalls);
|
|
41
|
+
const curve = capCurve(tasks, cs);
|
|
42
|
+
return { run: tasks[0] && tasks[0].run, model: tasks[0] && tasks[0].model, tasks: tasks.length, successes: succ.length, rate: tasks.length ? succ.length / tasks.length : 0,
|
|
43
|
+
cost, costPerTask: cost / Math.max(1, tasks.length), costPerSuccess: succ.length ? cost / succ.length : null, failShare: cost ? sum(fail, t => t.cost) / cost : 0,
|
|
44
|
+
calls: { success: { mean: mean(succ, t => t.calls), p90: q(succ.map(t => t.calls), 0.9) }, failure: { mean: mean(fail, t => t.calls), p90: q(fail.map(t => t.calls), 0.9) } },
|
|
45
|
+
costPerTaskBy: { success: mean(succ, t => t.cost), failure: mean(fail, t => t.cost) }, curve, best1pt: bestCap(curve, 1), best05pt: bestCap(curve, 0.5) };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function outcomeReport(tasks, opt = {}) {
|
|
49
|
+
const runs = new Map(); for (const t of tasks) { if (!runs.has(t.run)) runs.set(t.run, []); runs.get(t.run).push(t); }
|
|
50
|
+
const usable = [...runs.values()].filter(ts => ts.some(t => t.outcome === 'success') && sum(ts, t => t.cost) > 0);
|
|
51
|
+
const skipped = [...runs.keys()].filter(k => !usable.some(ts => ts[0].run === k));
|
|
52
|
+
const per = usable.map(ts => runSummary(ts, opt)).sort((a, b) => (a.costPerSuccess ?? Infinity) - (b.costPerSuccess ?? Infinity));
|
|
53
|
+
const all = usable.flat();
|
|
54
|
+
return { runs: per, skipped, pooled: per.length ? { tasks: all.length, failShare: sum(all.filter(t => t.outcome === 'failure'), t => t.cost) / Math.max(1e-12, sum(all, t => t.cost)),
|
|
55
|
+
medianFailShare: q(per.map(r => r.failShare), 0.5), callsRatio: q(per.map(r => (r.calls.failure.mean || 0) / Math.max(1, r.calls.success.mean || 1)), 0.5),
|
|
56
|
+
medianBest1ptSaved: q(per.map(r => (r.best1pt ? r.best1pt.saved : 0)), 0.5) } : null };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const $ = x => (x == null ? '–' : x >= 100 ? '$' + x.toFixed(0) : x >= 1 ? '$' + x.toFixed(2) : '$' + x.toFixed(3));
|
|
60
|
+
const P = x => (x == null ? '–' : (100 * x).toFixed(0) + '%');
|
|
61
|
+
export function outcomeText(R) {
|
|
62
|
+
const L = [`${R.runs.length} runs, ${R.pooled ? R.pooled.tasks : 0} tasks${R.skipped.length ? ` (skipped, no successes or no cost: ${R.skipped.join(', ')})` : ''}`, '',
|
|
63
|
+
' run success cost/task cost/success spent on failures calls ok/failed cap (≤1 pt lost)'];
|
|
64
|
+
for (const r of R.runs) L.push(` ${String(r.model || r.run).slice(0, 42).padEnd(42)} ${P(r.rate).padStart(7)} ${$(r.costPerTask).padStart(9)} ${$(r.costPerSuccess).padStart(12)} ${P(r.failShare).padStart(17)} ${String(Math.round(r.calls.success.mean || 0)).padStart(6)}/${String(Math.round(r.calls.failure.mean || 0)).padEnd(8)} ${r.best1pt ? `${r.best1pt.cap} calls: −${P(r.best1pt.saved)} cost, −${r.best1pt.rateLossPts.toFixed(1)} pts` : '–'}`);
|
|
65
|
+
if (R.pooled) L.push('', ` median run: ${P(R.pooled.medianFailShare)} of spend on tasks that failed; failed tasks take ${R.pooled.callsRatio.toFixed(2)}× the calls of successful ones; a call cap losing ≤1 point of success saves ${P(R.pooled.medianBest1ptSaved)}`);
|
|
66
|
+
return L.join('\n') + '\n';
|
|
67
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// What a model call cost: list prices for hosted APIs, or GPU time for self-hosted models (see gpu.mjs).
|
|
2
|
+
//
|
|
3
|
+
// A price file: { asOf, currency, models: { "<model id or prefix>": { input, cacheRead, cacheWrite, output ($ per
|
|
4
|
+
// million tokens), tier?: 'large'|'medium'|'small', downshift?: "<cheaper model to try for small routing calls>" } } }
|
|
5
|
+
// Keys match a model id exactly, or as a prefix ("claude-sonnet-4-5" matches "claude-sonnet-4-5-20250929").
|
|
6
|
+
//
|
|
7
|
+
// The defaults below are examples to make the report readable out of the box, not a price list to rely on. Prices
|
|
8
|
+
// change and new models appear; pass --prices with yours. Calls whose model isn't priced are reported as unpriced,
|
|
9
|
+
// and a cost the harness recorded itself (Claude Code's costUSD, OpenInference llm.cost.total, Langfuse cost) wins.
|
|
10
|
+
export const DEFAULT_PRICES = {
|
|
11
|
+
asOf: '2026-11-25', currency: 'USD',
|
|
12
|
+
note: 'Examples only. OpenAI rows from developers.openai.com/api/docs/pricing; Anthropic rows from the Claude pricing page as of late 2025 (5-minute cache writes). Check both before relying on them.',
|
|
13
|
+
models: {
|
|
14
|
+
'claude-opus-4-5': { input: 5, cacheRead: 0.5, cacheWrite: 6.25, output: 25, tier: 'large', downshift: 'claude-sonnet-4-5' },
|
|
15
|
+
'claude-sonnet-4-5': { input: 3, cacheRead: 0.3, cacheWrite: 3.75, output: 15, tier: 'medium', downshift: 'claude-haiku-4-5' },
|
|
16
|
+
'claude-haiku-4-5': { input: 1, cacheRead: 0.1, cacheWrite: 1.25, output: 5, tier: 'small' },
|
|
17
|
+
'gpt-5-nano': { input: 0.05, cacheRead: 0.005, cacheWrite: 0.05, output: 0.4, tier: 'small' },
|
|
18
|
+
'gpt-5-mini': { input: 0.25, cacheRead: 0.025, cacheWrite: 0.25, output: 2, tier: 'medium', downshift: 'gpt-5-nano' },
|
|
19
|
+
'gpt-5.4': { input: 2.5, cacheRead: 0.25, cacheWrite: 2.5, output: 15, tier: 'large' },
|
|
20
|
+
'gpt-5': { input: 1.25, cacheRead: 0.125, cacheWrite: 1.25, output: 10, tier: 'large', downshift: 'gpt-5-mini' },
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// Relative units, when real prices aren't known or don't matter (comparing harnesses on the same footing): every model at
|
|
25
|
+
// 1 per million fresh input tokens, cache reads 0.1, cache writes 1.25, output 5 — the usual shape of API price lists.
|
|
26
|
+
export const RELATIVE = { relative: true, source: 'relative units (1 = a million fresh input tokens)', models: {} };
|
|
27
|
+
const RELATIVE_ENTRY = { input: 1, cacheRead: 0.1, cacheWrite: 1.25, output: 5 };
|
|
28
|
+
|
|
29
|
+
export function priceTable(prices = DEFAULT_PRICES) {
|
|
30
|
+
if (prices === 'relative' || (prices && prices.relative)) return { find: m => (m ? { key: '*', ...RELATIVE_ENTRY } : null), source: RELATIVE.source, asOf: null, currency: 'units', relative: true };
|
|
31
|
+
const models = (prices && prices.models) || {};
|
|
32
|
+
const keys = Object.keys(models).sort((a, b) => b.length - a.length);
|
|
33
|
+
const find = model => {
|
|
34
|
+
if (!model) return null;
|
|
35
|
+
const m = String(model).toLowerCase().replace(/^(anthropic|openai|us\.anthropic|global\.anthropic|bedrock|vertex_ai)[./:]/, '');
|
|
36
|
+
// exact, or a prefix that ends where the id's next part starts ("gpt-5" prices "gpt-5-codex", not "gpt-5.5")
|
|
37
|
+
const k = keys.find(x => m === x.toLowerCase()) || keys.find(x => m.startsWith(x.toLowerCase()) && /^[-@:_]/.test(m.slice(x.length)));
|
|
38
|
+
return k ? { key: k, ...models[k] } : null;
|
|
39
|
+
};
|
|
40
|
+
return { find, source: prices === DEFAULT_PRICES ? 'example prices (pass --prices)' : (prices.source || 'price file'), asOf: prices.asOf, currency: prices.currency || 'USD' };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// $ per token for one call: { in, read, write, out, source } or null when unpriced.
|
|
44
|
+
const PER_M = 1e6;
|
|
45
|
+
export function perToken(entry, source) {
|
|
46
|
+
if (!entry || entry.input == null) return null;
|
|
47
|
+
const inP = entry.input / PER_M;
|
|
48
|
+
return { in: inP, read: (entry.cacheRead ?? entry.input) / PER_M, write: (entry.cacheWrite ?? entry.input) / PER_M, out: (entry.output ?? entry.input) / PER_M, source };
|
|
49
|
+
}
|
|
50
|
+
export const costWith = (c, p) => (p ? Math.max(0, (c.input || 0) - (c.cacheRead || 0) - (c.cacheWrite || 0)) * p.in + (c.cacheRead || 0) * p.read + (c.cacheWrite || 0) * p.write + (c.output || 0) * p.out : null);
|
|
51
|
+
|
|
52
|
+
// A cost the harness recorded but no price list: spread it over the call's tokens with typical ratios
|
|
53
|
+
// (cache read 0.1×, cache write 1.25×, output 5× input) so the waste checks can still price their parts.
|
|
54
|
+
export function fromRecordedCost(c) {
|
|
55
|
+
const units = Math.max(0, (c.input || 0) - (c.cacheRead || 0) - (c.cacheWrite || 0)) + 0.1 * (c.cacheRead || 0) + 1.25 * (c.cacheWrite || 0) + 5 * (c.output || 0);
|
|
56
|
+
if (!(units > 0) || !(c.costUSD >= 0)) return null;
|
|
57
|
+
const u = c.costUSD / units;
|
|
58
|
+
return { in: u, read: 0.1 * u, write: 1.25 * u, out: 5 * u, source: 'harness-recorded cost' };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function priceCalls(calls, table, gpuPrices = new Map()) {
|
|
62
|
+
for (const c of calls) {
|
|
63
|
+
const g = gpuPrices.get(c);
|
|
64
|
+
const listed = table.find(c.model);
|
|
65
|
+
let p = g || null;
|
|
66
|
+
if (!p && c.costUSD != null) { const lp = perToken(listed, table.source); const lc = costWith(c, lp); p = lp && lc > 0 ? scale(lp, c.costUSD / lc, 'harness-recorded cost') : fromRecordedCost(c); }
|
|
67
|
+
if (!p) p = perToken(listed, table.source);
|
|
68
|
+
c.price = p; c.cost = p ? (g && g.total != null ? g.total : c.costUSD ?? costWith(c, p)) : null;
|
|
69
|
+
c.tier = listed && listed.tier; c.downshift = listed && listed.downshift;
|
|
70
|
+
// the cheaper model's prices, for the model-tier check (not written out)
|
|
71
|
+
if (c.downshift) Object.defineProperty(c, 'cheaper', { value: perToken(table.find(c.downshift), table.source), enumerable: false, configurable: true });
|
|
72
|
+
}
|
|
73
|
+
return calls;
|
|
74
|
+
}
|
|
75
|
+
const scale = (p, k, source) => ({ in: p.in * k, read: p.read * k, write: p.write * k, out: p.out * k, source });
|