feat: scope dashboard token usage to episode, trace and branch (#4417)
## Summary - The trace sidebar shows **input / output / total tokens** from the trace's own `num_input_tokens` / `num_output_tokens` / `num_total_tokens`, so input + output = total. Before, it summed provider usage over every call: "input tokens" counted the re-sent context once per turn, and "total input" and "total tokens" built on that. - The sidebar groups its rows by scope: - **episode** (only when the episode has more than one trace): trace count and the episode's input / output / total. - **trace**: messages, turns, tool calls, branches, input / output / total and cost. - **branch N** (only for a multi-branch trace with one branch selected): messages, turns, tool calls and the branch's input / output / total. - Messages, turns and tool calls used to be per selected branch without saying so. They now sit in the section for their scope. - Timeline tooltips and the semantic inspector show the same input / output / total rows. - **Trace lanes** read the trace's fields. - **Branch and context lanes** count each fed-in token once (`new_input_tokens`, the same rule as verifiers' `min_new_input_tokens`). - **A single model call** shows its whole prompt (cached part included) as input. - The sidebar, timeline tooltips and semantic inspector no longer show "total input", "cached input", "reasoning tokens", "max context length", "cumulative processed" or "uncached input". Cached input added up the cached prompt of every call, so it counted the shared context again on each turn. The other rows read as parts of the total. Timeline lanes no longer carry `total_input_tokens`, `cached_tokens` or `reasoning_tokens`. - Counts the record already carries are read from it instead of recounted: the sidebar's trace turns and branches (`num_turns`, `num_branches`), its episode tokens (`Episode.num_*_tokens`), the live table's turns, branches and cost, the index row's turns and cost (`Episode.num_turns`, `Episode.usage.cost`), and the timeline trace lane's cost (`Trace.usage.cost`). The live table counted model calls as turns; it now reports sampled turns, like the finished table. - The trace toggle lists traces in the order their agents started, and an episode opens on the earliest one. An agentic judge used to come before the solver it graded. Trace indices stay as stored, so links and citations still resolve. ## Verification Ran a one-episode agentic-judge eval on SWE-bench Verified with the bash harness. Solver compaction was set at 12K tokens, so the solver trace split into 5 branches. Then opened it in a dashboard served from this branch (Playwright, no page errors). - **Live:** the solver trace carries the `num_*` fields while it runs. The trace section and the branch section updated as the trace grew. - **Finished:** the dashboard matches verifiers' `Episode` / `Trace` / `Branch` models on every number: | scope | input | output | total | |---|---|---|---| | episode | 42,707 | 28,557 | 71,264 | | solver trace | 37,259 | 26,608 | 63,867 | | solver branches 0–4 | 5,533 / 6,387 / 7,806 / 8,528 / 9,005 | 6,157 / 7,197 / 5,486 / 5,103 / 2,665 | 11,690 / 13,584 / 13,292 / 13,631 / 11,670 | | judge trace | 5,448 | 1,949 | 7,397 | - The old sidebar would have shown about 622K "total tokens" for the same solver trace, because it counted the re-sent context on every turn. - A branch's total here is input + output. On a compacted branch this exceeds verifiers' `Branch.num_total_tokens` (final sequence length). On the summary call, the server's chat template dropped the earlier turns' reasoning from the prompt, so those tokens were counted when generated but are no longer in the final sequence. - `tests/unit/test_dashboard_timeline.py`: the two semantic-context totals changed from 260 → 140 and 310 → 190. In those fixtures, the second call's prompt is shorter than the first call's final sequence, so it adds no new input. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes how token totals and costs are computed across the dashboard and live/index summaries; wrong field usage would misreport usage but does not affect training or auth. > > **Overview** > Dashboard token and activity numbers now align with persisted **episode / trace / branch** scopes instead of re-summing per-call provider usage (which inflated totals when context was resent each turn). > > The sidebar groups **episode**, **trace**, and selected **branch** rows and reads `num_*_tokens` (plus `branchTokens` / server `new_input_tokens` for branch paths). Timeline and semantic views drop cached/reasoning/max-context breakdowns; per-call tooltips treat **input** as full prompt (cached included). Monitors (**index**, **live**) stop recomputing turns, branches, and cost from calls and use record fields instead. Trace tabs and default selection follow **agent start order** via `traceOrder`. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 59aadfaa0a65b69346ae0082c114601584f82813. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
e18b36f059
commit
eed0e44ce0
@@ -944,9 +944,6 @@ def activity_spans(
|
||||
ended = call_time.get("end")
|
||||
usage = call.get("usage") or {}
|
||||
input_tokens, cached_tokens, output_tokens = token_usage(usage)
|
||||
reasoning_tokens = usage.get("reasoning_tokens")
|
||||
if reasoning_tokens is None:
|
||||
reasoning_tokens = (usage.get("completion_tokens_details") or {}).get("reasoning_tokens")
|
||||
text = " ".join(message_text(node.get("message") or {}).split())
|
||||
mask = node.get("mask")
|
||||
spans.append(
|
||||
@@ -964,7 +961,6 @@ def activity_spans(
|
||||
"input_tokens": input_tokens,
|
||||
"cached_tokens": cached_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
"cost": usage.get("cost"),
|
||||
"trainable": any(mask) if isinstance(mask, list) and mask else None,
|
||||
}
|
||||
@@ -998,6 +994,20 @@ def lifecycle_spans(trace: dict) -> list[dict]:
|
||||
return spans
|
||||
|
||||
|
||||
def new_input_tokens(activities: list[dict]) -> int | None:
|
||||
"""Fed-in tokens of one call chain, counted once: each call's prompt beyond the
|
||||
previous call's final sequence, clamped at zero (verifiers' `min_new_input_tokens`)."""
|
||||
total = None
|
||||
previous = 0
|
||||
for span in sorted(activities, key=lambda span: span["call_index"]):
|
||||
if span.get("input_tokens") is None:
|
||||
continue
|
||||
prompt = span["input_tokens"] + (span.get("cached_tokens") or 0)
|
||||
total = (total or 0) + max(0, prompt - previous)
|
||||
previous = prompt + (span.get("output_tokens") or 0)
|
||||
return total
|
||||
|
||||
|
||||
def timeline_lane(
|
||||
trace: dict,
|
||||
trace_index: int,
|
||||
@@ -1034,14 +1044,15 @@ def timeline_lane(
|
||||
values = [span[field] for span in activities if isinstance(span.get(field), (int, float))]
|
||||
return sum(values) if values else None
|
||||
|
||||
input_tokens = total("input_tokens")
|
||||
cached_tokens = total("cached_tokens")
|
||||
output_tokens = total("output_tokens")
|
||||
reasoning_tokens = total("reasoning_tokens")
|
||||
total_input_tokens = input_tokens + (cached_tokens or 0) if input_tokens is not None else None
|
||||
total_tokens = (
|
||||
total_input_tokens + output_tokens if total_input_tokens is not None and output_tokens is not None else None
|
||||
)
|
||||
if branch:
|
||||
input_tokens = new_input_tokens(activities)
|
||||
else:
|
||||
# the trace counts input on shared branch prefixes once; its call list
|
||||
# interleaves branches, so the lane's spans cannot reproduce that
|
||||
input_tokens = trace.get("num_input_tokens")
|
||||
output_tokens = trace.get("num_output_tokens", output_tokens)
|
||||
total_tokens = input_tokens + output_tokens if input_tokens is not None and output_tokens is not None else None
|
||||
context_lengths = [
|
||||
(span.get("input_tokens") or 0) + (span.get("cached_tokens") or 0)
|
||||
for span in activities
|
||||
@@ -1060,14 +1071,11 @@ def timeline_lane(
|
||||
"usage": {
|
||||
"model_calls": len(activities),
|
||||
"input_tokens": input_tokens,
|
||||
"cached_tokens": cached_tokens,
|
||||
"total_input_tokens": total_input_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
"latest_context_tokens": context_lengths[-1] if context_lengths else None,
|
||||
"max_context_tokens": max(context_lengths, default=None),
|
||||
"total_tokens": total_tokens,
|
||||
"cost": total("cost"),
|
||||
"cost": total("cost") if branch else (trace.get("usage") or {}).get("cost"),
|
||||
},
|
||||
"spans": spans,
|
||||
}
|
||||
|
||||
@@ -3781,7 +3781,9 @@ async function openEpisode(line, target = {}) {
|
||||
episode._hasTokens = withTokens;
|
||||
episode._hasRendered = withRendered;
|
||||
currentEpisode = episode;
|
||||
currentTraceIdx = target.traceId ? episode.traces.findIndex((trace) => trace.id === target.traceId) : target.trace ?? 0;
|
||||
currentTraceIdx = target.traceId
|
||||
? episode.traces.findIndex((trace) => trace.id === target.traceId)
|
||||
: target.trace ?? traceOrder(episode.traces)[0] ?? 0;
|
||||
currentBranchIdx = target.branch ?? 0;
|
||||
currentEvidenceView = target.evidence ?? null;
|
||||
traceView = currentEvidenceView == null ? preferredTraceView : "transcript";
|
||||
@@ -4561,6 +4563,25 @@ function metaRow(key, value, asId = false) {
|
||||
);
|
||||
}
|
||||
|
||||
/* mirrors verifiers Branch token counts: each call on the path adds its prompt beyond
|
||||
the previous call's final sequence (clamped at zero) plus its output */
|
||||
function branchTokens(trace, path) {
|
||||
const onPath = new Set(path);
|
||||
let input = null;
|
||||
let output = null;
|
||||
let previous = 0;
|
||||
for (const call of trace.calls || []) {
|
||||
if (!onPath.has(call.node) || !call.usage) continue;
|
||||
const usage = normalizedCallUsage(call.usage);
|
||||
if (usage.input == null) continue;
|
||||
const prompt = usage.input + (usage.cached ?? 0);
|
||||
input = (input ?? 0) + Math.max(0, prompt - previous);
|
||||
output = (output ?? 0) + (usage.output ?? 0);
|
||||
previous = prompt + (usage.output ?? 0);
|
||||
}
|
||||
return { input, output, total: input == null ? null : input + output };
|
||||
}
|
||||
|
||||
function renderMeta(ep, trace, branches) {
|
||||
const parts = [];
|
||||
const headline = (label, value) =>
|
||||
@@ -4586,33 +4607,41 @@ function renderMeta(ep, trace, branches) {
|
||||
}
|
||||
|
||||
if (trace) {
|
||||
const nodes = currentPath(trace, branches).map((i) => trace.nodes[i]);
|
||||
parts.push(`<div class="meta-sec">activity</div>`);
|
||||
parts.push(metaRow("messages", nodes.filter((n) => n.message).length));
|
||||
parts.push(metaRow("turns", nodes.filter((n) => n.sampled).length));
|
||||
parts.push(metaRow("branches", branches.length));
|
||||
parts.push(metaRow("tool calls", nodes.reduce((acc, n) => acc + (n.message?.tool_calls?.length || 0), 0)));
|
||||
const tokenRows = (input, output, total) => {
|
||||
if (input != null) parts.push(metaRow("input tokens", fmtCompact(input)));
|
||||
if (output != null) parts.push(metaRow("output tokens", fmtCompact(output)));
|
||||
if (total != null) parts.push(metaRow("total tokens", fmtCompact(total)));
|
||||
};
|
||||
const activityRows = (nodes, turns) => {
|
||||
parts.push(metaRow("messages", nodes.filter((n) => n.message).length));
|
||||
parts.push(metaRow("turns", turns));
|
||||
parts.push(metaRow("tool calls", nodes.reduce((acc, n) => acc + (n.message?.tool_calls?.length || 0), 0)));
|
||||
};
|
||||
|
||||
const traces = ep.traces || [];
|
||||
if (traces.length > 1) {
|
||||
parts.push(`<div class="meta-sec">episode</div>`);
|
||||
parts.push(metaRow("traces", traces.length));
|
||||
tokenRows(ep.num_input_tokens, ep.num_output_tokens, ep.num_total_tokens);
|
||||
}
|
||||
|
||||
parts.push(`<div class="meta-sec">trace</div>`);
|
||||
activityRows(trace.nodes || [], trace.num_turns);
|
||||
parts.push(metaRow("branches", trace.num_branches));
|
||||
const judgeRecords = Array.isArray(trace.info?.judge_calls) ? trace.info.judge_calls : [];
|
||||
if (judgeRecords.length) parts.push(metaRow("judge calls", judgeRecords.length));
|
||||
tokenRows(trace.num_input_tokens, trace.num_output_tokens, trace.num_total_tokens);
|
||||
const cost = trace.usage?.cost;
|
||||
if (cost != null) parts.push(metaRow("cost", fmtCost(cost)));
|
||||
|
||||
const contexts = (trace.calls || [])
|
||||
.map((call) => normalizedCallUsage(call.usage))
|
||||
.filter((current) => current.input != null)
|
||||
.map((current) => current.input + (current.cached ?? 0));
|
||||
const usage = { ...normalizedCallUsage(trace.usage ?? {}), maxContext: contexts.length ? Math.max(...contexts) : null };
|
||||
const totalInput = usage.input == null ? null : usage.input + (usage.cached ?? 0);
|
||||
const totalTokens = totalInput == null || usage.output == null ? null : totalInput + usage.output;
|
||||
const hasUsage = usage.input != null || usage.cached != null || usage.output != null;
|
||||
if (hasUsage) {
|
||||
parts.push(`<div class="meta-sec">usage</div>`);
|
||||
if (usage.input != null) parts.push(metaRow("input tokens", fmtCompact(usage.input)));
|
||||
if (usage.cached != null) parts.push(metaRow("cached input", fmtCompact(usage.cached)));
|
||||
if (totalInput != null) parts.push(metaRow("total input", fmtCompact(totalInput)));
|
||||
if (usage.output != null) parts.push(metaRow("output tokens", fmtCompact(usage.output)));
|
||||
if (usage.reasoning != null) parts.push(metaRow("reasoning tokens", fmtCompact(usage.reasoning)));
|
||||
if (usage.maxContext != null) parts.push(metaRow("max context length", fmtCompact(usage.maxContext)));
|
||||
if (usage.cost != null) parts.push(metaRow("cost", fmtCost(usage.cost)));
|
||||
if (totalTokens != null) parts.push(metaRow("total tokens", fmtCompact(totalTokens)));
|
||||
if (branches.length > 1 && currentBranchIdx !== -1) {
|
||||
const branchIdx = Math.min(currentBranchIdx, branches.length - 1);
|
||||
const path = branches[branchIdx] || [];
|
||||
const tokens = branchTokens(trace, path);
|
||||
parts.push(`<div class="meta-sec">branch ${branchIdx}</div>`);
|
||||
const nodes = path.map((i) => trace.nodes[i]);
|
||||
activityRows(nodes, nodes.filter((n) => n.sampled).length);
|
||||
tokenRows(tokens.input, tokens.output, tokens.total);
|
||||
}
|
||||
|
||||
parts.push(`<div class="meta-sec">state</div>`);
|
||||
@@ -4668,23 +4697,27 @@ function appendTimelineUsage(rows, usage, aggregate = false) {
|
||||
if (!usage) return;
|
||||
if (aggregate && usage.model_calls != null) rows.push(["model calls", fmtNum(usage.model_calls)]);
|
||||
if (usage.input_tokens != null) rows.push(["input tokens", fmtCompact(usage.input_tokens)]);
|
||||
if (usage.cached_tokens != null) rows.push(["cached input", fmtCompact(usage.cached_tokens)]);
|
||||
if (usage.total_input_tokens != null) rows.push(["total input", fmtCompact(usage.total_input_tokens)]);
|
||||
if (usage.output_tokens != null) rows.push(["output tokens", fmtCompact(usage.output_tokens)]);
|
||||
if (usage.reasoning_tokens != null) rows.push(["reasoning tokens", fmtCompact(usage.reasoning_tokens)]);
|
||||
if (usage.max_context_tokens != null) rows.push(["max context length", fmtCompact(usage.max_context_tokens)]);
|
||||
if (usage.total_tokens != null) rows.push(["total tokens", fmtCompact(usage.total_tokens)]);
|
||||
if (usage.cost != null) rows.push(["cost", fmtCost(usage.cost)]);
|
||||
}
|
||||
|
||||
// One call's input is its whole prompt, cached part included.
|
||||
function callTimelineUsage(span) {
|
||||
const input = span.input_tokens == null ? null : span.input_tokens + (span.cached_tokens || 0);
|
||||
return {
|
||||
input_tokens: input,
|
||||
output_tokens: span.output_tokens,
|
||||
total_tokens: input == null || span.output_tokens == null ? null : input + span.output_tokens,
|
||||
cost: span.cost,
|
||||
};
|
||||
}
|
||||
|
||||
function aggregateTimelineUsage(items) {
|
||||
const summedFields = [
|
||||
"model_calls",
|
||||
"input_tokens",
|
||||
"cached_tokens",
|
||||
"total_input_tokens",
|
||||
"output_tokens",
|
||||
"reasoning_tokens",
|
||||
"total_tokens",
|
||||
"cost",
|
||||
];
|
||||
@@ -4716,11 +4749,9 @@ function semanticCumulativeUsageRows(usage, compact = true) {
|
||||
const tokens = (value) => compact ? fmtCompact(value) : Math.round(value).toLocaleString();
|
||||
const rows = [];
|
||||
if (usage?.model_calls != null) rows.push(["model calls", fmtNum(usage.model_calls)]);
|
||||
if (usage?.total_tokens != null) rows.push(["cumulative processed", tokens(usage.total_tokens)]);
|
||||
if (usage?.input_tokens != null) rows.push(["uncached input", tokens(usage.input_tokens)]);
|
||||
if (usage?.cached_tokens != null) rows.push(["cached input", tokens(usage.cached_tokens)]);
|
||||
if (usage?.input_tokens != null) rows.push(["input", tokens(usage.input_tokens)]);
|
||||
if (usage?.output_tokens != null) rows.push(["output", tokens(usage.output_tokens)]);
|
||||
if (usage?.reasoning_tokens != null) rows.push(["reasoning", tokens(usage.reasoning_tokens)]);
|
||||
if (usage?.total_tokens != null) rows.push(["total", tokens(usage.total_tokens)]);
|
||||
if (usage?.cost != null) rows.push(["cost", fmtCost(usage.cost)]);
|
||||
return rows;
|
||||
}
|
||||
@@ -4740,17 +4771,7 @@ function timelineSpanHtml(lane, span, start, total) {
|
||||
];
|
||||
if (span.track === "activity") {
|
||||
if (span.shared) rows.push(["branch role", "shared prefix"]);
|
||||
const totalInput = span.input_tokens == null ? null : span.input_tokens + (span.cached_tokens || 0);
|
||||
appendTimelineUsage(rows, {
|
||||
input_tokens: span.input_tokens,
|
||||
cached_tokens: span.cached_tokens,
|
||||
total_input_tokens: totalInput,
|
||||
output_tokens: span.output_tokens,
|
||||
reasoning_tokens: span.reasoning_tokens,
|
||||
max_context_tokens: totalInput,
|
||||
total_tokens: totalInput == null || span.output_tokens == null ? null : totalInput + span.output_tokens,
|
||||
cost: span.cost,
|
||||
});
|
||||
appendTimelineUsage(rows, callTimelineUsage(span));
|
||||
} else {
|
||||
appendTimelineUsage(rows, lane.usage, true);
|
||||
}
|
||||
@@ -4857,7 +4878,6 @@ function semanticNodeKey(traceIndex, nodeIndex) {
|
||||
|
||||
function semanticNodeTip(event) {
|
||||
const span = event.span;
|
||||
const totalInput = span.input_tokens == null ? null : span.input_tokens + (span.cached_tokens || 0);
|
||||
const rows = [
|
||||
["agent", event.agent.label],
|
||||
["context", String(event.contextIndex)],
|
||||
@@ -4871,16 +4891,7 @@ function semanticNodeTip(event) {
|
||||
["training branch", event.compactionAttempt.accepted ? "included" : "excluded"]
|
||||
);
|
||||
}
|
||||
appendTimelineUsage(rows, {
|
||||
input_tokens: span.input_tokens,
|
||||
cached_tokens: span.cached_tokens,
|
||||
total_input_tokens: totalInput,
|
||||
output_tokens: span.output_tokens,
|
||||
reasoning_tokens: span.reasoning_tokens,
|
||||
max_context_tokens: totalInput,
|
||||
total_tokens: totalInput == null || span.output_tokens == null ? null : totalInput + span.output_tokens,
|
||||
cost: span.cost,
|
||||
});
|
||||
appendTimelineUsage(rows, callTimelineUsage(span));
|
||||
return timelineTipAttr({
|
||||
kind: event.compactionAttempt ? "compaction attempt" : "model call",
|
||||
title: event.compactionAttempt
|
||||
@@ -5510,7 +5521,7 @@ function semanticInspectorRows(rows) {
|
||||
function openSemanticCallInspector(event) {
|
||||
semanticSelection = { ...event, kind: "call" };
|
||||
const span = event.span;
|
||||
const totalInput = span.input_tokens == null ? null : span.input_tokens + (span.cached_tokens || 0);
|
||||
const usage = callTimelineUsage(span);
|
||||
const rows = [
|
||||
["agent", event.agent.label],
|
||||
["context", event.contextIndex],
|
||||
@@ -5518,8 +5529,9 @@ function openSemanticCallInspector(event) {
|
||||
["call", event.callIndex],
|
||||
["start", span.started_at == null ? "unknown" : timelineClock(span.started_at)],
|
||||
["duration", span.started_at == null || span.ended_at == null ? "—" : fmtDuration(span.ended_at - span.started_at)],
|
||||
["input", totalInput == null ? "n/a" : fmtCompact(totalInput)],
|
||||
["output", span.output_tokens == null ? "n/a" : fmtCompact(span.output_tokens)],
|
||||
["input", usage.input_tokens == null ? "n/a" : fmtCompact(usage.input_tokens)],
|
||||
["output", usage.output_tokens == null ? "n/a" : fmtCompact(usage.output_tokens)],
|
||||
["total", usage.total_tokens == null ? "n/a" : fmtCompact(usage.total_tokens)],
|
||||
["cost", span.cost == null ? "n/a" : fmtCost(span.cost)],
|
||||
];
|
||||
if (event.inferredContinuation) rows.splice(2, 0, ["lineage", "recovered from physical tool flow"]);
|
||||
@@ -5797,11 +5809,17 @@ async function setTraceView(view, { persist = true } = {}) {
|
||||
savePrefs();
|
||||
}
|
||||
|
||||
/* trace indices in the order their agents started */
|
||||
function traceOrder(traces) {
|
||||
const start = (trace) => trace.timing?.start ?? Infinity;
|
||||
return traces.map((_, i) => i).sort((a, b) => start(traces[a]) - start(traces[b]));
|
||||
}
|
||||
|
||||
function renderEpisode() {
|
||||
const ep = currentEpisode;
|
||||
if (!ep) return;
|
||||
const traces = ep.traces || [];
|
||||
if (currentTraceIdx >= traces.length) currentTraceIdx = 0;
|
||||
if (currentTraceIdx >= traces.length) currentTraceIdx = traceOrder(traces)[0] ?? 0;
|
||||
const trace = traces[currentTraceIdx];
|
||||
updateHash();
|
||||
const branches = trace ? traceBranches(trace) : [];
|
||||
@@ -5815,8 +5833,9 @@ function renderEpisode() {
|
||||
traceTabs.hidden = traces.length <= 1;
|
||||
traceTabs.innerHTML =
|
||||
traces.length > 1
|
||||
? traces
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.is_timeout ? " timeout" : trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
? traceOrder(traces)
|
||||
.map((i) => [traces[i], i])
|
||||
.map(([trace, i]) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.is_timeout ? " timeout" : trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.join("")
|
||||
: "";
|
||||
const branchTabs = $("#tm-branch-tabs");
|
||||
|
||||
@@ -53,19 +53,15 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
rewards, advantages = [], []
|
||||
input_tokens = rec.get("num_input_tokens")
|
||||
output_tokens = rec.get("num_output_tokens")
|
||||
turns = branches = 0
|
||||
branches = 0
|
||||
stop_condition = None
|
||||
truncated = False
|
||||
timeout = bool(rec.get("is_timeout"))
|
||||
reward_parts: dict[str, list[float]] = {}
|
||||
metric_parts: dict[str, list[float]] = {}
|
||||
timing: dict[str, float] = {}
|
||||
costs: list[float] = []
|
||||
for trace in rec.get("traces") or []:
|
||||
if isinstance(cost := (trace.get("usage") or {}).get("cost"), (int, float)):
|
||||
costs.append(cost)
|
||||
branches += trace.get("num_branches") or 0
|
||||
turns += trace.get("num_turns") or 0
|
||||
# skip reward-less seats (e.g. a judge) in the episode mean
|
||||
if trace.get("rewards") and isinstance(trace.get("reward"), (int, float)):
|
||||
rewards.append(trace["reward"])
|
||||
@@ -88,7 +84,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
|
||||
"metrics": {name: sum(v) / len(v) for name, v in metric_parts.items()},
|
||||
"timing": timing,
|
||||
"cost": sum(costs) if costs else None,
|
||||
"cost": (rec.get("usage") or {}).get("cost"),
|
||||
"line": line,
|
||||
"offset": offset,
|
||||
"id": rec.get("id"),
|
||||
@@ -104,7 +100,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
"advantage": sum(advantages) / len(advantages) if advantages else None,
|
||||
"input_tokens": input_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"turns": turns,
|
||||
"turns": rec.get("num_turns"),
|
||||
"branches": branches,
|
||||
"stop_condition": stop_condition,
|
||||
"truncated": truncated,
|
||||
|
||||
@@ -182,26 +182,21 @@ def message_text(message: dict[str, Any]) -> str:
|
||||
|
||||
def trace_row(record: dict[str, Any]) -> dict[str, Any]:
|
||||
"""The live table's view of one trace: phase, turns, tokens, cost, last message."""
|
||||
calls = record.get("calls") or []
|
||||
usage = [call.get("usage") or {} for call in calls]
|
||||
# The newest node is usually a tool result; the assistant's latest words say more.
|
||||
last = ""
|
||||
for node in reversed(record.get("nodes") or []):
|
||||
message = node.get("message") or {}
|
||||
if message.get("role") == "assistant" and (last := " ".join(message_text(message).split())):
|
||||
break
|
||||
costs = [u["cost"] for u in usage if u.get("cost") is not None]
|
||||
nodes = record.get("nodes") or []
|
||||
parents = {node.get("parent") for node in nodes if node.get("parent") is not None}
|
||||
return {
|
||||
"trace": record.get("id"),
|
||||
"agent": (record.get("agent") or {}).get("name", "agent"),
|
||||
"stage": stage(record),
|
||||
"turns": len(calls),
|
||||
"branches": sum(1 for index in range(len(nodes)) if index not in parents),
|
||||
"turns": record.get("num_turns"),
|
||||
"branches": record.get("num_branches"),
|
||||
"input_tokens": record.get("num_input_tokens"),
|
||||
"output_tokens": record.get("num_output_tokens"),
|
||||
"cost": sum(costs) if costs else None,
|
||||
"cost": (record.get("usage") or {}).get("cost"),
|
||||
"stop_condition": record.get("stop_condition"),
|
||||
"errors": len(record.get("errors") or []),
|
||||
"pending": len(record.get("pending") or []),
|
||||
|
||||
@@ -115,7 +115,7 @@ def test_semantic_timeline_projects_concurrent_fork_join() -> None:
|
||||
1,
|
||||
]
|
||||
assert [lane["usage"]["total_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
|
||||
260,
|
||||
140,
|
||||
130,
|
||||
130,
|
||||
]
|
||||
@@ -164,7 +164,7 @@ def test_semantic_timeline_starts_new_context_after_compaction() -> None:
|
||||
1,
|
||||
]
|
||||
assert [lane["usage"]["total_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
|
||||
310,
|
||||
190,
|
||||
70,
|
||||
]
|
||||
assert [lane["usage"]["latest_context_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
|
||||
|
||||
Reference in New Issue
Block a user