openai.d.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. * - 429 gets its own, larger retry budget and honours `Retry-After`
  14. * (header or `"Retry after 29s"` body text) — a shared gateway bucket
  15. * refilling in 30s must not exhaust a 1s/4s/16s schedule (i-yghj098h)
  16. * - Bulk lane (`embedBatch` with >1 input): a 429 pauses the WHOLE worker
  17. * pool for the advertised cooldown and halves in-flight concurrency
  18. * (AIMD), so reindex traffic yields the bucket to interactive callers
  19. * instead of contending head-on with them
  20. * - 4xx (non-429) → no retry, count as failure
  21. * - Circuit breaker: >50% failures in a 60s window → OPEN for 5 min,
  22. * callers receive failures; local fallback is forbidden
  23. * - Per-call timeout via AbortSignal (default QMD_EMBED_TIMEOUT_MS=30000)
  24. * - Healthcheck via `GET /health` if available, else a probe embed call
  25. */
  26. import type { EmbeddingProvider, ProviderEmbedOptions, ProviderEmbedding, ProviderHealth, ProviderKind } from "./provider.js";
  27. /**
  28. * Default batch size — most OpenAI-compatible embedding endpoints accept up to
  29. * 2048 inputs per call but for memory and latency we cap at 64.
  30. */
  31. export declare const DEFAULT_BATCH_SIZE = 64;
  32. /**
  33. * Default in-flight concurrency cap for `embedBatch`. The qmd-embed-worker
  34. * exposes a 4-way semaphore (`MAX_CONCURRENT_REQUESTS=4`) and idles at
  35. * queue-depth 1.0 under sequential clients (i-fkpnar9i baseline). Defaulting
  36. * to 4 matches the worker's advertised concurrency without overshooting the
  37. * GPU. Override per-deploy via `QMD_EMBED_CONCURRENCY`. Setting to 1 reverts
  38. * to the legacy sequential dispatch.
  39. */
  40. export declare const DEFAULT_CONCURRENCY = 4;
  41. /**
  42. * Default per-request timeout (30 s). embeddinggemma-300M on RTX 4090 takes
  43. * <500ms per batch of 64 in practice; 30s is a safe upper bound.
  44. */
  45. export declare const DEFAULT_TIMEOUT_MS = 30000;
  46. /**
  47. * Retry backoff schedule (ms) for 429/503 responses. 3 attempts total
  48. * (initial + 2 retries) — aligns with issue spec "1s/4s/16s".
  49. */
  50. export declare const RETRY_BACKOFFS_MS: readonly number[];
  51. /**
  52. * Rate-limit (429) retry budget, separate from `RETRY_BACKOFFS_MS`.
  53. *
  54. * A 429 is backpressure, not a fault: the shared ai.mm.mk gateway answers
  55. * `{"detail":"Rate limit exceeded (tokens). Retry after 29s."}` with observed
  56. * retry-after values of 7s/29s/30s, while the generic schedule waits at most
  57. * 1+4+16 = 21s in total. Bulk reindex runs therefore burned all three attempts
  58. * inside one bucket refill and reported the chunk as failed (i-yghj098h).
  59. * 429s get their own attempt count and always wait at least as long as the
  60. * server asked for, capped by `RATE_LIMIT_MAX_BACKOFF_MS`.
  61. */
  62. export declare const DEFAULT_RATE_LIMIT_RETRIES = 5;
  63. /** Upper bound on a single rate-limit wait, so a bogus Retry-After can't hang a run. */
  64. export declare const RATE_LIMIT_MAX_BACKOFF_MS = 60000;
  65. /** Fallback wait when a 429 carries no parseable Retry-After (doubles per attempt). */
  66. export declare const RATE_LIMIT_BASE_BACKOFF_MS = 5000;
  67. /**
  68. * Consecutive successful bulk requests before the lane additively recovers one
  69. * unit of concurrency after a 429-triggered halving (AIMD).
  70. */
  71. export declare const LANE_RECOVERY_STREAK = 8;
  72. /**
  73. * Circuit breaker — flips OPEN when error rate exceeds threshold within
  74. * window. While OPEN, every call fails fast so the caller can fall back.
  75. */
  76. export declare const CIRCUIT_WINDOW_MS = 60000;
  77. export declare const CIRCUIT_OPEN_DURATION_MS: number;
  78. export declare const CIRCUIT_FAILURE_RATE_THRESHOLD = 0.5;
  79. export declare const CIRCUIT_MIN_SAMPLES = 4;
  80. export type OpenAIProviderConfig = {
  81. /** Endpoint base URL — e.g. "https://ai.mm.mk" (no trailing slash) */
  82. endpoint: string;
  83. /** Optional bearer token sent as `Authorization: Bearer ...` */
  84. apiKey?: string;
  85. /**
  86. * Stable model identifier to report up via `getModelId()`.
  87. * Defaults to "embeddinggemma" to match qmd's existing DB rows.
  88. */
  89. modelId?: string;
  90. /**
  91. * Upstream model name sent in the HTTP request body. Often differs from
  92. * `modelId` (e.g. modelId="embeddinggemma" but upstream model="embeddinggemma:300m").
  93. */
  94. upstreamModel?: string;
  95. /** Batch size cap (default DEFAULT_BATCH_SIZE = 64) */
  96. batchSize?: number;
  97. /**
  98. * Max in-flight HTTP requests during a single `embedBatch` call. Default
  99. * `DEFAULT_CONCURRENCY=4` matches the worker semaphore. Set to 1 to force
  100. * legacy sequential dispatch (useful for benchmarks / regression bisect).
  101. */
  102. concurrency?: number;
  103. /** Per-request timeout in ms (default DEFAULT_TIMEOUT_MS = 30_000) */
  104. timeoutMs?: number;
  105. /** Custom fetch (for testing). Defaults to global `fetch`. */
  106. fetchImpl?: typeof fetch;
  107. /** Custom retry schedule (for testing). Defaults to RETRY_BACKOFFS_MS. */
  108. retryBackoffsMs?: readonly number[];
  109. /**
  110. * Extra retry attempts granted to 429 responses on top of the generic
  111. * schedule (default DEFAULT_RATE_LIMIT_RETRIES = 5, env
  112. * `QMD_EMBED_RATE_LIMIT_RETRIES`). Rate limits are backpressure, not faults.
  113. */
  114. rateLimitRetries?: number;
  115. /** Custom sleep impl (for testing). Defaults to setTimeout. */
  116. sleep?: (ms: number) => Promise<void>;
  117. /** Custom clock (for testing). Defaults to Date.now. */
  118. now?: () => number;
  119. };
  120. export type OpenAIEmbeddingsResponse = {
  121. object?: string;
  122. model?: string;
  123. data: Array<{
  124. object?: string;
  125. index: number;
  126. embedding: number[];
  127. }>;
  128. usage?: {
  129. prompt_tokens?: number;
  130. total_tokens?: number;
  131. };
  132. };
  133. /**
  134. * Circuit breaker state — exported for tests
  135. */
  136. export type CircuitState = "closed" | "open" | "half-open";
  137. /**
  138. * Traffic lane for a single `embedBatch` call. `bulk` = reindex traffic
  139. * (multi-input batch), which self-throttles via `BulkLaneGate` and is
  140. * attributed separately in `X-AI-Caller`. `interactive` = query-time embeds,
  141. * which are never made to wait behind a bulk cooldown.
  142. */
  143. export type EmbedLane = "interactive" | "bulk";
  144. /**
  145. * Determine whether an HTTP status is retryable. 429 (Too Many Requests)
  146. * and 503 (Service Unavailable) are retried; 4xx (other than 429) are not.
  147. */
  148. export declare function isRetryableStatus(status: number): boolean;
  149. /**
  150. * Extract the server-advertised cooldown from a rate-limited response.
  151. *
  152. * Two sources, in priority order:
  153. * 1. the standard `Retry-After` header — delta-seconds or an HTTP-date;
  154. * 2. the ai.mm.mk body text, which states the cooldown in prose only:
  155. * `{"detail":"Rate limit exceeded (tokens). Retry after 29s.", ...}`.
  156. *
  157. * Returns `undefined` when neither source yields a sane positive duration, so
  158. * the caller falls back to its own schedule. Values are clamped to
  159. * `RATE_LIMIT_MAX_BACKOFF_MS`.
  160. */
  161. export declare function parseRetryAfterMs(headerValue: string | null | undefined, bodyPreview?: string, now?: () => number): number | undefined;
  162. /**
  163. * Chunk an array into pieces of ≤ size each. `size` MUST be ≥ 1.
  164. */
  165. export declare function chunkArray<T>(items: T[], size: number): T[][];
  166. /**
  167. * Sliding-window circuit breaker. Tracks the last N samples (min 4) over a
  168. * 60-second window; flips OPEN when failure rate exceeds 50%, then auto-
  169. * resets to HALF-OPEN after 5 minutes — at which point the next probe
  170. * decides whether to close (success) or re-open (failure).
  171. */
  172. export declare class CircuitBreaker {
  173. private samples;
  174. private state;
  175. private openedAt;
  176. private readonly windowMs;
  177. private readonly openDurationMs;
  178. private readonly threshold;
  179. private readonly minSamples;
  180. private readonly now;
  181. constructor(opts?: {
  182. windowMs?: number;
  183. openDurationMs?: number;
  184. threshold?: number;
  185. minSamples?: number;
  186. now?: () => number;
  187. });
  188. getState(): CircuitState;
  189. /**
  190. * Returns true when calls should be short-circuited (skip HTTP, fall back).
  191. * Side-effects: may transition OPEN → HALF-OPEN if the open window expired.
  192. */
  193. shouldFailFast(): boolean;
  194. /** Record a successful call. */
  195. recordSuccess(): void;
  196. /** Record a failed call. May trigger OPEN. */
  197. recordFailure(): void;
  198. /** Force-reset the breaker (used by tests / admin) */
  199. reset(): void;
  200. private pushSample;
  201. private evaluate;
  202. private tickAutoReset;
  203. }
  204. /**
  205. * Raised when the circuit breaker is OPEN and a call is short-circuited.
  206. * Callers (e.g. fallback wrapper) can catch this to switch to local provider.
  207. */
  208. export declare class CircuitOpenError extends Error {
  209. constructor(message?: string);
  210. }
  211. /**
  212. * Persistent (non-retryable) HTTP error from upstream. Includes status code.
  213. */
  214. export declare class HttpError extends Error {
  215. readonly status: number;
  216. readonly bodyPreview: string;
  217. /** Server-advertised cooldown for 429s, when the response stated one. */
  218. readonly retryAfterMs?: number;
  219. constructor(status: number, bodyPreview: string, retryAfterMs?: number);
  220. }
  221. /**
  222. * Client-side bulk lane for reindex traffic (i-yghj098h).
  223. *
  224. * qmd's bulk embedding shares the interactive ai.mm.mk token bucket. Without a
  225. * server-side per-caller budget, the only way bulk traffic can stop contending
  226. * head-on with interactive callers is to police itself:
  227. *
  228. * - a 429 on ANY worker pauses the ENTIRE pool for the advertised cooldown
  229. * (one shared promise — concurrent 429s coalesce instead of stacking N
  230. * cooldowns), so the bucket refills for interactive callers rather than
  231. * being re-drained by the remaining workers;
  232. * - the in-flight cap halves on each cooldown (floor 1) and recovers one unit
  233. * per `LANE_RECOVERY_STREAK` successes — classic AIMD, so a run settles at
  234. * whatever share the bucket actually has spare.
  235. *
  236. * Deliberately clock-free: cooldowns are modelled as a promise produced by the
  237. * injected `sleep`, so tests drive them with a fake sleep and no fake clock.
  238. */
  239. export declare class BulkLaneGate {
  240. private readonly maxPermits;
  241. private readonly sleep;
  242. private permits;
  243. private inFlight;
  244. private okStreak;
  245. private cooldown;
  246. private waiters;
  247. constructor(maxPermits: number, sleep: (ms: number) => Promise<void>);
  248. /** Current in-flight cap — exported state for tests/diagnostics. */
  249. get permitCount(): number;
  250. /** True while the lane is serving a rate-limit cooldown. */
  251. get isCoolingDown(): boolean;
  252. /** Take a slot, waiting out any cooldown and respecting the current cap. */
  253. acquire(): Promise<void>;
  254. /** Return a slot. Always call from a `finally`. */
  255. release(): void;
  256. /**
  257. * Enter (or join) a cooldown of `waitMs` and halve the in-flight cap.
  258. * Returns the shared cooldown promise — the caller awaits it INSTEAD of
  259. * sleeping itself, so a burst of 429s costs one cooldown, not one each.
  260. */
  261. penalize(waitMs: number): Promise<void>;
  262. /** Record a successful bulk request; recovers one permit per success streak. */
  263. noteSuccess(): void;
  264. private wakeOne;
  265. private wakeAll;
  266. }
  267. export declare class OpenAIEmbeddingsProvider implements EmbeddingProvider {
  268. readonly kind: ProviderKind;
  269. private readonly endpoint;
  270. private readonly apiKey?;
  271. private readonly modelId;
  272. private readonly upstreamModel;
  273. private readonly batchSize;
  274. private readonly concurrency;
  275. private readonly timeoutMs;
  276. private readonly fetchImpl;
  277. private readonly retryBackoffsMs;
  278. private readonly rateLimitRetries;
  279. private readonly sleep;
  280. private readonly now;
  281. private dimensions;
  282. private lastError;
  283. readonly breaker: CircuitBreaker;
  284. /** Shared bulk-traffic lane — see `BulkLaneGate`. */
  285. readonly lane: BulkLaneGate;
  286. constructor(config: OpenAIProviderConfig);
  287. getModelId(): string;
  288. getDimensions(): number | undefined;
  289. /**
  290. * Most recent per-chunk failure message (HTTP status + body preview, malformed
  291. * JSON, timeout, abort reason). Returns `undefined` after a successful call
  292. * or before the first call. See `EmbeddingProvider.getLastError`.
  293. */
  294. getLastError(): string | undefined;
  295. /** Endpoint URL configured at construction time — used by callers when
  296. * building error messages for failed first-chunk probes. */
  297. getEndpoint(): string;
  298. healthcheck(signal?: AbortSignal): Promise<ProviderHealth>;
  299. embed(text: string, options?: ProviderEmbedOptions): Promise<ProviderEmbedding | null>;
  300. embedBatch(texts: string[], options?: ProviderEmbedOptions): Promise<(ProviderEmbedding | null)[]>;
  301. dispose(): Promise<void>;
  302. /**
  303. * Format a request-failure context string for `lastError`. Includes endpoint
  304. * + HTTP status + body preview when the error was an `HttpError`, otherwise
  305. * falls back to the message of the underlying error (or the value itself
  306. * when not an Error). Kept short — body preview is already capped at 1024
  307. * chars by `HttpError`, but we trim further here for the dimension-probe
  308. * thrown error which surfaces directly to users.
  309. */
  310. private formatErrorContext;
  311. private buildHeaders;
  312. /**
  313. * Single HTTP request with retry on 429/503. Returns embeddings indexed
  314. * the same as `texts`. Throws on non-retryable failure or all attempts
  315. * exhausted.
  316. */
  317. private requestWithRetry;
  318. /**
  319. * How long to wait after a 429. The server's own `Retry-After` wins when it
  320. * gave one; otherwise fall back to the configured schedule (so injected test
  321. * schedules stay authoritative) and then to an exponential 5s/10s/20s… ramp.
  322. * Always clamped to `RATE_LIMIT_MAX_BACKOFF_MS`.
  323. */
  324. private rateLimitWaitMs;
  325. /**
  326. * Issue one HTTP attempt to `POST /v1/embeddings`. Does NOT retry.
  327. */
  328. private requestOnce;
  329. }