mirror of
https://github.com/openclaw/openclaw.git
synced 2026-04-03 03:03:24 -04:00
refactor(subagents): share token usage formatting
This commit is contained in:
@@ -39,3 +39,58 @@ export function truncateLine(value: string, maxLength: number) {
|
||||
}
|
||||
return `${value.slice(0, maxLength).trimEnd()}...`;
|
||||
}
|
||||
|
||||
export type TokenUsageLike = {
|
||||
totalTokens?: unknown;
|
||||
inputTokens?: unknown;
|
||||
outputTokens?: unknown;
|
||||
};
|
||||
|
||||
export function resolveTotalTokens(entry?: TokenUsageLike) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof entry.totalTokens === "number" && Number.isFinite(entry.totalTokens)) {
|
||||
return entry.totalTokens;
|
||||
}
|
||||
const input = typeof entry.inputTokens === "number" ? entry.inputTokens : 0;
|
||||
const output = typeof entry.outputTokens === "number" ? entry.outputTokens : 0;
|
||||
const total = input + output;
|
||||
return total > 0 ? total : undefined;
|
||||
}
|
||||
|
||||
export function resolveIoTokens(entry?: TokenUsageLike) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const input =
|
||||
typeof entry.inputTokens === "number" && Number.isFinite(entry.inputTokens)
|
||||
? entry.inputTokens
|
||||
: 0;
|
||||
const output =
|
||||
typeof entry.outputTokens === "number" && Number.isFinite(entry.outputTokens)
|
||||
? entry.outputTokens
|
||||
: 0;
|
||||
const total = input + output;
|
||||
if (total <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
return { input, output, total };
|
||||
}
|
||||
|
||||
export function formatTokenUsageDisplay(entry?: TokenUsageLike) {
|
||||
const io = resolveIoTokens(entry);
|
||||
const promptCache = resolveTotalTokens(entry);
|
||||
const parts: string[] = [];
|
||||
if (io) {
|
||||
const input = formatTokenShort(io.input) ?? "0";
|
||||
const output = formatTokenShort(io.output) ?? "0";
|
||||
parts.push(`tokens ${formatTokenShort(io.total)} (in ${input} / out ${output})`);
|
||||
} else if (typeof promptCache === "number" && promptCache > 0) {
|
||||
parts.push(`tokens ${formatTokenShort(promptCache)} prompt/cache`);
|
||||
}
|
||||
if (typeof promptCache === "number" && io && promptCache > io.total) {
|
||||
parts.push(`prompt/cache ${formatTokenShort(promptCache)}`);
|
||||
}
|
||||
return parts.join(", ");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user