@copilotkit/runtime
Version:
<img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />
63 lines (61 loc) • 2.4 kB
JavaScript
require("reflect-metadata");
//#region src/agent/converters/usage.ts
const tokenCountKeys = [
"inputTokens",
"outputTokens",
"totalTokens",
"reasoningTokens",
"cachedInputTokens"
];
/** Returns a token count only when it is a safe, non-negative integer. */
function getTokenCount(value) {
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
}
/** Adds usage entries to a run, grouping and summing matching identities. */
function aggregateRunUsage(details, entries) {
for (const entry of entries) {
if (!tokenCountKeys.some((key) => entry[key] !== void 0)) continue;
details.usage ??= [];
const existing = details.usage.find((candidate) => candidate.provider === entry.provider && candidate.model === entry.model);
if (!existing) {
details.usage.push({ ...entry });
continue;
}
for (const key of tokenCountKeys) {
const value = entry[key];
if (value === void 0) continue;
const sum = (existing[key] ?? 0) + value;
if (Number.isSafeInteger(sum)) existing[key] = sum;
}
}
}
/** Copies standard AG-UI terminal usage into a run-level accumulator. */
function collectStandardRunFinishedDetails(event, details, fallbackIdentity = {}) {
if (typeof event.finishReason === "string") details.finishReason = event.finishReason;
if (!Array.isArray(event.usage)) return;
aggregateRunUsage(details, event.usage.flatMap((entry) => {
if (!isRecord(entry)) return [];
const normalized = {
provider: getNonEmptyString(entry.provider) ?? fallbackIdentity.provider,
model: getNonEmptyString(entry.model) ?? fallbackIdentity.model
};
for (const key of tokenCountKeys) normalized[key] = getTokenCount(entry[key]);
return [normalized];
}));
}
/** Narrows an unknown value to a string-keyed object. */
function isRecord(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
/** Returns a non-empty string identity without changing its value. */
function getNonEmptyString(value) {
return typeof value === "string" && value.length > 0 ? value : void 0;
}
//#endregion
exports.aggregateRunUsage = aggregateRunUsage;
exports.collectStandardRunFinishedDetails = collectStandardRunFinishedDetails;
exports.getNonEmptyString = getNonEmptyString;
exports.getTokenCount = getTokenCount;
exports.isRecord = isRecord;
exports.tokenCountKeys = tokenCountKeys;
//# sourceMappingURL=usage.cjs.map