/** * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ /** * @module bxc/embed/embedder * * Text embedders behind one interface. Index and query MUST use the same * embedder: every stored vector records `model`, and search ignores vectors * from another model. * * Resolution order of {@link defaultEmbedder}: * 1. `local` — sentence-transformers model running in-process through the * Rust bridge (no API key, batched, off the event loop); * 2. `remote` — Gemini, then OpenAI, embeddings when an API key is configured; * 3. `hashing` — 512-d feature hashing. Deterministic and free, but NOT * semantic ("car" and "automobile" are orthogonal); reported as such. */ import { getLocalTextEmbedding } from "../utils/vector.ts"; export type EmbeddingKind = "query" | "passage"; export interface Embedder { /** Stable model identifier stored next to every vector. */ readonly model: string; readonly dim: number; /** `true` when similarity reflects meaning (not just shared tokens). */ readonly semantic: boolean; embed(texts: readonly string[], kind?: EmbeddingKind): Promise; } /** Feature-hashing fallback (not semantic). */ export class HashingEmbedder implements Embedder { readonly model = "bxc-hashing-512"; readonly dim = 512; readonly semantic = false; async embed(texts: readonly string[]): Promise { return texts.map((text) => Float32Array.from(getLocalTextEmbedding(text, this.dim))); } } /** Gemini `text-embedding-004` (768-d) through the public REST API. */ export class GeminiEmbedder implements Embedder { readonly model = "gemini-text-embedding-004"; readonly dim = 768; readonly semantic = true; readonly #apiKey: string; constructor(apiKey: string) { this.#apiKey = apiKey; } async embed(texts: readonly string[], kind: EmbeddingKind = "passage"): Promise { const res = await fetch( `https://generativelanguage.googleapis.com/v1beta/models/text-embedding-004:batchEmbedContents?key=${this.#apiKey}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ requests: texts.map((text) => ({ model: "models/text-embedding-004", content: { parts: [{ text: text.slice(0, 8000) }] }, taskType: kind === "query" ? "RETRIEVAL_QUERY" : "RETRIEVAL_DOCUMENT", })), }), }, ); if (!res.ok) throw new Error(`Gemini embeddings failed: HTTP ${res.status}`); const json = (await res.json()) as { embeddings?: Array<{ values: number[] }> }; return (json.embeddings ?? []).map((e) => Float32Array.from(e.values)); } } /** OpenAI `text-embedding-3-small` (1536-d). */ export class OpenAIEmbedder implements Embedder { readonly model = "openai-text-embedding-3-small"; readonly dim = 1536; readonly semantic = true; readonly #apiKey: string; constructor(apiKey: string) { this.#apiKey = apiKey; } async embed(texts: readonly string[]): Promise { const res = await fetch("https://api.openai.com/v1/embeddings", { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${this.#apiKey}` }, body: JSON.stringify({ model: "text-embedding-3-small", input: texts.map((t) => t.slice(0, 8000)) }), }); if (!res.ok) throw new Error(`OpenAI embeddings failed: HTTP ${res.status}`); const json = (await res.json()) as { data?: Array<{ index: number; embedding: number[] }> }; return (json.data ?? []).sort((a, b) => a.index - b.index).map((d) => Float32Array.from(d.embedding)); } } let cached: Promise | null = null; /** Best available embedder (see module docs). Cached per process. */ export function defaultEmbedder(): Promise { cached ??= (async (): Promise => { if (Bun.env.BXC_EMBEDDER !== "hashing" && Bun.env.BXC_EMBEDDER !== "remote") { try { const { NativeEmbedder } = await import("./native-embedder.ts"); const native = await NativeEmbedder.tryLoad(); if (native) return native; } catch { // Native embeddings unavailable (bridge without model): fall through. } } if (Bun.env.BXC_EMBEDDER !== "hashing" && Bun.env.GEMINI_API_KEY) { return new GeminiEmbedder(Bun.env.GEMINI_API_KEY); } if (Bun.env.BXC_EMBEDDER !== "hashing" && Bun.env.OPENAI_API_KEY) { return new OpenAIEmbedder(Bun.env.OPENAI_API_KEY); } return new HashingEmbedder(); })(); return cached; } /** Reset the cached default (tests). */ export function resetDefaultEmbedder(): void { cached = null; }