BYOK provider embeddings (wave 6 chunk B): kill local transformers
Replace the @huggingface/transformers local embedder (~316MB ONNX cache) with an EmbeddingPort seam: graph.embeddingModel (nullable "provider:id" slug) selects an OpenRouter/OpenAI/Gemini adapter, resolved fresh per call from settings + the auth store so key rotations land immediately. - src/server/embeddings.ts rewritten: slug grammar, injected-fetch adapters (OpenRouter input_type, Gemini taskType batching, OpenAI index-ordered rows), honest resolution (null = skip-with-info, set model with missing key = honest error), embedNewNodes with model-change re-embed wipe + ghost pruning + usage steps, federated catalog (OpenRouter /api/v1/embeddings/models — VERIFIED live, the inverse path 404s; OpenAI text-embedding- filter; Gemini embedContent filter). - GET /api/models/embeddings: federated catalog, empty when no keys. - Extraction tail records stages.embedding usage into the run's money channel; EMBEDDING_PRICES overlay in core/prices.ts (outside the sync-generated block), callCost falls back to it; cost-summary folds the fourth stage; graph-context injection resolves its embedder per run, fails honestly when unconfigured, records query tokens. - Settings: GraphSettings.embeddingModel (null factory), section parser validates slug shape (id may contain colons — OpenRouter :free suffixes, live catalog fact). - Removal: @huggingface/transformers uninstalled, PATHS.modelCache and onnx tracing entries deleted, @huggingface tracing-excludes guard added, stale sharp/libvips comments updated to historical. Live-verified on port 3004: catalog federates 36 rows (33 OpenRouter + 3 OpenAI), embedNewNodes embedded 10 nodes via the free liquid/lfm-2.5 model (dim 1024, 435 prompt tokens, 1 call, $0), settings PUT rejects bad slugs with 400. Gates: typecheck, lint, 895/895 tests, build.
This commit is contained in:
@@ -108,6 +108,10 @@ export interface ExtractionRunUsage {
|
||||
stages: {
|
||||
extractor: ExtractionStageUsage;
|
||||
auditor: ExtractionStageUsage;
|
||||
/** Wave 6 (2026-09-23): the provider-embedding tail — present only
|
||||
* when an embedding model is configured and the run embedded
|
||||
* (local embeddings were free, so this post-dates them). */
|
||||
embedding?: ExtractionStageUsage;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -55,10 +55,12 @@ export interface GraphCostSummary {
|
||||
totalDollars: number;
|
||||
/** Runs where EVERY stage was unpriced (totalDollars excludes them). */
|
||||
unpricedRuns: number;
|
||||
/** The three billable pipeline stages (merger/embedder are free). */
|
||||
/** The billable pipeline stages (wave 6: the embedder became one —
|
||||
* provider embeddings cost money; merger is the only free stage). */
|
||||
stages: {
|
||||
extraction: StageCost;
|
||||
audit: StageCost;
|
||||
embedding: StageCost;
|
||||
naming: StageCost;
|
||||
};
|
||||
/** Newest first, capped at `recentCap` (default 10). */
|
||||
@@ -113,6 +115,7 @@ function mergeTokens(into: CallUsage, steps: readonly CallUsage[]): void {
|
||||
export function graphCostSummary(input: CostSummaryInput): GraphCostSummary {
|
||||
const extraction = emptyStage();
|
||||
const audit = emptyStage();
|
||||
const embedding = emptyStage();
|
||||
const naming = emptyStage();
|
||||
const runs: RecentRun[] = [];
|
||||
|
||||
@@ -131,10 +134,25 @@ export function graphCostSummary(input: CostSummaryInput): GraphCostSummary {
|
||||
if (audDollars === null) audit.unpricedRuns++;
|
||||
else audit.dollars += audDollars;
|
||||
|
||||
// Run-level: null only when BOTH stages are unpriced.
|
||||
const priced = extDollars ?? 0;
|
||||
const runDollars = extDollars === null && audDollars === null ? null : priced + (audDollars ?? 0);
|
||||
const allSteps = [...stages.extractor.steps, ...stages.auditor.steps];
|
||||
// Wave 6: the embedding tail — present only when an embedding model
|
||||
// ran (absent stage = the run embedded nothing, never "free").
|
||||
let embDollars: number | null = null;
|
||||
let embSteps: CallUsage[] = [];
|
||||
if (stages.embedding) {
|
||||
embedding.runs++;
|
||||
embSteps = stages.embedding.steps;
|
||||
mergeTokens(embedding.tokens, embSteps);
|
||||
embDollars = stageDollars(stages.embedding.model, embSteps);
|
||||
if (embDollars === null) embedding.unpricedRuns++;
|
||||
else embedding.dollars += embDollars;
|
||||
}
|
||||
|
||||
// Run-level: null only when EVERY stage is unpriced.
|
||||
const allStages: Array<number | null> = [extDollars, audDollars, embDollars];
|
||||
const runDollars = allStages.every((d) => d === null)
|
||||
? null
|
||||
: allStages.reduce<number>((a, d) => a + (d ?? 0), 0);
|
||||
const allSteps = [...stages.extractor.steps, ...stages.auditor.steps, ...embSteps];
|
||||
runs.push({
|
||||
startedAt: run.startedAt,
|
||||
at: run.at,
|
||||
@@ -177,9 +195,9 @@ export function graphCostSummary(input: CostSummaryInput): GraphCostSummary {
|
||||
// A run is "unpriced" when it billed nothing countable at all.
|
||||
const unpricedRuns = runs.filter((r) => r.dollars === null).length;
|
||||
return {
|
||||
totalDollars: extraction.dollars + audit.dollars + naming.dollars,
|
||||
totalDollars: extraction.dollars + audit.dollars + embedding.dollars + naming.dollars,
|
||||
unpricedRuns,
|
||||
stages: { extraction, audit, naming },
|
||||
stages: { extraction, audit, embedding, naming },
|
||||
runs: capped,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -243,3 +243,49 @@ export interface AuthStore {
|
||||
/** Remove one VAR if present (absent = no-op, still a silent success). */
|
||||
deleteAuthVar(name: string): void;
|
||||
}
|
||||
|
||||
// ─── EmbeddingPort — BYOK provider embeddings (wave 6, 2026-09-23) ───────────
|
||||
|
||||
/**
|
||||
* The provider-embedding seam (the local transformers embedder died with
|
||||
* this wave): vectors come from the user's keyed provider — OpenRouter,
|
||||
* OpenAI, or Google — named by graph.embeddingModel ("provider:id", null =
|
||||
* honestly off: embedding/clustering/injection skip with an info log).
|
||||
*
|
||||
* Owner decisions (2026-09-23) baked in:
|
||||
* - The adapters are resolved FRESH per call from the setting + the auth
|
||||
* store (key rotations land immediately — the search port's treatment).
|
||||
* - Vectors are stored as the provider returns them (default dims, no
|
||||
* truncation, no normalization); the ledger is self-describing on
|
||||
* model + dim, and any model change voids it (full re-embed).
|
||||
* - Usage (prompt tokens) flows back to the money channel: adapters
|
||||
* report it, the caller records it as a CallUsage step.
|
||||
*
|
||||
* Pure types only (browser-safe): the adapters are server-side
|
||||
* (src/server/embeddings.ts) and arrive as injected dependencies.
|
||||
*/
|
||||
|
||||
/** Which side of retrieval the text is — providers bill identically but
|
||||
* quality-optimize differently (OpenRouter's input_type, Gemini's
|
||||
* taskType); every input in one call shares the task. */
|
||||
export type EmbeddingTask = "document" | "query";
|
||||
|
||||
/** One embedding batch's result: vectors in input order, the model's
|
||||
* identity + dim (the ledger stamps), and the provider-reported prompt
|
||||
* token count (undefined = provider didn't report; cost stays honest
|
||||
* "—" via the existing unpriced path). */
|
||||
export interface EmbeddingResult {
|
||||
vectors: number[][];
|
||||
/** The full "provider:id" slug — ledger/cost keys use it verbatim. */
|
||||
model: string;
|
||||
dim: number;
|
||||
promptTokens?: number;
|
||||
}
|
||||
|
||||
/** A live provider embedding adapter. `embed` throws on failure (adapters
|
||||
* map HTTP errors to clear Error messages); callers treat failure as
|
||||
* non-fatal per the extraction contract. */
|
||||
export interface EmbeddingPort {
|
||||
model: string;
|
||||
embed(texts: readonly string[], task: EmbeddingTask): Promise<EmbeddingResult>;
|
||||
}
|
||||
|
||||
+26
-1
@@ -2752,6 +2752,30 @@ export const CONTEXT_LIMITS: Record<string, number> = {
|
||||
|
||||
// ─── Pure helpers (folds + cost inference) ───────────────────────────────────
|
||||
|
||||
// ─── Embedding prices (wave 6, 2026-09-23) ─────────────────────────────────
|
||||
|
||||
/** Hand-maintained BYOK embedding prices, USD per 1M INPUT tokens — the
|
||||
* sync script never touches this block (pi-ai's catalogs carry no
|
||||
* embedding models, so the generated PRICES table has none of these).
|
||||
* VERIFIED against provider pricing pages 2026-09-23: OpenAI's model
|
||||
* docs ($0.02 3-small / $0.13 3-large / $0.10 ada-002), Google's pricing
|
||||
* page ($0.15 gemini-embedding-001 / $0.20 Gemini Embedding 2 text),
|
||||
* OpenRouter passes provider pricing through. output: 0 — embeddings
|
||||
* emit no output tokens. Unlisted models stay unpriced ("—", never
|
||||
* zero); tokens still get captured. */
|
||||
export const EMBEDDING_PRICES: Record<string, ModelPrice> = {
|
||||
"openai:text-embedding-3-small": { input: 0.02, output: 0 },
|
||||
"openai:text-embedding-3-large": { input: 0.13, output: 0 },
|
||||
"openai:text-embedding-ada-002": { input: 0.1, output: 0 },
|
||||
"google:gemini-embedding-001": { input: 0.15, output: 0 },
|
||||
"google:gemini-embedding-2": { input: 0.2, output: 0 },
|
||||
"openrouter:openai/text-embedding-3-small": { input: 0.02, output: 0 },
|
||||
"openrouter:openai/text-embedding-3-large": { input: 0.13, output: 0 },
|
||||
"openrouter:openai/text-embedding-ada-002": { input: 0.1, output: 0 },
|
||||
"openrouter:google/gemini-embedding-001": { input: 0.15, output: 0 },
|
||||
};
|
||||
|
||||
|
||||
/** Sum a list of per-step usages into one CallUsage. A field stays
|
||||
* undefined when EVERY step left it unreported — absent is not zero. */
|
||||
export function sumSteps(steps: readonly CallUsage[]): CallUsage {
|
||||
@@ -2773,7 +2797,8 @@ export function callCost(
|
||||
usage: { inputTokens?: number; outputTokens?: number; cacheReadTokens?: number; cacheWriteTokens?: number },
|
||||
model: string,
|
||||
): number | null {
|
||||
const price = PRICES[model];
|
||||
// Wave 6: the hand-maintained embedding overlay backs the lookup too.
|
||||
const price = PRICES[model] ?? EMBEDDING_PRICES[model];
|
||||
if (!price) return null;
|
||||
if (usage.inputTokens === undefined || usage.outputTokens === undefined) return null;
|
||||
const cacheRead = usage.cacheReadTokens ?? 0;
|
||||
|
||||
@@ -201,6 +201,9 @@ export function resolveSettings(record: UserSettings | null): EffectiveSettings
|
||||
embedding: graph.embedding ?? FACTORY_SETTINGS.graph.embedding,
|
||||
clustering: graph.clustering ?? FACTORY_SETTINGS.graph.clustering,
|
||||
labeling: graph.labeling ?? FACTORY_SETTINGS.graph.labeling,
|
||||
// BYOK (wave 6): null is the factory floor and a VALID resolved
|
||||
// value — ?? only fills the absent case, null passes through.
|
||||
embeddingModel: graph.embeddingModel ?? FACTORY_SETTINGS.graph.embeddingModel,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
+16
-1
@@ -251,6 +251,13 @@ export interface GraphSettings {
|
||||
clustering?: boolean;
|
||||
/** The LLM cluster-namer (needs clustering). */
|
||||
labeling?: boolean;
|
||||
/** BYOK embeddings (wave 6, 2026-09-23): the provider embedding model
|
||||
* as a "provider:id" slug (openrouter:…, openai:…, google:…). null =
|
||||
* no model — embedding/clustering/injection skip honestly (info log,
|
||||
* graph stays textual); no factory floor exists. Keys live in the auth
|
||||
* store, resolved fresh per call. A model CHANGE re-embeds everything
|
||||
* (the ledger's staleness semantics). */
|
||||
embeddingModel?: string | null;
|
||||
}
|
||||
|
||||
/** THE record. Every section optional (delta); unknown top-level keys are
|
||||
@@ -303,7 +310,7 @@ export const FACTORY_SETTINGS: FactorySettings = {
|
||||
sessionNameSerif: true,
|
||||
mdRendering: { headingWeight: 900, boldColor: null, italicColor: null },
|
||||
},
|
||||
graph: { enabled: true, embedding: true, clustering: true, labeling: true },
|
||||
graph: { enabled: true, embedding: true, clustering: true, labeling: true, embeddingModel: null },
|
||||
};
|
||||
|
||||
// ─── Sanitizer ─────────────────────────────────────────────────────────────
|
||||
@@ -453,6 +460,14 @@ function sanitizeGraph(raw: Record<string, unknown>): GraphSettings {
|
||||
if (clustering !== undefined) out.clustering = clustering;
|
||||
const labeling = boolOrDrop(raw.labeling);
|
||||
if (labeling !== undefined) out.labeling = labeling;
|
||||
// BYOK embeddings (wave 6): null or a provider-qualified slug; anything
|
||||
// else (bad type, bad shape) DROPS to absent — an invalid write never
|
||||
// becomes a live model (the PUT parser 400s it first; this is the
|
||||
// read-side belt-and-suspenders for hand-edited files).
|
||||
if (raw.embeddingModel === null) out.embeddingModel = null;
|
||||
else if (typeof raw.embeddingModel === "string" && /^\S+:\S+$/.test(raw.embeddingModel)) {
|
||||
out.embeddingModel = raw.embeddingModel;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user