@abhishek944/pi-embeddings 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/providers.js CHANGED
@@ -1,17 +1,101 @@
1
1
  import { getEncoding } from 'js-tiktoken';
2
2
  import { VertexProvider, vertexEmbeddingSpace } from './vertex-provider.js';
3
3
  import { EmbeddingsError } from './errors.js';
4
- import { EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_FORMAT_VERSION, EMBEDDING_NORMALIZATION_VERSION, CLOUDFLARE_EMBEDDING_MODELS, DEFAULT_GEMINI_DIMENSIONS, DEFAULT_GEMINI_TASK_FORMAT, GEMINI_EMBEDDING_MODELS, GEMINI_TASK_PREFIXES, OPENROUTER_EMBEDDING_MODELS, } from './schemas.js';
4
+ import { EMBEDDING_DOCUMENT_PREFIX, EMBEDDING_FORMAT_VERSION, EMBEDDING_NORMALIZATION_VERSION, CLOUDFLARE_EMBEDDING_MODELS, COHERE_EMBEDDING_MODELS, DASHSCOPE_EMBEDDING_MODELS, DEFAULT_COHERE_DIMENSIONS, DEFAULT_DASHSCOPE_DIMENSIONS, DEFAULT_GEMINI_DIMENSIONS, DEFAULT_GEMINI_TASK_FORMAT, DEFAULT_VOYAGE_DIMENSIONS, GEMINI_EMBEDDING_MODELS, GEMINI_TASK_PREFIXES, HETZNER_EMBEDDING_DIMENSIONS, HETZNER_EMBEDDING_MODELS, JINA_EMBEDDING_DIMENSIONS, JINA_EMBEDDING_MODELS, OPENAI_EMBEDDING_DIMENSIONS, OPENAI_EMBEDDING_MODELS, OPENCODE_EMBEDDING_MODELS, OPENCODE_GO_EMBEDDING_MODELS, OPENROUTER_EMBEDDING_MODELS, VOYAGE_EMBEDDING_MODELS, } from './schemas.js';
5
5
  import { fixedOrigin, headerValueIsSafe, requestJson } from './provider-http.js';
6
6
  import { acquireLocalRuntime, LOCAL_EMBEDDING_SPACE } from './local-runtime.js';
7
- import { parseBatchResponse, parseCloudflareBatchResponse, parseGeminiCountTokensResponse, parseGeminiEmbeddingResponse, } from './response.js';
8
- export const OPENAI_EMBEDDING_SPACE = Object.freeze({
9
- provider: 'openai',
10
- model: 'text-embedding-3-small',
7
+ import { parseBatchResponse, parseCloudflareBatchResponse, parseCohereBatchResponse, parseGeminiCountTokensResponse, parseGeminiEmbeddingResponse, parseOpenCodeBatchResponse, parseOptionalUsageBatchResponse, parseVoyageBatchResponse, } from './response.js';
8
+ export const openaiEmbeddingSpace = (model) => {
9
+ const common = {
10
+ provider: 'openai',
11
+ revision: null,
12
+ quantization: null,
13
+ runtime: null,
14
+ format: EMBEDDING_FORMAT_VERSION,
15
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
16
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
17
+ };
18
+ // Dimension is bound to the model so the descriptor cannot record an impossible pair.
19
+ if (model === 'text-embedding-3-large')
20
+ return Object.freeze({
21
+ ...common,
22
+ model: 'text-embedding-3-large',
23
+ dimensions: OPENAI_EMBEDDING_DIMENSIONS['text-embedding-3-large'],
24
+ });
25
+ return Object.freeze({
26
+ ...common,
27
+ model: 'text-embedding-3-small',
28
+ dimensions: OPENAI_EMBEDDING_DIMENSIONS['text-embedding-3-small'],
29
+ });
30
+ };
31
+ export const OPENAI_EMBEDDING_SPACE = openaiEmbeddingSpace('text-embedding-3-small');
32
+ export const voyageEmbeddingSpace = (config) => Object.freeze({
33
+ provider: 'voyage',
34
+ model: config.model,
35
+ revision: null,
36
+ quantization: null,
37
+ runtime: 'voyage-api-v1',
38
+ dimensions: config.dimensions,
39
+ inputType: 'document',
40
+ format: EMBEDDING_FORMAT_VERSION,
41
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
42
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
43
+ });
44
+ export const cohereEmbeddingSpace = (config) => Object.freeze({
45
+ provider: 'cohere',
46
+ model: config.model,
47
+ revision: null,
48
+ quantization: null,
49
+ runtime: 'cohere-api-v2',
50
+ dimensions: config.dimensions,
51
+ inputType: 'search_document',
52
+ format: EMBEDDING_FORMAT_VERSION,
53
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
54
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
55
+ });
56
+ /** Jina's declared default is the largest documented Matryoshka size for that model. */
57
+ const jinaDefaultDimensions = (model) => {
58
+ const documented = JINA_EMBEDDING_DIMENSIONS[model];
59
+ const largest = documented[documented.length - 1];
60
+ if (largest === undefined)
61
+ throw new EmbeddingsError('configuration-invalid');
62
+ return largest;
63
+ };
64
+ /** Jina documents per-model Matryoshka sizes; an undeclared size is a configuration error. */
65
+ export const jinaEmbeddingSpace = (config) => {
66
+ if (!JINA_EMBEDDING_DIMENSIONS[config.model].includes(config.dimensions))
67
+ throw new EmbeddingsError('configuration-invalid');
68
+ return Object.freeze({
69
+ provider: 'jina',
70
+ model: config.model,
71
+ revision: null,
72
+ quantization: null,
73
+ runtime: 'jina-api-v1',
74
+ dimensions: config.dimensions,
75
+ task: 'retrieval.passage',
76
+ format: EMBEDDING_FORMAT_VERSION,
77
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
78
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
79
+ });
80
+ };
81
+ export const dashScopeEmbeddingSpace = (dimensions) => Object.freeze({
82
+ provider: 'dashscope',
83
+ model: DASHSCOPE_EMBEDDING_MODELS[0],
11
84
  revision: null,
12
85
  quantization: null,
13
- runtime: null,
14
- dimensions: 1536,
86
+ runtime: 'dashscope-compatible-mode-v1',
87
+ dimensions,
88
+ format: EMBEDDING_FORMAT_VERSION,
89
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
90
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
91
+ });
92
+ export const HETZNER_EMBEDDING_SPACE = Object.freeze({
93
+ provider: 'hetzner',
94
+ model: HETZNER_EMBEDDING_MODELS[0],
95
+ revision: null,
96
+ quantization: null,
97
+ runtime: 'hetzner-inference-v1',
98
+ dimensions: HETZNER_EMBEDDING_DIMENSIONS,
15
99
  format: EMBEDDING_FORMAT_VERSION,
16
100
  prefix: EMBEDDING_DOCUMENT_PREFIX,
17
101
  normalization: EMBEDDING_NORMALIZATION_VERSION,
@@ -51,6 +135,9 @@ export const geminiEmbeddingSpace = (config) => Object.freeze({
51
135
  prefix: GEMINI_TASK_PREFIXES[config.taskFormat],
52
136
  normalization: EMBEDDING_NORMALIZATION_VERSION,
53
137
  });
138
+ export const OPENCODE_CONSOLE_EMBEDDINGS_URL = 'https://opencode.ai/inference/openai/v1/embeddings';
139
+ export const OPENCODE_GO_EMBEDDINGS_URL = 'https://opencode.ai/inference/go/openai/v1/embeddings';
140
+ const OPENCODE_USER_AGENT = 'pi-embeddings';
54
141
  const OPENAI_MODEL = 'text-embedding-3-small';
55
142
  const SARVAM_MODEL = 'embeddinggemma-2';
56
143
  const SARVAM_ORIGIN = 'https://api.sarvam.ai';
@@ -61,13 +148,60 @@ const GEMINI_MAX_INPUT_TOKENS = 8192;
61
148
  const OPENAI_MAX_INPUT_TOKENS = 8192;
62
149
  const OPENAI_MAX_REQUEST_INPUTS = 2048;
63
150
  const OPENAI_MAX_REQUEST_TOKENS = 300000;
151
+ /** Voyage documents a 1000-input list ceiling; aggregate caps are provider-enforced only. */
152
+ const VOYAGE_ORIGIN = 'https://api.voyageai.com';
153
+ const VOYAGE_MAX_REQUEST_INPUTS = 1000;
154
+ /** Cohere documents a maximum of 96 texts per call. */
155
+ const COHERE_ORIGIN = 'https://api.cohere.com';
156
+ const COHERE_MAX_REQUEST_INPUTS = 96;
157
+ /** Jina publishes RPM/TPM rate limits but no per-request input count ceiling. */
158
+ const JINA_EMBEDDINGS_URL = 'https://api.jina.ai/v1/embeddings';
159
+ /** Model Studio documents at most 20 rows per request for qwen3.7-text-embedding. */
160
+ const DASHSCOPE_EMBEDDINGS_PATH = '/compatible-mode/v1/embeddings';
161
+ const DASHSCOPE_MAX_REQUEST_INPUTS = 20;
162
+ /** Hetzner publishes a 32 MiB body ceiling and about 1M recommended tokens, no count cap. */
163
+ const HETZNER_EMBEDDINGS_URL = 'https://inference.hetzner.com/v1/embeddings';
164
+ const VOYAGE_INPUT_TYPE = 'document';
165
+ const COHERE_INPUT_TYPE = 'search_document';
166
+ const JINA_TASK = 'retrieval.passage';
167
+ const isOneOf = (values, value) => values.some((candidate) => candidate === value);
168
+ export const opencodeEmbeddingSpace = (args) => {
169
+ const common = {
170
+ revision: null,
171
+ quantization: null,
172
+ dimensions: args.dimensions,
173
+ format: EMBEDDING_FORMAT_VERSION,
174
+ prefix: EMBEDDING_DOCUMENT_PREFIX,
175
+ normalization: EMBEDDING_NORMALIZATION_VERSION,
176
+ };
177
+ if (args.provider === 'opencode') {
178
+ if (!isOneOf(OPENCODE_EMBEDDING_MODELS, args.model))
179
+ throw new EmbeddingsError('configuration-invalid');
180
+ const space = {
181
+ ...common,
182
+ provider: 'opencode',
183
+ model: args.model,
184
+ runtime: 'opencode-console-embeddings-v1',
185
+ };
186
+ return Object.freeze(space);
187
+ }
188
+ if (!isOneOf(OPENCODE_GO_EMBEDDING_MODELS, args.model))
189
+ throw new EmbeddingsError('configuration-invalid');
190
+ const space = {
191
+ ...common,
192
+ provider: 'opencode-go',
193
+ model: args.model,
194
+ runtime: 'opencode-go-embeddings-v1',
195
+ };
196
+ return Object.freeze(space);
197
+ };
64
198
  const trim = (value) => {
65
199
  const trimmed = value?.trim();
66
200
  return trimmed === undefined || trimmed === '' ? undefined : trimmed;
67
201
  };
68
202
  export const routeKey = (route) => `${route.provider}\u0000${route.model}`;
69
203
  /** Diagnostics are provider-free and never contain keys, origins or model paths. */
70
- export function routeDiagnostics(settings, route) {
204
+ export function routeDiagnostics(settings, route, piCredentialAvailable = {}) {
71
205
  const diagnostics = [];
72
206
  const add = (code, severity = 'error') => {
73
207
  diagnostics.push({ code, severity });
@@ -113,11 +247,48 @@ export function routeDiagnostics(settings, route) {
113
247
  if (trim(settings.providers?.gemini?.apiKey) === undefined && trim(process.env.GEMINI_API_KEY) === undefined)
114
248
  add('gemini-key-unconfigured');
115
249
  break;
250
+ case 'opencode':
251
+ if (trim(settings.providers?.opencode?.apiKey) === undefined &&
252
+ trim(process.env.OPENCODE_API_KEY) === undefined &&
253
+ piCredentialAvailable.opencode !== true)
254
+ add('opencode-key-unconfigured');
255
+ break;
256
+ case 'opencode-go':
257
+ if (trim(settings.providers?.['opencode-go']?.apiKey) === undefined &&
258
+ trim(process.env.OPENCODE_API_KEY) === undefined &&
259
+ piCredentialAvailable['opencode-go'] !== true)
260
+ add('opencode-go-key-unconfigured');
261
+ break;
116
262
  case 'vertex':
117
263
  if (settings.providers?.vertex === undefined)
118
264
  add('vertex-configuration-unconfigured');
119
265
  // Provider-free diagnostics cannot establish ADC, IAM, quota or live model availability.
120
266
  break;
267
+ case 'voyage':
268
+ if (trim(settings.providers?.voyage?.apiKey) === undefined && trim(process.env.VOYAGE_API_KEY) === undefined)
269
+ add('voyage-key-unconfigured');
270
+ break;
271
+ case 'cohere':
272
+ if (trim(settings.providers?.cohere?.apiKey) === undefined && trim(process.env.COHERE_API_KEY) === undefined)
273
+ add('cohere-key-unconfigured');
274
+ break;
275
+ case 'jina':
276
+ if (trim(settings.providers?.jina?.apiKey) === undefined && trim(process.env.JINA_API_KEY) === undefined)
277
+ add('jina-key-unconfigured');
278
+ break;
279
+ case 'dashscope': {
280
+ const dashscope = settings.providers?.dashscope;
281
+ if (trim(dashscope?.baseUrl) === undefined && trim(process.env.DASHSCOPE_BASE_URL) === undefined)
282
+ add('dashscope-base-url-unconfigured');
283
+ if (trim(dashscope?.apiKey) === undefined && trim(process.env.DASHSCOPE_API_KEY) === undefined)
284
+ add('dashscope-key-unconfigured');
285
+ break;
286
+ }
287
+ case 'hetzner':
288
+ if (trim(settings.providers?.hetzner?.apiKey) === undefined &&
289
+ trim(process.env.HETZNER_INFERENCE_TOKEN) === undefined)
290
+ add('hetzner-key-unconfigured');
291
+ break;
121
292
  }
122
293
  return diagnostics;
123
294
  }
@@ -133,6 +304,31 @@ const headerCredential = (configured, env) => {
133
304
  throw new EmbeddingsError('configuration-invalid');
134
305
  return value;
135
306
  };
307
+ const safeHeaderValue = (value) => {
308
+ if (!headerValueIsSafe(value))
309
+ throw new EmbeddingsError('configuration-invalid');
310
+ return value;
311
+ };
312
+ /** Host-provided provider keys are read only when a route is acquired; errors never carry a value. */
313
+ async function openCodeCredential(args) {
314
+ const configured = args.route === 'opencode'
315
+ ? args.settings.providers?.opencode?.apiKey
316
+ : args.settings.providers?.['opencode-go']?.apiKey;
317
+ const explicit = trim(configured);
318
+ if (explicit !== undefined)
319
+ return safeHeaderValue(explicit);
320
+ if (args.resolver !== undefined) {
321
+ try {
322
+ const resolved = trim(await args.resolver(args.route));
323
+ if (resolved !== undefined)
324
+ return safeHeaderValue(resolved);
325
+ }
326
+ catch {
327
+ // A host resolver that cannot supply a key leaves the trusted environment fallback intact.
328
+ }
329
+ }
330
+ return headerCredential(undefined, process.env.OPENCODE_API_KEY);
331
+ }
136
332
  /** The documented text-string path avoids the token-array schema contradiction without truncating. */
137
333
  const openAIPrepare = (encoding, text, signal) => {
138
334
  signal.throwIfAborted();
@@ -150,15 +346,18 @@ const providerTexts = (inputs) => inputs.map((input) => {
150
346
  throw new EmbeddingsError('provider-response-invalid');
151
347
  return input.text;
152
348
  });
349
+ const openRouterCanonicalModel = (model) => model === 'openai/text-embedding-3-large' ? 'text-embedding-3-large' : 'text-embedding-3-small';
153
350
  class OpenAiProvider {
154
351
  route = 'openai';
155
- model = OPENAI_MODEL;
156
- space = OPENAI_EMBEDDING_SPACE;
352
+ model;
353
+ space;
157
354
  maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
158
355
  maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
159
356
  #encoding = getEncoding('cl100k_base');
160
357
  #key;
161
- constructor(key) {
358
+ constructor(model, key) {
359
+ this.model = model;
360
+ this.space = openaiEmbeddingSpace(model);
162
361
  this.#key = key;
163
362
  }
164
363
  async prepare(text, signal) {
@@ -187,6 +386,62 @@ class OpenAiProvider {
187
386
  // js-tiktoken is pure JavaScript and owns no process or handle.
188
387
  }
189
388
  }
389
+ class OpenCodeProvider {
390
+ route;
391
+ model;
392
+ space;
393
+ // OpenCode documents per-input context requirements but publishes no aggregate request ceiling.
394
+ maxRequestInputs = Number.POSITIVE_INFINITY;
395
+ maxRequestTokens = Number.POSITIVE_INFINITY;
396
+ #url;
397
+ #key;
398
+ constructor(args) {
399
+ this.route = args.route;
400
+ this.model = args.model;
401
+ this.space = opencodeEmbeddingSpace({
402
+ provider: args.route,
403
+ model: args.model,
404
+ dimensions: null,
405
+ });
406
+ this.#url = args.url;
407
+ this.#key = args.key;
408
+ }
409
+ async prepare(text, signal) {
410
+ signal.throwIfAborted();
411
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
412
+ }
413
+ async embed(inputs, signal) {
414
+ const parsed = parseOpenCodeBatchResponse({
415
+ response: await requestJson({
416
+ url: this.#url,
417
+ signal,
418
+ headers: {
419
+ authorization: `Bearer ${this.#key}`,
420
+ 'user-agent': OPENCODE_USER_AGENT,
421
+ },
422
+ body: {
423
+ model: this.model,
424
+ input: providerTexts(inputs),
425
+ encoding_format: 'float',
426
+ },
427
+ }),
428
+ expectedModels: [this.model],
429
+ expectedCount: inputs.length,
430
+ });
431
+ return {
432
+ vectors: parsed.vectors,
433
+ usage: parsed.usage,
434
+ space: opencodeEmbeddingSpace({
435
+ provider: this.route,
436
+ model: this.model,
437
+ dimensions: parsed.dimensions,
438
+ }),
439
+ };
440
+ }
441
+ async close() {
442
+ // Native fetch owns no long-lived resource.
443
+ }
444
+ }
190
445
  class SarvamProvider {
191
446
  route = 'sarvam';
192
447
  model = SARVAM_MODEL;
@@ -270,13 +525,15 @@ class GatewayProvider {
270
525
  }
271
526
  class OpenRouterProvider {
272
527
  route = 'openrouter';
273
- model = OPENROUTER_EMBEDDING_MODELS[0];
274
- space = OPENAI_EMBEDDING_SPACE;
528
+ model;
529
+ space;
275
530
  maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
276
531
  maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
277
532
  #encoding = getEncoding('cl100k_base');
278
533
  #key;
279
- constructor(key) {
534
+ constructor(model, key) {
535
+ this.model = model;
536
+ this.space = openaiEmbeddingSpace(openRouterCanonicalModel(model));
280
537
  this.#key = key;
281
538
  }
282
539
  async prepare(text, signal) {
@@ -307,6 +564,195 @@ class OpenRouterProvider {
307
564
  // js-tiktoken is pure JavaScript and owns no process or handle.
308
565
  }
309
566
  }
567
+ class VoyageProvider {
568
+ route = 'voyage';
569
+ model;
570
+ space;
571
+ // Voyage documents a 1000-input list ceiling; aggregate token caps stay provider-enforced.
572
+ maxRequestInputs = VOYAGE_MAX_REQUEST_INPUTS;
573
+ maxRequestTokens = Number.POSITIVE_INFINITY;
574
+ #key;
575
+ constructor(config) {
576
+ this.model = config.model;
577
+ this.space = voyageEmbeddingSpace({ model: config.model, dimensions: config.dimensions });
578
+ this.#key = config.key;
579
+ }
580
+ async prepare(text, signal) {
581
+ signal.throwIfAborted();
582
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
583
+ }
584
+ async embed(inputs, signal) {
585
+ const response = await requestJson({
586
+ url: new URL('/v1/embeddings', VOYAGE_ORIGIN),
587
+ signal,
588
+ headers: { authorization: `Bearer ${this.#key}` },
589
+ body: {
590
+ model: this.model,
591
+ input: providerTexts(inputs),
592
+ input_type: VOYAGE_INPUT_TYPE,
593
+ output_dimension: this.space.dimensions,
594
+ // This package never truncates, so an over-length input must fail instead of being cut.
595
+ truncation: false,
596
+ },
597
+ });
598
+ return parseVoyageBatchResponse({
599
+ response,
600
+ space: this.space,
601
+ expectedModels: [this.model],
602
+ expectedCount: inputs.length,
603
+ });
604
+ }
605
+ async close() {
606
+ // Native fetch owns no long-lived resource.
607
+ }
608
+ }
609
+ class CohereProvider {
610
+ route = 'cohere';
611
+ model;
612
+ space;
613
+ /** Cohere rejects more than 96 texts in one call. */
614
+ maxRequestInputs = COHERE_MAX_REQUEST_INPUTS;
615
+ maxRequestTokens = Number.POSITIVE_INFINITY;
616
+ #key;
617
+ constructor(config) {
618
+ this.model = config.model;
619
+ this.space = cohereEmbeddingSpace({ model: config.model, dimensions: config.dimensions });
620
+ this.#key = config.key;
621
+ }
622
+ async prepare(text, signal) {
623
+ signal.throwIfAborted();
624
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
625
+ }
626
+ async embed(inputs, signal) {
627
+ const response = await requestJson({
628
+ url: new URL('/v2/embed', COHERE_ORIGIN),
629
+ signal,
630
+ headers: { authorization: `Bearer ${this.#key}` },
631
+ body: {
632
+ model: this.model,
633
+ input_type: COHERE_INPUT_TYPE,
634
+ texts: providerTexts(inputs),
635
+ embedding_types: ['float'],
636
+ output_dimension: this.space.dimensions,
637
+ // Default is END; refuse instead of silently shortening an over-length input.
638
+ truncate: 'NONE',
639
+ },
640
+ });
641
+ return parseCohereBatchResponse({ response, space: this.space, expectedCount: inputs.length });
642
+ }
643
+ async close() {
644
+ // Native fetch owns no long-lived resource.
645
+ }
646
+ }
647
+ class JinaProvider {
648
+ route = 'jina';
649
+ model;
650
+ space;
651
+ // Jina publishes RPM/TPM limits but no per-request input count ceiling.
652
+ maxRequestInputs = Number.POSITIVE_INFINITY;
653
+ maxRequestTokens = Number.POSITIVE_INFINITY;
654
+ #key;
655
+ constructor(config) {
656
+ this.model = config.model;
657
+ this.space = jinaEmbeddingSpace({ model: config.model, dimensions: config.dimensions });
658
+ this.#key = config.key;
659
+ }
660
+ async prepare(text, signal) {
661
+ signal.throwIfAborted();
662
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
663
+ }
664
+ async embed(inputs, signal) {
665
+ const response = await requestJson({
666
+ url: new URL(JINA_EMBEDDINGS_URL),
667
+ signal,
668
+ headers: { authorization: `Bearer ${this.#key}` },
669
+ body: {
670
+ model: this.model,
671
+ input: providerTexts(inputs),
672
+ task: JINA_TASK,
673
+ dimensions: this.space.dimensions,
674
+ embedding_type: 'float',
675
+ // The package owns normalization and never truncates, so both are disabled explicitly.
676
+ normalized: false,
677
+ truncate: false,
678
+ },
679
+ });
680
+ return parseBatchResponse({ response, space: this.space, expectedModels: [this.model] });
681
+ }
682
+ async close() {
683
+ // Native fetch owns no long-lived resource.
684
+ }
685
+ }
686
+ class DashScopeProvider {
687
+ route = 'dashscope';
688
+ model = DASHSCOPE_EMBEDDING_MODELS[0];
689
+ space;
690
+ /** Model Studio documents at most 20 rows per request for this model. */
691
+ maxRequestInputs = DASHSCOPE_MAX_REQUEST_INPUTS;
692
+ maxRequestTokens = Number.POSITIVE_INFINITY;
693
+ #url;
694
+ #key;
695
+ constructor(config) {
696
+ this.#url = new URL(DASHSCOPE_EMBEDDINGS_PATH, config.origin);
697
+ this.#key = config.key;
698
+ this.space = dashScopeEmbeddingSpace(config.dimensions);
699
+ }
700
+ async prepare(text, signal) {
701
+ signal.throwIfAborted();
702
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
703
+ }
704
+ async embed(inputs, signal) {
705
+ const response = await requestJson({
706
+ url: this.#url,
707
+ signal,
708
+ headers: { authorization: `Bearer ${this.#key}` },
709
+ body: {
710
+ model: this.model,
711
+ input: providerTexts(inputs),
712
+ dimensions: this.space.dimensions,
713
+ encoding_format: 'float',
714
+ },
715
+ });
716
+ return parseBatchResponse({ response, space: this.space, expectedModels: [this.model] });
717
+ }
718
+ async close() {
719
+ // Native fetch owns no long-lived resource.
720
+ }
721
+ }
722
+ class HetznerProvider {
723
+ route = 'hetzner';
724
+ model = HETZNER_EMBEDDING_MODELS[0];
725
+ space = HETZNER_EMBEDDING_SPACE;
726
+ // Hetzner documents a 32 MiB body ceiling and no fixed input count.
727
+ maxRequestInputs = Number.POSITIVE_INFINITY;
728
+ maxRequestTokens = Number.POSITIVE_INFINITY;
729
+ #key;
730
+ constructor(key) {
731
+ this.#key = key;
732
+ }
733
+ async prepare(text, signal) {
734
+ signal.throwIfAborted();
735
+ return { kind: 'text', text: EMBEDDING_DOCUMENT_PREFIX + text, tokenCount: null };
736
+ }
737
+ async embed(inputs, signal) {
738
+ const response = await requestJson({
739
+ url: new URL(HETZNER_EMBEDDINGS_URL),
740
+ signal,
741
+ headers: { authorization: `Bearer ${this.#key}` },
742
+ // Hetzner documents `float` and `base64` for this endpoint; float is the value this package records.
743
+ body: { model: this.model, input: providerTexts(inputs), encoding_format: 'float' },
744
+ });
745
+ return parseOptionalUsageBatchResponse({
746
+ response,
747
+ space: this.space,
748
+ expectedModels: [this.model],
749
+ expectedCount: inputs.length,
750
+ });
751
+ }
752
+ async close() {
753
+ // Native fetch owns no long-lived resource.
754
+ }
755
+ }
310
756
  class CloudflareProvider {
311
757
  route = 'cloudflare';
312
758
  model = CLOUDFLARE_EMBEDDING_MODELS[0];
@@ -414,7 +860,7 @@ class GeminiProvider {
414
860
  }
415
861
  const noRelease = async () => undefined;
416
862
  /** Resolve a configured route only when that route is actually about to be used. */
417
- export async function acquireProvider({ settings, route, signal, }) {
863
+ export async function acquireProvider({ settings, route, signal, credentialResolver, }) {
418
864
  switch (route.provider) {
419
865
  case 'local': {
420
866
  const local = settings.providers?.local;
@@ -425,11 +871,14 @@ export async function acquireProvider({ settings, route, signal, }) {
425
871
  const acquired = await acquireLocalRuntime({ executable, modelPath, port: local.port ?? 8791 }, signal);
426
872
  return { provider: acquired.provider, release: acquired.release };
427
873
  }
428
- case 'openai':
874
+ case 'openai': {
875
+ if (!isOneOf(OPENAI_EMBEDDING_MODELS, route.model))
876
+ throw new EmbeddingsError('configuration-invalid');
429
877
  return {
430
- provider: new OpenAiProvider(credential(settings.providers?.openai?.apiKey, process.env.OPENAI_API_KEY)),
878
+ provider: new OpenAiProvider(route.model, credential(settings.providers?.openai?.apiKey, process.env.OPENAI_API_KEY)),
431
879
  release: noRelease,
432
880
  };
881
+ }
433
882
  case 'sarvam':
434
883
  return {
435
884
  provider: new SarvamProvider(credential(settings.providers?.sarvam?.apiKey, process.env.SARVAM_API_KEY)),
@@ -452,11 +901,14 @@ export async function acquireProvider({ settings, route, signal, }) {
452
901
  release: noRelease,
453
902
  };
454
903
  }
455
- case 'openrouter':
904
+ case 'openrouter': {
905
+ if (!isOneOf(OPENROUTER_EMBEDDING_MODELS, route.model))
906
+ throw new EmbeddingsError('configuration-invalid');
456
907
  return {
457
- provider: new OpenRouterProvider(headerCredential(settings.providers?.openrouter?.apiKey, process.env.OPENROUTER_API_KEY)),
908
+ provider: new OpenRouterProvider(route.model, headerCredential(settings.providers?.openrouter?.apiKey, process.env.OPENROUTER_API_KEY)),
458
909
  release: noRelease,
459
910
  };
911
+ }
460
912
  case 'cloudflare': {
461
913
  const configured = settings.providers?.cloudflare;
462
914
  const accountId = trim(configured?.accountId) ?? trim(process.env.CLOUDFLARE_ACCOUNT_ID);
@@ -480,6 +932,19 @@ export async function acquireProvider({ settings, route, signal, }) {
480
932
  release: noRelease,
481
933
  };
482
934
  }
935
+ case 'opencode':
936
+ case 'opencode-go':
937
+ return {
938
+ provider: new OpenCodeProvider({
939
+ route: route.provider,
940
+ model: route.model,
941
+ key: await openCodeCredential({ route: route.provider, settings, resolver: credentialResolver }),
942
+ url: new URL(route.provider === 'opencode'
943
+ ? OPENCODE_CONSOLE_EMBEDDINGS_URL
944
+ : OPENCODE_GO_EMBEDDINGS_URL),
945
+ }),
946
+ release: noRelease,
947
+ };
483
948
  case 'vertex': {
484
949
  const configured = settings.providers?.vertex;
485
950
  if (configured === undefined)
@@ -496,6 +961,65 @@ export async function acquireProvider({ settings, route, signal, }) {
496
961
  release: noRelease,
497
962
  };
498
963
  }
964
+ case 'voyage': {
965
+ const configured = settings.providers?.voyage;
966
+ if (!isOneOf(VOYAGE_EMBEDDING_MODELS, route.model))
967
+ throw new EmbeddingsError('configuration-invalid');
968
+ return {
969
+ provider: new VoyageProvider({
970
+ model: route.model,
971
+ dimensions: configured?.dimensions ?? DEFAULT_VOYAGE_DIMENSIONS,
972
+ key: headerCredential(configured?.apiKey, process.env.VOYAGE_API_KEY),
973
+ }),
974
+ release: noRelease,
975
+ };
976
+ }
977
+ case 'cohere': {
978
+ const configured = settings.providers?.cohere;
979
+ if (!isOneOf(COHERE_EMBEDDING_MODELS, route.model))
980
+ throw new EmbeddingsError('configuration-invalid');
981
+ return {
982
+ provider: new CohereProvider({
983
+ model: route.model,
984
+ dimensions: configured?.dimensions ?? DEFAULT_COHERE_DIMENSIONS,
985
+ key: headerCredential(configured?.apiKey, process.env.COHERE_API_KEY),
986
+ }),
987
+ release: noRelease,
988
+ };
989
+ }
990
+ case 'jina': {
991
+ const configured = settings.providers?.jina;
992
+ if (!isOneOf(JINA_EMBEDDING_MODELS, route.model))
993
+ throw new EmbeddingsError('configuration-invalid');
994
+ const model = route.model;
995
+ return {
996
+ provider: new JinaProvider({
997
+ model,
998
+ dimensions: configured?.dimensions ?? jinaDefaultDimensions(model),
999
+ key: headerCredential(configured?.apiKey, process.env.JINA_API_KEY),
1000
+ }),
1001
+ release: noRelease,
1002
+ };
1003
+ }
1004
+ case 'dashscope': {
1005
+ const configured = settings.providers?.dashscope;
1006
+ const baseUrl = trim(configured?.baseUrl) ?? trim(process.env.DASHSCOPE_BASE_URL);
1007
+ if (baseUrl === undefined)
1008
+ throw new EmbeddingsError('configuration-invalid');
1009
+ return {
1010
+ provider: new DashScopeProvider({
1011
+ origin: fixedOrigin(baseUrl),
1012
+ dimensions: configured?.dimensions ?? DEFAULT_DASHSCOPE_DIMENSIONS,
1013
+ key: headerCredential(configured?.apiKey, process.env.DASHSCOPE_API_KEY),
1014
+ }),
1015
+ release: noRelease,
1016
+ };
1017
+ }
1018
+ case 'hetzner':
1019
+ return {
1020
+ provider: new HetznerProvider(headerCredential(settings.providers?.hetzner?.apiKey, process.env.HETZNER_INFERENCE_TOKEN)),
1021
+ release: noRelease,
1022
+ };
499
1023
  }
500
1024
  }
501
1025
  export const spaceForRoute = (route, settings) => {
@@ -503,9 +1027,42 @@ export const spaceForRoute = (route, settings) => {
503
1027
  case 'local':
504
1028
  return LOCAL_EMBEDDING_SPACE;
505
1029
  case 'openai':
1030
+ if (!isOneOf(OPENAI_EMBEDDING_MODELS, route.model))
1031
+ throw new EmbeddingsError('configuration-invalid');
1032
+ return openaiEmbeddingSpace(route.model);
506
1033
  case 'gateway':
507
- case 'openrouter':
508
1034
  return OPENAI_EMBEDDING_SPACE;
1035
+ case 'openrouter':
1036
+ if (!isOneOf(OPENROUTER_EMBEDDING_MODELS, route.model))
1037
+ throw new EmbeddingsError('configuration-invalid');
1038
+ return openaiEmbeddingSpace(openRouterCanonicalModel(route.model));
1039
+ case 'voyage':
1040
+ if (!isOneOf(VOYAGE_EMBEDDING_MODELS, route.model))
1041
+ throw new EmbeddingsError('configuration-invalid');
1042
+ return voyageEmbeddingSpace({
1043
+ model: route.model,
1044
+ dimensions: settings?.providers?.voyage?.dimensions ?? DEFAULT_VOYAGE_DIMENSIONS,
1045
+ });
1046
+ case 'cohere':
1047
+ if (!isOneOf(COHERE_EMBEDDING_MODELS, route.model))
1048
+ throw new EmbeddingsError('configuration-invalid');
1049
+ return cohereEmbeddingSpace({
1050
+ model: route.model,
1051
+ dimensions: settings?.providers?.cohere?.dimensions ?? DEFAULT_COHERE_DIMENSIONS,
1052
+ });
1053
+ case 'jina': {
1054
+ if (!isOneOf(JINA_EMBEDDING_MODELS, route.model))
1055
+ throw new EmbeddingsError('configuration-invalid');
1056
+ const model = route.model;
1057
+ return jinaEmbeddingSpace({
1058
+ model,
1059
+ dimensions: settings?.providers?.jina?.dimensions ?? jinaDefaultDimensions(model),
1060
+ });
1061
+ }
1062
+ case 'dashscope':
1063
+ return dashScopeEmbeddingSpace(settings?.providers?.dashscope?.dimensions ?? DEFAULT_DASHSCOPE_DIMENSIONS);
1064
+ case 'hetzner':
1065
+ return HETZNER_EMBEDDING_SPACE;
509
1066
  case 'sarvam':
510
1067
  return SARVAM_EMBEDDING_SPACE;
511
1068
  case 'cloudflare':
@@ -521,5 +1078,8 @@ export const spaceForRoute = (route, settings) => {
521
1078
  dimensions: settings?.providers?.gemini?.dimensions ?? DEFAULT_GEMINI_DIMENSIONS,
522
1079
  taskFormat: settings?.providers?.gemini?.taskFormat ?? DEFAULT_GEMINI_TASK_FORMAT,
523
1080
  });
1081
+ case 'opencode':
1082
+ case 'opencode-go':
1083
+ return opencodeEmbeddingSpace({ provider: route.provider, model: route.model, dimensions: null });
524
1084
  }
525
1085
  };