@abhishek944/pi-embeddings 0.5.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/README.md +26 -5
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/providers.d.ts +17 -1
- package/dist/providers.js +435 -18
- package/dist/response.d.ts +23 -0
- package/dist/response.js +115 -0
- package/dist/schemas.d.ts +846 -23
- package/dist/schemas.js +203 -2
- package/dist/settings.js +20 -2
- package/dist/tool-contracts.d.ts +387 -9
- package/package.json +8 -3
- package/src/index.ts +29 -0
- package/src/providers.ts +519 -14
- package/src/response.ts +152 -0
- package/src/schemas.ts +265 -2
- package/src/settings.ts +26 -1
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, OPENCODE_EMBEDDING_MODELS, OPENCODE_GO_EMBEDDING_MODELS, 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, parseOpenCodeBatchResponse, } from './response.js';
|
|
8
|
-
export const
|
|
9
|
-
|
|
10
|
-
|
|
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:
|
|
14
|
-
dimensions
|
|
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,
|
|
@@ -64,6 +148,22 @@ const GEMINI_MAX_INPUT_TOKENS = 8192;
|
|
|
64
148
|
const OPENAI_MAX_INPUT_TOKENS = 8192;
|
|
65
149
|
const OPENAI_MAX_REQUEST_INPUTS = 2048;
|
|
66
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';
|
|
67
167
|
const isOneOf = (values, value) => values.some((candidate) => candidate === value);
|
|
68
168
|
export const opencodeEmbeddingSpace = (args) => {
|
|
69
169
|
const common = {
|
|
@@ -164,6 +264,31 @@ export function routeDiagnostics(settings, route, piCredentialAvailable = {}) {
|
|
|
164
264
|
add('vertex-configuration-unconfigured');
|
|
165
265
|
// Provider-free diagnostics cannot establish ADC, IAM, quota or live model availability.
|
|
166
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;
|
|
167
292
|
}
|
|
168
293
|
return diagnostics;
|
|
169
294
|
}
|
|
@@ -221,15 +346,18 @@ const providerTexts = (inputs) => inputs.map((input) => {
|
|
|
221
346
|
throw new EmbeddingsError('provider-response-invalid');
|
|
222
347
|
return input.text;
|
|
223
348
|
});
|
|
349
|
+
const openRouterCanonicalModel = (model) => model === 'openai/text-embedding-3-large' ? 'text-embedding-3-large' : 'text-embedding-3-small';
|
|
224
350
|
class OpenAiProvider {
|
|
225
351
|
route = 'openai';
|
|
226
|
-
model
|
|
227
|
-
space
|
|
352
|
+
model;
|
|
353
|
+
space;
|
|
228
354
|
maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
|
|
229
355
|
maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
|
|
230
356
|
#encoding = getEncoding('cl100k_base');
|
|
231
357
|
#key;
|
|
232
|
-
constructor(key) {
|
|
358
|
+
constructor(model, key) {
|
|
359
|
+
this.model = model;
|
|
360
|
+
this.space = openaiEmbeddingSpace(model);
|
|
233
361
|
this.#key = key;
|
|
234
362
|
}
|
|
235
363
|
async prepare(text, signal) {
|
|
@@ -397,13 +525,15 @@ class GatewayProvider {
|
|
|
397
525
|
}
|
|
398
526
|
class OpenRouterProvider {
|
|
399
527
|
route = 'openrouter';
|
|
400
|
-
model
|
|
401
|
-
space
|
|
528
|
+
model;
|
|
529
|
+
space;
|
|
402
530
|
maxRequestInputs = OPENAI_MAX_REQUEST_INPUTS;
|
|
403
531
|
maxRequestTokens = OPENAI_MAX_REQUEST_TOKENS;
|
|
404
532
|
#encoding = getEncoding('cl100k_base');
|
|
405
533
|
#key;
|
|
406
|
-
constructor(key) {
|
|
534
|
+
constructor(model, key) {
|
|
535
|
+
this.model = model;
|
|
536
|
+
this.space = openaiEmbeddingSpace(openRouterCanonicalModel(model));
|
|
407
537
|
this.#key = key;
|
|
408
538
|
}
|
|
409
539
|
async prepare(text, signal) {
|
|
@@ -434,6 +564,195 @@ class OpenRouterProvider {
|
|
|
434
564
|
// js-tiktoken is pure JavaScript and owns no process or handle.
|
|
435
565
|
}
|
|
436
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
|
+
}
|
|
437
756
|
class CloudflareProvider {
|
|
438
757
|
route = 'cloudflare';
|
|
439
758
|
model = CLOUDFLARE_EMBEDDING_MODELS[0];
|
|
@@ -552,11 +871,14 @@ export async function acquireProvider({ settings, route, signal, credentialResol
|
|
|
552
871
|
const acquired = await acquireLocalRuntime({ executable, modelPath, port: local.port ?? 8791 }, signal);
|
|
553
872
|
return { provider: acquired.provider, release: acquired.release };
|
|
554
873
|
}
|
|
555
|
-
case 'openai':
|
|
874
|
+
case 'openai': {
|
|
875
|
+
if (!isOneOf(OPENAI_EMBEDDING_MODELS, route.model))
|
|
876
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
556
877
|
return {
|
|
557
|
-
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)),
|
|
558
879
|
release: noRelease,
|
|
559
880
|
};
|
|
881
|
+
}
|
|
560
882
|
case 'sarvam':
|
|
561
883
|
return {
|
|
562
884
|
provider: new SarvamProvider(credential(settings.providers?.sarvam?.apiKey, process.env.SARVAM_API_KEY)),
|
|
@@ -579,11 +901,14 @@ export async function acquireProvider({ settings, route, signal, credentialResol
|
|
|
579
901
|
release: noRelease,
|
|
580
902
|
};
|
|
581
903
|
}
|
|
582
|
-
case 'openrouter':
|
|
904
|
+
case 'openrouter': {
|
|
905
|
+
if (!isOneOf(OPENROUTER_EMBEDDING_MODELS, route.model))
|
|
906
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
583
907
|
return {
|
|
584
|
-
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)),
|
|
585
909
|
release: noRelease,
|
|
586
910
|
};
|
|
911
|
+
}
|
|
587
912
|
case 'cloudflare': {
|
|
588
913
|
const configured = settings.providers?.cloudflare;
|
|
589
914
|
const accountId = trim(configured?.accountId) ?? trim(process.env.CLOUDFLARE_ACCOUNT_ID);
|
|
@@ -636,6 +961,65 @@ export async function acquireProvider({ settings, route, signal, credentialResol
|
|
|
636
961
|
release: noRelease,
|
|
637
962
|
};
|
|
638
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
|
+
};
|
|
639
1023
|
}
|
|
640
1024
|
}
|
|
641
1025
|
export const spaceForRoute = (route, settings) => {
|
|
@@ -643,9 +1027,42 @@ export const spaceForRoute = (route, settings) => {
|
|
|
643
1027
|
case 'local':
|
|
644
1028
|
return LOCAL_EMBEDDING_SPACE;
|
|
645
1029
|
case 'openai':
|
|
1030
|
+
if (!isOneOf(OPENAI_EMBEDDING_MODELS, route.model))
|
|
1031
|
+
throw new EmbeddingsError('configuration-invalid');
|
|
1032
|
+
return openaiEmbeddingSpace(route.model);
|
|
646
1033
|
case 'gateway':
|
|
647
|
-
case 'openrouter':
|
|
648
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;
|
|
649
1066
|
case 'sarvam':
|
|
650
1067
|
return SARVAM_EMBEDDING_SPACE;
|
|
651
1068
|
case 'cloudflare':
|
package/dist/response.d.ts
CHANGED
|
@@ -41,3 +41,26 @@ export declare function parseCloudflareBatchResponse(args: {
|
|
|
41
41
|
space: EmbeddingSpace;
|
|
42
42
|
expectedCount: number;
|
|
43
43
|
}): ProviderBatchResult;
|
|
44
|
+
/** Voyage reports `usage.total_tokens` rather than an OpenAI `prompt_tokens` count. */
|
|
45
|
+
export declare function parseVoyageBatchResponse(args: {
|
|
46
|
+
response: unknown;
|
|
47
|
+
space: EmbeddingSpace;
|
|
48
|
+
expectedModels: readonly string[];
|
|
49
|
+
expectedCount: number;
|
|
50
|
+
}): ProviderBatchResult;
|
|
51
|
+
/** Hetzner documents no embedding usage payload, so a missing count stays explicitly unknown. */
|
|
52
|
+
export declare function parseOptionalUsageBatchResponse(args: {
|
|
53
|
+
response: unknown;
|
|
54
|
+
space: EmbeddingSpace;
|
|
55
|
+
expectedModels: readonly string[];
|
|
56
|
+
expectedCount: number;
|
|
57
|
+
}): ProviderBatchResult;
|
|
58
|
+
/**
|
|
59
|
+
* Cohere `/v2/embed` returns embeddings grouped by type in input order and echoes no model id.
|
|
60
|
+
* Only the requested float vectors are accepted; the count and declared dimension are enforced.
|
|
61
|
+
*/
|
|
62
|
+
export declare function parseCohereBatchResponse(args: {
|
|
63
|
+
response: unknown;
|
|
64
|
+
space: EmbeddingSpace;
|
|
65
|
+
expectedCount: number;
|
|
66
|
+
}): ProviderBatchResult;
|
package/dist/response.js
CHANGED
|
@@ -236,3 +236,118 @@ export function parseCloudflareBatchResponse(args) {
|
|
|
236
236
|
},
|
|
237
237
|
};
|
|
238
238
|
}
|
|
239
|
+
const orderedVectorsResponseSchema = Type.Object({
|
|
240
|
+
model: Type.Optional(Type.String({ minLength: 1 })),
|
|
241
|
+
data: Type.Array(Type.Object({
|
|
242
|
+
index: Type.Integer({ minimum: 0 }),
|
|
243
|
+
embedding: Type.Array(Type.Number()),
|
|
244
|
+
})),
|
|
245
|
+
});
|
|
246
|
+
const voyageUsageSchema = Type.Object({ total_tokens: Type.Integer({ minimum: 0 }) });
|
|
247
|
+
const promptTokensUsageSchema = Type.Object({
|
|
248
|
+
prompt_tokens: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
249
|
+
});
|
|
250
|
+
/**
|
|
251
|
+
* Ordered one-vector-per-input response for providers that report usage under their own field names
|
|
252
|
+
* or not at all. The declared dimension is enforced, so an unexpected vector length fails closed.
|
|
253
|
+
*/
|
|
254
|
+
function parseOrderedVectors(args) {
|
|
255
|
+
if (!Value.Check(orderedVectorsResponseSchema, args.response))
|
|
256
|
+
throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
|
|
257
|
+
const parsed = args.response;
|
|
258
|
+
const knownUsage = {
|
|
259
|
+
providerReportedInputTokens: args.providerReportedInputTokens,
|
|
260
|
+
preparedInputTokens: null,
|
|
261
|
+
};
|
|
262
|
+
const fail = (code) => {
|
|
263
|
+
throw new EmbeddingsError(code, { knownUsage });
|
|
264
|
+
};
|
|
265
|
+
if (parsed.model !== undefined && !args.expectedModels.includes(parsed.model))
|
|
266
|
+
fail('provider-response-mismatch');
|
|
267
|
+
const ordered = [...parsed.data].sort((left, right) => left.index - right.index);
|
|
268
|
+
if (ordered.length !== args.expectedCount || ordered.some((item, index) => item.index !== index))
|
|
269
|
+
fail('provider-response-mismatch');
|
|
270
|
+
let vectors;
|
|
271
|
+
try {
|
|
272
|
+
vectors = ordered.map((item) => normalizeVector(item.embedding, dimensionsOf(args.space)));
|
|
273
|
+
}
|
|
274
|
+
catch (error) {
|
|
275
|
+
if (error instanceof EmbeddingsError)
|
|
276
|
+
fail(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid');
|
|
277
|
+
throw error;
|
|
278
|
+
}
|
|
279
|
+
return {
|
|
280
|
+
vectors,
|
|
281
|
+
usage: {
|
|
282
|
+
providerReportedInputTokens: args.providerReportedInputTokens,
|
|
283
|
+
preparedInputTokens: null,
|
|
284
|
+
billedTokens: null,
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
const usageField = (response, field) => {
|
|
289
|
+
if (typeof response !== 'object' || response === null || Array.isArray(response))
|
|
290
|
+
return undefined;
|
|
291
|
+
const usage = response.usage;
|
|
292
|
+
if (typeof usage !== 'object' || usage === null || Array.isArray(usage))
|
|
293
|
+
return undefined;
|
|
294
|
+
return usage[field];
|
|
295
|
+
};
|
|
296
|
+
/** Voyage reports `usage.total_tokens` rather than an OpenAI `prompt_tokens` count. */
|
|
297
|
+
export function parseVoyageBatchResponse(args) {
|
|
298
|
+
const usage = (() => {
|
|
299
|
+
const holder = usageField(args.response, 'total_tokens');
|
|
300
|
+
return holder === undefined ? undefined : { total_tokens: holder };
|
|
301
|
+
})();
|
|
302
|
+
if (!Value.Check(voyageUsageSchema, usage))
|
|
303
|
+
throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
|
|
304
|
+
return parseOrderedVectors({ ...args, providerReportedInputTokens: usage.total_tokens });
|
|
305
|
+
}
|
|
306
|
+
/** Hetzner documents no embedding usage payload, so a missing count stays explicitly unknown. */
|
|
307
|
+
export function parseOptionalUsageBatchResponse(args) {
|
|
308
|
+
const reported = usageField(args.response, 'prompt_tokens');
|
|
309
|
+
const usage = reported === undefined ? undefined : { prompt_tokens: reported };
|
|
310
|
+
if (usage !== undefined && !Value.Check(promptTokensUsageSchema, usage))
|
|
311
|
+
throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
|
|
312
|
+
const tokens = Value.Check(promptTokensUsageSchema, usage) ? (usage.prompt_tokens ?? null) : null;
|
|
313
|
+
return parseOrderedVectors({ ...args, providerReportedInputTokens: tokens });
|
|
314
|
+
}
|
|
315
|
+
const cohereResponseSchema = Type.Object({
|
|
316
|
+
embeddings: Type.Object({
|
|
317
|
+
float: Type.Array(Type.Array(Type.Number())),
|
|
318
|
+
}),
|
|
319
|
+
meta: Type.Optional(Type.Object({
|
|
320
|
+
billed_units: Type.Optional(Type.Object({ input_tokens: Type.Optional(Type.Number({ minimum: 0 })) })),
|
|
321
|
+
tokens: Type.Optional(Type.Object({ input_tokens: Type.Optional(Type.Number({ minimum: 0 })) })),
|
|
322
|
+
})),
|
|
323
|
+
});
|
|
324
|
+
/**
|
|
325
|
+
* Cohere `/v2/embed` returns embeddings grouped by type in input order and echoes no model id.
|
|
326
|
+
* Only the requested float vectors are accepted; the count and declared dimension are enforced.
|
|
327
|
+
*/
|
|
328
|
+
export function parseCohereBatchResponse(args) {
|
|
329
|
+
if (!Value.Check(cohereResponseSchema, args.response))
|
|
330
|
+
throw new EmbeddingsError('provider-response-invalid', { knownUsage: {} });
|
|
331
|
+
const parsed = args.response;
|
|
332
|
+
const billed = parsed.meta?.tokens?.input_tokens ?? parsed.meta?.billed_units?.input_tokens ?? null;
|
|
333
|
+
const providerReportedInputTokens = billed === null ? null : Math.round(billed);
|
|
334
|
+
const knownUsage = { providerReportedInputTokens, preparedInputTokens: null };
|
|
335
|
+
const fail = (code) => {
|
|
336
|
+
throw new EmbeddingsError(code, { knownUsage });
|
|
337
|
+
};
|
|
338
|
+
if (parsed.embeddings.float.length !== args.expectedCount)
|
|
339
|
+
fail('provider-response-mismatch');
|
|
340
|
+
let vectors;
|
|
341
|
+
try {
|
|
342
|
+
vectors = parsed.embeddings.float.map((vector) => normalizeVector(vector, dimensionsOf(args.space)));
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
if (error instanceof EmbeddingsError)
|
|
346
|
+
fail(error.code === 'vector-zero' ? 'vector-zero' : 'vector-invalid');
|
|
347
|
+
throw error;
|
|
348
|
+
}
|
|
349
|
+
return {
|
|
350
|
+
vectors,
|
|
351
|
+
usage: { providerReportedInputTokens, preparedInputTokens: null, billedTokens: null },
|
|
352
|
+
};
|
|
353
|
+
}
|