@sema-agent/core
Version:
Stateless, task-oriented AI agent core
52 lines (51 loc) • 2.65 kB
JavaScript
export const ACCOUNT_ORIGINS = Object.freeze(["run", "side_query"]);
export function accountRowOfResult(result) {
const { tokens, costMicroUsd, usageMissing, nested } = result.stats;
const known = costMicroUsd !== undefined && (nested === undefined || nested.costMicroUsd !== undefined);
return {
origin: "run",
tokens: tokens + (nested?.tokens ?? 0),
...(known ? { costMicroUsd: costMicroUsd + (nested?.costMicroUsd ?? 0) } : {}),
...(usageMissing === true ? { usageMissing: true } : {}),
};
}
function addRow(total, row) {
total.rows += 1;
total.tokens += row.tokens;
total.costMicroUsd = total.costMicroUsd === undefined || row.costMicroUsd === undefined ? undefined : total.costMicroUsd + row.costMicroUsd;
if (row.usageMissing === true)
total.usageMissing = true;
}
function settled(total) {
const { costMicroUsd, ...rest } = total;
return { ...rest, ...(costMicroUsd !== undefined ? { costMicroUsd } : {}) };
}
function checkedRow(row, index) {
const bad = (why) => {
throw new TypeError(`foldAccount: row ${index} ${why}`);
};
if (typeof row !== "object" || row === null)
return bad("is not an object");
const { origin, tokens, costMicroUsd, usageMissing } = row;
if (!ACCOUNT_ORIGINS.includes(origin))
bad(`has origin ${JSON.stringify(origin)}, outside ${JSON.stringify(ACCOUNT_ORIGINS)}`);
if (typeof tokens !== "number" || !Number.isFinite(tokens) || tokens < 0)
bad("has tokens that are not a finite non-negative number");
if (costMicroUsd !== undefined && (typeof costMicroUsd !== "number" || !Number.isInteger(costMicroUsd) || costMicroUsd < 0))
bad("has costMicroUsd that is not a non-negative integer of micro-USD (an unknown cost is an absent key; a USD figure is not micro-USD)");
if (usageMissing !== undefined && usageMissing !== true)
bad("has usageMissing other than true (an absent key is the only other reading)");
return { origin: origin, tokens: tokens, ...(costMicroUsd !== undefined ? { costMicroUsd: costMicroUsd } : {}), ...(usageMissing === true ? { usageMissing: true } : {}) };
}
export function foldAccount(rows) {
const empty = () => ({ rows: 0, tokens: 0, costMicroUsd: 0 });
const byOrigin = { run: empty(), side_query: empty() };
const all = empty();
let index = 0;
for (const raw of rows) {
const row = checkedRow(raw, index++);
addRow(byOrigin[row.origin], row);
addRow(all, row);
}
return { ...settled(all), byOrigin: { run: settled(byOrigin.run), side_query: settled(byOrigin.side_query) } };
}