@sema-agent/core
Version:
Stateless, task-oriented AI agent core
135 lines (134 loc) • 8.3 kB
TypeScript
/**
* Cost computation (1.37). core never hardcodes provider pricing — a deployment injects it via
* `RunnerDeps.pricing` or each `Model.cost`. All prices are **absolute per-1M-token USD**, not
* multipliers: each provider's adapter precomputes its discount into an absolute value
* (OpenAI/DeepSeek: the cache-hit price; Anthropic's published prompt-caching rates: base×0.1 read / ×1.25 5min-write / ×2.0 1h-write).
*/
/** Per-1M-token absolute prices (USD) for a model. */
export interface ModelPricing {
inputPer1M: number;
outputPer1M: number;
/** Cache-read (hit) absolute price per 1M. Default 0 (treated as full-price input if absent). */
cacheReadPer1M?: number;
/** Cache-write 5-min-TTL absolute price per 1M (Anthropic's published rate: 1.25× the base input price). 0 elsewhere. */
cacheWritePer1M?: number;
/** Cache-write 1-hour-TTL absolute price per 1M (Anthropic's published rate: 2× the base input price). 0 elsewhere. */
cacheWriteLongPer1M?: number;
/**
* The FAST tier: the absolute rates of a call the provider served at fast speed (`Usage.speed: "fast"`), every column its
* own — not a multiple of the rates above (the reference's tiers differ column by column). A cache rate it leaves out charges
* that subset at the fast tier's OWN input rate (the cache law above, read inside this tier; never the standard cache rate).
* Absent ⇒ this table prices no fast-served call ({@link callRatesOf}: such a call is unpriced spend). Its own `fast` is not read.
*/
fast?: Omit<ModelPricing, "fast">;
}
/** A `Model.cost` declaration as the price reader reads it (per-1M absolute USD; `fast` = the fast tier, the same five columns). */
export interface ModelCostDeclaration {
input?: number;
output?: number;
cacheRead?: number;
cacheWrite?: number;
cacheWriteLong?: number;
fast?: {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
cacheWriteLong?: number;
};
}
/** A price table and whether it EXISTS ({@link isModelPriced}): `exists: false` ⇒ `table` is the all-zero stand-in, and every
* figure computed from it is unknown, not free. */
export interface PriceTable {
readonly table: ModelPricing;
readonly exists: boolean;
/** Where `table` was taken from: the deployment's entry for the model's id, or the model's own `cost` (also the stand-in when no table exists). */
readonly from: "deployment" | "model";
}
/**
* THE price table of a model — the one reading of where a model's prices come from: the deployment's entry for its id
* (`RunnerDeps.pricing`), else the model's own `cost`. Both tiers come from the table this picks; a tier is never taken from
* the other source. Every reader that prices a model, estimates its spend or judges its table asks here — and asks `from` which
* of the two it read, never the pricing record again.
*/
export declare function priceTableOf(model: {
id: string;
cost?: ModelCostDeclaration;
}, pricing: Record<string, ModelPricing> | undefined): PriceTable;
/**
* The rates ONE call is priced at: the table's fast tier for a call served at fast speed, the table's standard rates otherwise.
* `tierDeclared: false` ⇒ the call was served at fast speed and the table declares no fast tier (or one its judge refuses): the standard rates stand in,
* so the figure is a lower bound and the call is UNPRICED spend (the caller marks it as it marks a model with no table). An
* estimate made before a call reads the same tier for a call that will go at fast speed.
*/
export declare function callRatesOf(table: ModelPricing, servedFast: boolean): {
readonly rates: ModelPricing;
readonly tierDeclared: boolean;
};
/**
* What a model's price table gets wrong about the fast speed its entry serves (`servesFast`: `fastModeUnavailableFor`), or
* `undefined`. On a table that EXISTS, the tier such an entry declares is judged by the table judge ({@link malformedPricingField}'s
* fast leg), column by column; a tier left out is reported too (`missing`: every call served at fast speed on that table is unpriced
* — the door tells it, a bad tier it refuses). `where` is the member at fault as the caller wrote it (`RunnerDeps.pricing["id"].fast…`,
* or `cost.fast…` under the model's seat). Not judged: an entry that does not serve fast mode, a model with no table at all (unpriced already).
*/
export declare function fastTierFaultOf(model: {
id: string;
cost?: ModelCostDeclaration;
}, pricing: Record<string, ModelPricing> | undefined, servesFast: boolean): {
readonly where: string;
readonly missing: boolean;
readonly from: PriceTable["from"];
} | undefined;
/**
* Unified token counts for one task/turn, **already normalized** so `totalInputTokens` INCLUDES all
* cache tokens (matching OTel `gen_ai.usage.input_tokens`). `cacheReadTokens`/`cacheWriteTokens`/
* `cacheWriteTokensLong` are mutually exclusive PRICING BUCKETS of `totalInputTokens` — not the usage counts: a provider's write count
* covers both lifetimes and its one-hour part is a subset of it, and the accounting seat (`usageCostMicroUsd`) splits it into these.
*/
export interface TokenCounts {
totalInputTokens: number;
cacheReadTokens: number;
cacheWriteTokens: number;
cacheWriteTokensLong: number;
outputTokens: number;
}
/**
* Cost in **integer micro-USD** (1e-6 USD) — integer to avoid float-accumulation error in billing
* reconcile (Stripe/AWS-style). Convergent across providers: full-price input = `totalInputTokens`
* minus all cache tokens; cache read/write priced at their own absolute rates; output at its rate.
*
* DeepSeek (hit price as `cacheReadPer1M`, no cache-write) and OpenAI (no 1h write) fall out by their
* zero token counts; Anthropic uses all fields. This fixes P2 (cached charged at full price) by
* pricing the cache subset separately instead of trusting the brain's possibly-overstated cost total.
*/
export declare function computeCostMicroUsd(counts: TokenCounts, pricing: ModelPricing): number;
/**
* RB-368's predicate, single-sourced: does a price table EXIST for this model — an id-keyed
* `RunnerDeps.pricing` entry, or the model's own `cost` declaration? When neither does,
* `modelCostToPricing(undefined)` yields an all-zero table and every computed cost is a fabricated 0,
* indistinguishable from "declared free". Every consumer that must keep those apart (the disclosure faces
* that go absent rather than lie; the deployment $ governance window that refuses rather than charge a
* fabricated 0) asks HERE, so the two can never drift into two different answers.
*/
export declare function isModelPriced(model: {
id: string;
cost?: unknown;
}, pricing: Record<string, ModelPricing> | undefined): boolean;
/**
* The first UNEVALUABLE member of a price table (`"inputPer1M"`, …), or `undefined` when every declared
* price is a finite, non-negative number.
*
* {@link isModelPriced} answers "does a table EXIST", which is the RB-368 question. It is deliberately not
* the same question as "can this table price anything": a `NaN` rate silently computes a cost of ZERO (the
* `price && tokens` guard treats NaN as absent) and a negative rate computes a negative one, so a table of
* garbage looks priced and prices everything at nothing. Wherever a number from this table becomes a
* CEILING rather than a report, the caller must ask this too — a bad value has to be loud, never folded
* into a silent default.
*/
export declare function malformedPricingField(pricing: ModelPricing): string | undefined;
/** Map a vendor `Model.cost` (already per-1M absolute) to `ModelPricing`. A model that declares no one-hour write price
* (`cacheWriteLong`) gets its five-minute write price there: one-hour writes are priced like five-minute ones until a price says otherwise.
* The fast tier (`cost.fast`) maps by the same rule (only an ABSENT `cacheWriteLong` takes the five-minute rate), its rates as
* written: a missing or unreadable rate is not filled in, so {@link malformedPricingField} names it (`fast.inputPer1M`, …). */
export declare function modelCostToPricing(cost: ModelCostDeclaration | undefined): ModelPricing;