UNPKG

@juspay/neurolink

Version:

The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002

83 lines (82 loc) • 3 kB
import { getProviderRules } from "./registry.js"; /** The value at a dotted path, or undefined. */ export function valueAtPath(source, path) { let current = source; for (const key of path.split(".")) { if (current === null || typeof current !== "object") { return undefined; } current = current[key]; } return current; } /** A wire's usage field map; throws when its rules file has none. */ export function getWireUsage(id) { const usage = getProviderRules(id).usage; if (!usage) { throw new Error(`Provider rules file "${id}.json" has no "usage" block`); } return usage; } /** Each count the wire reported, exactly as reported (undefined when absent). */ export function readWireUsage(wire, usage) { const read = (path) => path === undefined ? undefined : valueAtPath(usage, path); return { input: read(wire.input), output: read(wire.output), total: read(wire.total), cacheRead: read(wire.cacheRead), reasoning: read(wire.reasoning), }; } /** * Split `part` out of a `total` that already contains it: `rest` is the * remainder (never below 0) and `part` is clamped to the total, since some * gateways report a part larger than its total. */ export function splitIncludedCount(total, part) { return { rest: Math.max(0, total - part), part: Math.min(part, total) }; } /** {@link splitIncludedCount}, passing both through when either is missing. */ export function splitIncludedPart(total, part) { if (total === undefined || part === undefined) { return { rest: total, part }; } return splitIncludedCount(total, part); } /** Output billed at the output rate: reasoning is added when the wire reports it apart. */ export function outputWithReasoning(wire, output, reasoning) { return wire.reasoningInOutput ? output : output + (reasoning ?? 0); } /** A named count dialect from a rules file; throws when it is missing. */ export function getUsageDialect(id, name) { const dialect = getProviderRules(id).usageDialects?.[name]; if (!dialect) { throw new Error(`Provider rules file "${id}.json" has no usageDialects.${name}`); } return dialect; } /** Prompt, completion and total counts read through a dialect (see ProviderUsageCountDialect). */ export function readUsageCounts(dialect, source) { const pick = (paths) => { let value; for (const path of paths) { value = valueAtPath(source, path); if (dialect.pick === "truthy" ? value : value !== undefined && value !== null) { return value; } } return value; }; const promptTokens = Number(pick(dialect.input)) || 0; const completionTokens = Number(pick(dialect.output)) || 0; return { promptTokens, completionTokens, total: Number(pick(dialect.total)) || promptTokens + completionTokens, }; }