openai.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. /**
  2. * openai.ts - OpenAI-compatible HTTP embedding provider
  3. *
  4. * Talks to any endpoint that implements `POST /v1/embeddings` with the OpenAI
  5. * shape: request `{model, input: string|string[]}`, response
  6. * `{data: [{embedding: number[], index: number}, ...]}`.
  7. *
  8. * Used by qmd to delegate embeddings to an approved commercial HTTPS API.
  9. *
  10. * Features:
  11. * - Batches input in groups of ≤64 (configurable via QMD_EMBED_BATCH_SIZE)
  12. * - Retries 429 / 503 with exponential backoff (1s, 4s, 16s)
  13. * - 4xx (non-429) → no retry, count as failure
  14. * - Circuit breaker: >50% failures in a 60s window → OPEN for 5 min,
  15. * callers receive failures; local fallback is forbidden
  16. * - Per-call timeout via AbortSignal (default QMD_EMBED_TIMEOUT_MS=30000)
  17. * - Healthcheck via `GET /health` if available, else a probe embed call
  18. */
  19. import os from "node:os";
  20. // ─────────────────────────── Configuration ───────────────────────────────────
  21. /**
  22. * Default batch size — most OpenAI-compatible embedding endpoints accept up to
  23. * 2048 inputs per call but for memory and latency we cap at 64.
  24. */
  25. export const DEFAULT_BATCH_SIZE = 64;
  26. /**
  27. * Default in-flight concurrency cap for `embedBatch`. The qmd-embed-worker
  28. * exposes a 4-way semaphore (`MAX_CONCURRENT_REQUESTS=4`) and idles at
  29. * queue-depth 1.0 under sequential clients (i-fkpnar9i baseline). Defaulting
  30. * to 4 matches the worker's advertised concurrency without overshooting the
  31. * GPU. Override per-deploy via `QMD_EMBED_CONCURRENCY`. Setting to 1 reverts
  32. * to the legacy sequential dispatch.
  33. */
  34. export const DEFAULT_CONCURRENCY = 4;
  35. /**
  36. * Default per-request timeout (30 s). embeddinggemma-300M on RTX 4090 takes
  37. * <500ms per batch of 64 in practice; 30s is a safe upper bound.
  38. */
  39. export const DEFAULT_TIMEOUT_MS = 30_000;
  40. /**
  41. * Retry backoff schedule (ms) for 429/503 responses. 3 attempts total
  42. * (initial + 2 retries) — aligns with issue spec "1s/4s/16s".
  43. */
  44. export const RETRY_BACKOFFS_MS = [1_000, 4_000, 16_000];
  45. /**
  46. * Circuit breaker — flips OPEN when error rate exceeds threshold within
  47. * window. While OPEN, every call fails fast so the caller can fall back.
  48. */
  49. export const CIRCUIT_WINDOW_MS = 60_000;
  50. export const CIRCUIT_OPEN_DURATION_MS = 5 * 60_000;
  51. export const CIRCUIT_FAILURE_RATE_THRESHOLD = 0.5;
  52. export const CIRCUIT_MIN_SAMPLES = 4;
  53. // ─────────────────────────── Helpers ─────────────────────────────────────────
  54. function defaultSleep(ms) {
  55. return new Promise((resolve) => setTimeout(resolve, ms));
  56. }
  57. /**
  58. * Build the advisory `X-AI-Caller` attribution header value (Oivo ai.mm.mk
  59. * "Observability-Driven Fleet Self-Improvement" rollout, Thread 1). Format
  60. * mirrors Oivo's `cli/src/shared/aiCallerHeader.ts` EXACTLY:
  61. * site=<file:line | tool file>; mc=<machine>; sid=<session-8char>;
  62. * comp=<component>; via=<logical-label>
  63. *
  64. * Advisory metadata ONLY — never an auth/authorization input. `mc`/`sid` come
  65. * from the Oivo fleet env when qmd runs as a delegated embedder; both degrade
  66. * to `-`/short-hostname safely when qmd runs standalone. Values are sanitized
  67. * (`;` + control chars stripped, capped at 120) so a pathological env value can
  68. * never break the header grammar.
  69. */
  70. function aiCallerHeaderValue(via) {
  71. const clean = (raw, fallback) => {
  72. if (raw == null)
  73. return fallback;
  74. let out = "";
  75. for (const ch of String(raw)) {
  76. const code = ch.charCodeAt(0);
  77. out += code < 32 || code === 127 || ch === ";" ? " " : ch;
  78. }
  79. const collapsed = out.replace(/\s+/g, " ").trim();
  80. return (collapsed || fallback).slice(0, 120);
  81. };
  82. let mc = (process.env.OIVO_MACHINE_NAME ?? "").trim();
  83. if (!mc) {
  84. try {
  85. mc = os.hostname().split(".")[0] || "unknown";
  86. }
  87. catch {
  88. mc = "unknown";
  89. }
  90. }
  91. const sid = (process.env.OIVO_SESSION_ID || process.env.CLAUDE_CODE_SESSION_ID || "-").slice(0, 8);
  92. return `site=src/embedding/openai.ts; mc=${clean(mc, "unknown")}; sid=${clean(sid, "-")}; comp=qmd; via=${clean(via, "-")}`;
  93. }
  94. /**
  95. * Build the merged AbortSignal for a single HTTP attempt: combines an
  96. * external `userSignal` (from caller / withLLMSession) with a per-attempt
  97. * timeout signal. Returns the merged signal AND the timeout id so the
  98. * caller can `clearTimeout` after the attempt completes (avoids leaks).
  99. */
  100. function buildAttemptSignal(userSignal, timeoutMs) {
  101. const ctrl = new AbortController();
  102. const timeoutId = setTimeout(() => {
  103. ctrl.abort(new Error(`Request timed out after ${timeoutMs}ms`));
  104. }, timeoutMs);
  105. // Don't keep process alive just for this timer
  106. if (typeof timeoutId === "object" && timeoutId !== null && "unref" in timeoutId) {
  107. timeoutId.unref();
  108. }
  109. const onUserAbort = () => ctrl.abort(userSignal?.reason);
  110. if (userSignal) {
  111. if (userSignal.aborted) {
  112. ctrl.abort(userSignal.reason);
  113. }
  114. else {
  115. userSignal.addEventListener("abort", onUserAbort, { once: true });
  116. }
  117. }
  118. const cleanup = () => {
  119. clearTimeout(timeoutId);
  120. if (userSignal)
  121. userSignal.removeEventListener("abort", onUserAbort);
  122. };
  123. return { signal: ctrl.signal, cleanup };
  124. }
  125. /**
  126. * Determine whether an HTTP status is retryable. 429 (Too Many Requests)
  127. * and 503 (Service Unavailable) are retried; 4xx (other than 429) are not.
  128. */
  129. export function isRetryableStatus(status) {
  130. return status === 429 || status === 503;
  131. }
  132. /**
  133. * Chunk an array into pieces of ≤ size each. `size` MUST be ≥ 1.
  134. */
  135. export function chunkArray(items, size) {
  136. if (size < 1)
  137. throw new Error(`chunkArray: size must be ≥ 1, got ${size}`);
  138. if (items.length <= size)
  139. return items.length === 0 ? [] : [items];
  140. const out = [];
  141. for (let i = 0; i < items.length; i += size) {
  142. out.push(items.slice(i, i + size));
  143. }
  144. return out;
  145. }
  146. // ─────────────────────────── Circuit Breaker ─────────────────────────────────
  147. /**
  148. * Sliding-window circuit breaker. Tracks the last N samples (min 4) over a
  149. * 60-second window; flips OPEN when failure rate exceeds 50%, then auto-
  150. * resets to HALF-OPEN after 5 minutes — at which point the next probe
  151. * decides whether to close (success) or re-open (failure).
  152. */
  153. export class CircuitBreaker {
  154. samples = [];
  155. state = "closed";
  156. openedAt = null;
  157. windowMs;
  158. openDurationMs;
  159. threshold;
  160. minSamples;
  161. now;
  162. constructor(opts = {}) {
  163. this.windowMs = opts.windowMs ?? CIRCUIT_WINDOW_MS;
  164. this.openDurationMs = opts.openDurationMs ?? CIRCUIT_OPEN_DURATION_MS;
  165. this.threshold = opts.threshold ?? CIRCUIT_FAILURE_RATE_THRESHOLD;
  166. this.minSamples = opts.minSamples ?? CIRCUIT_MIN_SAMPLES;
  167. this.now = opts.now ?? Date.now;
  168. }
  169. getState() {
  170. this.tickAutoReset();
  171. return this.state;
  172. }
  173. /**
  174. * Returns true when calls should be short-circuited (skip HTTP, fall back).
  175. * Side-effects: may transition OPEN → HALF-OPEN if the open window expired.
  176. */
  177. shouldFailFast() {
  178. return this.getState() === "open";
  179. }
  180. /** Record a successful call. */
  181. recordSuccess() {
  182. // Honor the time-based OPEN→HALF-OPEN transition before deciding what
  183. // to do with this sample. Without this, a success that lands AFTER the
  184. // open window expired would still see state==="open" and never close
  185. // the breaker (a probe call could only flip it via getState()).
  186. this.tickAutoReset();
  187. this.pushSample(true);
  188. if (this.state === "half-open") {
  189. this.state = "closed";
  190. this.openedAt = null;
  191. }
  192. }
  193. /** Record a failed call. May trigger OPEN. */
  194. recordFailure() {
  195. // Same reasoning as recordSuccess — apply lazy auto-reset before
  196. // classifying the sample.
  197. this.tickAutoReset();
  198. this.pushSample(false);
  199. if (this.state === "half-open") {
  200. // Probe failed — re-open
  201. this.state = "open";
  202. this.openedAt = this.now();
  203. return;
  204. }
  205. if (this.state === "closed")
  206. this.evaluate();
  207. }
  208. /** Force-reset the breaker (used by tests / admin) */
  209. reset() {
  210. this.samples = [];
  211. this.state = "closed";
  212. this.openedAt = null;
  213. }
  214. pushSample(ok) {
  215. const ts = this.now();
  216. this.samples.push({ ts, ok });
  217. // Drop samples outside the window
  218. const cutoff = ts - this.windowMs;
  219. while (this.samples.length > 0 && this.samples[0].ts < cutoff) {
  220. this.samples.shift();
  221. }
  222. }
  223. evaluate() {
  224. if (this.samples.length < this.minSamples)
  225. return;
  226. const failures = this.samples.filter((s) => !s.ok).length;
  227. const rate = failures / this.samples.length;
  228. if (rate > this.threshold) {
  229. this.state = "open";
  230. this.openedAt = this.now();
  231. }
  232. }
  233. tickAutoReset() {
  234. if (this.state === "open" && this.openedAt !== null) {
  235. if (this.now() - this.openedAt >= this.openDurationMs) {
  236. this.state = "half-open";
  237. }
  238. }
  239. }
  240. }
  241. // ─────────────────────────── Errors ──────────────────────────────────────────
  242. /**
  243. * Raised when the circuit breaker is OPEN and a call is short-circuited.
  244. * Callers (e.g. fallback wrapper) can catch this to switch to local provider.
  245. */
  246. export class CircuitOpenError extends Error {
  247. constructor(message = "OpenAIEmbeddingsProvider circuit is OPEN") {
  248. super(message);
  249. this.name = "CircuitOpenError";
  250. }
  251. }
  252. /**
  253. * Persistent (non-retryable) HTTP error from upstream. Includes status code.
  254. */
  255. export class HttpError extends Error {
  256. status;
  257. bodyPreview;
  258. constructor(status, bodyPreview) {
  259. super(`HTTP ${status}: ${bodyPreview.slice(0, 200)}`);
  260. this.name = "HttpError";
  261. this.status = status;
  262. this.bodyPreview = bodyPreview.slice(0, 1024);
  263. }
  264. }
  265. // ─────────────────────────── Provider ────────────────────────────────────────
  266. export class OpenAIEmbeddingsProvider {
  267. kind = "openai";
  268. endpoint;
  269. apiKey;
  270. modelId;
  271. upstreamModel;
  272. batchSize;
  273. concurrency;
  274. timeoutMs;
  275. fetchImpl;
  276. retryBackoffsMs;
  277. sleep;
  278. now;
  279. dimensions = undefined;
  280. lastError = undefined;
  281. breaker;
  282. constructor(config) {
  283. if (!config.endpoint) {
  284. throw new Error("OpenAIEmbeddingsProvider: endpoint is required");
  285. }
  286. this.endpoint = config.endpoint.replace(/\/+$/, "");
  287. this.apiKey = config.apiKey;
  288. this.modelId = config.modelId ?? "embeddinggemma";
  289. this.upstreamModel = config.upstreamModel ?? this.modelId;
  290. this.batchSize = config.batchSize ?? DEFAULT_BATCH_SIZE;
  291. this.concurrency = config.concurrency ?? DEFAULT_CONCURRENCY;
  292. this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
  293. this.fetchImpl = config.fetchImpl ?? globalThis.fetch;
  294. this.retryBackoffsMs = config.retryBackoffsMs ?? RETRY_BACKOFFS_MS;
  295. this.sleep = config.sleep ?? defaultSleep;
  296. this.now = config.now ?? Date.now;
  297. this.breaker = new CircuitBreaker({ now: this.now });
  298. if (!this.fetchImpl) {
  299. throw new Error("OpenAIEmbeddingsProvider: global fetch is unavailable. " +
  300. "Provide a `fetchImpl` config option (Node ≥18 ships fetch by default).");
  301. }
  302. if (this.batchSize < 1) {
  303. throw new Error(`OpenAIEmbeddingsProvider: batchSize must be ≥ 1, got ${this.batchSize}`);
  304. }
  305. if (this.concurrency < 1) {
  306. throw new Error(`OpenAIEmbeddingsProvider: concurrency must be ≥ 1, got ${this.concurrency}`);
  307. }
  308. }
  309. getModelId() {
  310. return this.modelId;
  311. }
  312. getDimensions() {
  313. return this.dimensions;
  314. }
  315. /**
  316. * Most recent per-chunk failure message (HTTP status + body preview, malformed
  317. * JSON, timeout, abort reason). Returns `undefined` after a successful call
  318. * or before the first call. See `EmbeddingProvider.getLastError`.
  319. */
  320. getLastError() {
  321. return this.lastError;
  322. }
  323. /** Endpoint URL configured at construction time — used by callers when
  324. * building error messages for failed first-chunk probes. */
  325. getEndpoint() {
  326. return this.endpoint;
  327. }
  328. async healthcheck(signal) {
  329. // Try GET /health first (worker exposes it). Fall back to probe embed.
  330. try {
  331. const { signal: attemptSig, cleanup } = buildAttemptSignal(signal, this.timeoutMs);
  332. try {
  333. const resp = await this.fetchImpl(`${this.endpoint}/health`, {
  334. method: "GET",
  335. headers: this.buildHeaders(),
  336. signal: attemptSig,
  337. });
  338. if (resp.ok) {
  339. return {
  340. ok: true,
  341. model: this.modelId,
  342. dimensions: this.dimensions,
  343. detail: `GET /health → ${resp.status}`,
  344. };
  345. }
  346. return {
  347. ok: false,
  348. model: this.modelId,
  349. detail: `GET /health → HTTP ${resp.status}`,
  350. };
  351. }
  352. finally {
  353. cleanup();
  354. }
  355. }
  356. catch (err) {
  357. // Endpoint may not implement /health — try a single embed probe instead.
  358. try {
  359. const probe = await this.embed("healthcheck", { signal });
  360. if (probe) {
  361. return {
  362. ok: true,
  363. model: this.modelId,
  364. dimensions: probe.embedding.length,
  365. detail: "embed probe ok",
  366. };
  367. }
  368. return {
  369. ok: false,
  370. model: this.modelId,
  371. detail: "embed probe returned null",
  372. };
  373. }
  374. catch (probeErr) {
  375. return {
  376. ok: false,
  377. model: this.modelId,
  378. detail: (err instanceof Error ? err.message : String(err)) +
  379. " | probe: " +
  380. (probeErr instanceof Error ? probeErr.message : String(probeErr)),
  381. };
  382. }
  383. }
  384. }
  385. async embed(text, options = {}) {
  386. const batch = await this.embedBatch([text], options);
  387. return batch[0] ?? null;
  388. }
  389. async embedBatch(texts, options = {}) {
  390. if (texts.length === 0)
  391. return [];
  392. if (this.breaker.shouldFailFast()) {
  393. throw new CircuitOpenError();
  394. }
  395. const chunks = chunkArray(texts, this.batchSize);
  396. const results = new Array(texts.length).fill(null);
  397. // Pre-compute the input-array starting position for each chunk so each
  398. // worker can write its slice of `results` independently — input order is
  399. // preserved end-to-end without a final re-sort step.
  400. const chunkStarts = new Array(chunks.length);
  401. {
  402. let cursor = 0;
  403. for (let i = 0; i < chunks.length; i++) {
  404. chunkStarts[i] = cursor;
  405. cursor += chunks[i].length;
  406. }
  407. }
  408. // Shared state across the worker pool. Each transition is final-write,
  409. // so plain JS scalars are safe — no atomics or locks needed since
  410. // workers only contend on these via cooperative-scheduled awaits.
  411. let nextChunkIdx = 0;
  412. let anySucceeded = false;
  413. let aborted = false;
  414. let circuitTrippedDuringRun = null;
  415. // Workers run as parallel async tasks pulling chunks off `nextChunkIdx`
  416. // until the queue is drained or one of the early-exit flags is set.
  417. // Concurrency is capped at min(this.concurrency, chunks.length) so we
  418. // don't spin up idle workers for tiny inputs.
  419. const workerCount = Math.min(this.concurrency, chunks.length);
  420. const dispatchOne = async () => {
  421. while (true) {
  422. if (aborted || circuitTrippedDuringRun)
  423. return;
  424. const idx = nextChunkIdx++;
  425. if (idx >= chunks.length)
  426. return;
  427. const chunk = chunks[idx];
  428. const start = chunkStarts[idx];
  429. // Honor abort/breaker BEFORE issuing the request so we don't waste
  430. // network for a dispatch we know will be discarded.
  431. if (options.signal?.aborted) {
  432. aborted = true;
  433. this.lastError = `aborted by caller${options.signal.reason ? `: ${String(options.signal.reason)}` : ""}`;
  434. return;
  435. }
  436. if (this.breaker.shouldFailFast()) {
  437. // Capture the breaker-open intent so we throw it AFTER all
  438. // currently in-flight workers settle, instead of leaking
  439. // half-completed results. The thrown error is a fresh instance
  440. // (matching legacy behavior).
  441. circuitTrippedDuringRun = new CircuitOpenError();
  442. return;
  443. }
  444. try {
  445. const embeddings = await this.requestWithRetry(chunk, options);
  446. for (let i = 0; i < chunk.length; i++) {
  447. const embedding = embeddings[i];
  448. if (embedding) {
  449. results[start + i] = {
  450. embedding,
  451. model: this.modelId,
  452. };
  453. anySucceeded = true;
  454. // Record dimensions on first success. Concurrent workers may
  455. // race on this assignment, but they all observe the same
  456. // length so the race is benign.
  457. if (this.dimensions === undefined) {
  458. this.dimensions = embedding.length;
  459. }
  460. }
  461. }
  462. this.breaker.recordSuccess();
  463. }
  464. catch (err) {
  465. this.breaker.recordFailure();
  466. if (err instanceof CircuitOpenError) {
  467. circuitTrippedDuringRun = err;
  468. return;
  469. }
  470. // Last-write-wins on lastError matches the legacy semantics — under
  471. // concurrency multiple workers may fail in the same call, but the
  472. // lastError just needs to surface "the most recent cause."
  473. this.lastError = this.formatErrorContext(err);
  474. if (process.env.QMD_EMBED_DEBUG) {
  475. process.stderr.write(`OpenAIEmbeddingsProvider: chunk failed (${err instanceof Error ? err.message : String(err)})\n`);
  476. }
  477. }
  478. }
  479. };
  480. await Promise.all(Array.from({ length: workerCount }, () => dispatchOne()));
  481. // If a worker observed `shouldFailFast()` mid-run, surface the error
  482. // after all in-flight workers have settled.
  483. if (circuitTrippedDuringRun)
  484. throw circuitTrippedDuringRun;
  485. // Clear lastError on a fully-successful sweep (every input got an embedding).
  486. if (anySucceeded && results.every((r) => r !== null)) {
  487. this.lastError = undefined;
  488. }
  489. return results;
  490. }
  491. async dispose() {
  492. // Nothing to release — fetch handles its own connection pooling.
  493. // Reset the breaker so a re-instantiation starts fresh.
  494. this.breaker.reset();
  495. }
  496. // ────────────────────── Internals ──────────────────────
  497. /**
  498. * Format a request-failure context string for `lastError`. Includes endpoint
  499. * + HTTP status + body preview when the error was an `HttpError`, otherwise
  500. * falls back to the message of the underlying error (or the value itself
  501. * when not an Error). Kept short — body preview is already capped at 1024
  502. * chars by `HttpError`, but we trim further here for the dimension-probe
  503. * thrown error which surfaces directly to users.
  504. */
  505. formatErrorContext(err) {
  506. if (err instanceof HttpError) {
  507. const preview = err.bodyPreview.replace(/\s+/g, " ").trim().slice(0, 240);
  508. return `endpoint=${this.endpoint}/v1/embeddings status=${err.status}${preview ? ` body="${preview}"` : ""}`;
  509. }
  510. if (err instanceof Error) {
  511. return `endpoint=${this.endpoint}/v1/embeddings error="${err.message}"`;
  512. }
  513. return `endpoint=${this.endpoint}/v1/embeddings error="${String(err)}"`;
  514. }
  515. buildHeaders() {
  516. const headers = {
  517. "Content-Type": "application/json",
  518. "Accept": "application/json",
  519. // Advisory caller attribution for the ai.mm.mk gateway (NULL-safe, never
  520. // auth). Single chokepoint for both /health and /v1/embeddings.
  521. "X-AI-Caller": aiCallerHeaderValue("embeddings"),
  522. };
  523. if (this.apiKey) {
  524. headers["Authorization"] = `Bearer ${this.apiKey}`;
  525. }
  526. return headers;
  527. }
  528. /**
  529. * Single HTTP request with retry on 429/503. Returns embeddings indexed
  530. * the same as `texts`. Throws on non-retryable failure or all attempts
  531. * exhausted.
  532. */
  533. async requestWithRetry(texts, options) {
  534. let lastErr = null;
  535. const maxAttempts = this.retryBackoffsMs.length + 1;
  536. for (let attempt = 0; attempt < maxAttempts; attempt++) {
  537. // Honor user abort BEFORE issuing the call (avoids wasted network)
  538. if (options.signal?.aborted) {
  539. throw new Error("aborted by caller");
  540. }
  541. try {
  542. return await this.requestOnce(texts, options);
  543. }
  544. catch (err) {
  545. lastErr = err;
  546. const retryable = err instanceof HttpError ? isRetryableStatus(err.status) : false;
  547. if (!retryable)
  548. throw err;
  549. if (attempt < this.retryBackoffsMs.length) {
  550. await this.sleep(this.retryBackoffsMs[attempt]);
  551. }
  552. }
  553. }
  554. // Exhausted retries → throw the last error so caller marks the chunk null
  555. throw lastErr ?? new Error("requestWithRetry exhausted");
  556. }
  557. /**
  558. * Issue one HTTP attempt to `POST /v1/embeddings`. Does NOT retry.
  559. */
  560. async requestOnce(texts, options) {
  561. const { signal: attemptSig, cleanup } = buildAttemptSignal(options.signal, this.timeoutMs);
  562. try {
  563. const body = JSON.stringify({
  564. model: options.model ?? this.upstreamModel,
  565. input: texts,
  566. });
  567. const resp = await this.fetchImpl(`${this.endpoint}/v1/embeddings`, {
  568. method: "POST",
  569. headers: this.buildHeaders(),
  570. body,
  571. signal: attemptSig,
  572. });
  573. if (!resp.ok) {
  574. const text = await resp.text().catch(() => "");
  575. throw new HttpError(resp.status, text);
  576. }
  577. let parsed;
  578. try {
  579. parsed = (await resp.json());
  580. }
  581. catch (err) {
  582. throw new Error(`OpenAIEmbeddingsProvider: malformed JSON from ${this.endpoint}/v1/embeddings: ${err instanceof Error ? err.message : String(err)}`);
  583. }
  584. if (!parsed || !Array.isArray(parsed.data)) {
  585. throw new Error(`OpenAIEmbeddingsProvider: response missing "data" array (got ${typeof parsed})`);
  586. }
  587. // Sort by index to match input order (in case server returns out-of-order).
  588. const out = new Array(texts.length);
  589. for (const item of parsed.data) {
  590. if (typeof item.index !== "number" ||
  591. item.index < 0 ||
  592. item.index >= texts.length) {
  593. throw new Error(`OpenAIEmbeddingsProvider: data item index out of range (${item.index}, expected 0..${texts.length - 1})`);
  594. }
  595. if (!Array.isArray(item.embedding)) {
  596. throw new Error(`OpenAIEmbeddingsProvider: data[${item.index}].embedding is not an array`);
  597. }
  598. out[item.index] = item.embedding;
  599. }
  600. // Sanity check — every slot must be filled
  601. for (let i = 0; i < texts.length; i++) {
  602. if (!out[i]) {
  603. throw new Error(`OpenAIEmbeddingsProvider: response missing embedding for index ${i}`);
  604. }
  605. }
  606. return out;
  607. }
  608. finally {
  609. cleanup();
  610. }
  611. }
  612. }