@abhishek944/pi-embeddings 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/README.md +87 -2
- package/dist/errors.d.ts +21 -0
- package/dist/errors.js +41 -0
- package/dist/execute.d.ts +25 -0
- package/dist/execute.js +229 -0
- package/dist/extension.d.ts +2 -0
- package/dist/extension.js +195 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/local-runtime.d.ts +14 -0
- package/dist/local-runtime.js +246 -0
- package/dist/mcp-cli.d.ts +2 -0
- package/dist/mcp-cli.js +46 -0
- package/dist/mcp-server.d.ts +23 -0
- package/dist/mcp-server.js +154 -0
- package/dist/provider-http.d.ts +11 -0
- package/dist/provider-http.js +60 -0
- package/dist/provider-types.d.ts +30 -0
- package/dist/provider-types.js +1 -0
- package/dist/providers.d.ts +18 -0
- package/dist/providers.js +265 -0
- package/dist/response.d.ts +11 -0
- package/dist/response.js +62 -0
- package/dist/runtime.d.ts +19 -0
- package/dist/runtime.js +121 -0
- package/dist/schemas.d.ts +431 -0
- package/dist/schemas.js +214 -0
- package/dist/settings-write.d.ts +9 -0
- package/dist/settings-write.js +77 -0
- package/dist/settings.d.ts +8 -0
- package/dist/settings.js +97 -0
- package/dist/tool-contracts.d.ts +200 -0
- package/dist/tool-contracts.js +19 -0
- package/package.json +83 -4
- package/src/errors.ts +52 -0
- package/src/execute.ts +261 -0
- package/src/extension.ts +245 -0
- package/src/index.ts +37 -0
- package/src/local-runtime.ts +273 -0
- package/src/mcp-cli.ts +52 -0
- package/src/mcp-server.ts +206 -0
- package/src/provider-http.ts +67 -0
- package/src/provider-types.ts +33 -0
- package/src/providers.ts +335 -0
- package/src/response.ts +74 -0
- package/src/runtime.ts +146 -0
- package/src/schemas.ts +326 -0
- package/src/settings-write.ts +96 -0
- package/src/settings.ts +115 -0
- package/src/tool-contracts.ts +34 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,88 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-embeddings
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Config-driven text embeddings for Pi and MCP. The package owns provider configuration, credentials, request construction, preparation, mandatory batching, transport, local runtime lifecycle, validation, normalization, fallback, explicit comparison and usage accounting. Callers own storage and compatibility decisions.
|
|
4
|
+
|
|
5
|
+
## Public surfaces
|
|
6
|
+
|
|
7
|
+
- `@abhishek944/pi-embeddings` — typed library factory and derived public types. No Pi runtime imports.
|
|
8
|
+
- `@abhishek944/pi-embeddings/schemas` — authoritative TypeBox schemas for settings, requests, outcomes, attempts, results, context, descriptors and describe output.
|
|
9
|
+
- `@abhishek944/pi-embeddings/extension` — Pi extension registered in `pi.extensions`.
|
|
10
|
+
- `@abhishek944/pi-embeddings/mcp` — `createEmbeddingsMcpServer`; transport-neutral, no Pi runtime dependency.
|
|
11
|
+
- `pi-embeddings-mcp` — stdio binary. stdout carries JSON-RPC only; diagnostics go to stderr.
|
|
12
|
+
|
|
13
|
+
MCP tools are `embed`, `embed_compare` and `embeddings_describe`. Vectors are returned in `structuredContent.result`; the text content is a short summary. Pi commands are `/embeddings list`, `doctor`, `reload`, `use <provider> <model>` and `compare <text>`.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createEmbeddingsRuntime } from '@abhishek944/pi-embeddings';
|
|
17
|
+
|
|
18
|
+
const runtime = createEmbeddingsRuntime({ settings, cwd });
|
|
19
|
+
const described = runtime.describe();
|
|
20
|
+
const result = await runtime.embed({ inputs: ['Attribute: value'] }, { signal, context });
|
|
21
|
+
await runtime.close();
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
There are no per-call provider, model, endpoint, credential or expected-space parameters. `describe` is provider-free information, not a reservation or a caller storage policy.
|
|
25
|
+
|
|
26
|
+
## Settings
|
|
27
|
+
|
|
28
|
+
Settings live under the `pi-embeddings` namespace. Pi loading follows global < agent config < explicitly trusted project; environment interpolation applies only to the global and agent layers. A standalone CLI never reads project settings. A service host passes operator-approved settings explicitly.
|
|
29
|
+
|
|
30
|
+
```json
|
|
31
|
+
{
|
|
32
|
+
"pi-embeddings": {
|
|
33
|
+
"version": 1,
|
|
34
|
+
"default": { "provider": "local", "model": "embeddinggemma-2" },
|
|
35
|
+
"fallback": [{ "provider": "openai", "model": "text-embedding-3-small" }],
|
|
36
|
+
"compare": [{ "provider": "sarvam", "model": "embeddinggemma-2" }],
|
|
37
|
+
"providers": {
|
|
38
|
+
"local": {
|
|
39
|
+
"executable": "/operator-supplied/runtime/llama-server",
|
|
40
|
+
"modelPath": "/operator-supplied/model/embeddinggemma-2-Q8_0.gguf"
|
|
41
|
+
},
|
|
42
|
+
"openai": { "apiKey": "${OPENAI_API_KEY}" },
|
|
43
|
+
"sarvam": { "apiKey": "${SARVAM_API_KEY}" },
|
|
44
|
+
"gateway": {
|
|
45
|
+
"baseUrl": "https://operator-gateway.example",
|
|
46
|
+
"apiKey": "${LITELLM_INFERENCE_KEY}",
|
|
47
|
+
"model": "openai/text-embedding-3-small",
|
|
48
|
+
"stage": "dev"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Provider IDs are route identifiers: `local`, `openai`, `sarvam` and `gateway`. Only the declared model pairs are valid. Omitted or empty `fallback` and `compare` lists are inactive. No route is activated by a schema annotation, a present key or existing model files.
|
|
56
|
+
|
|
57
|
+
Ordinary calls use the configured default, then configured fallback in order, advancing only for typed missing credentials or HTTP 401/404/429. There is no fallback for 403, refusal, 400/422, invalid input or vector, malformed response, ambiguous network failure, timeout, 5xx or cancellation. Successful inputs are never replayed on another route. Explicit comparison runs exactly the configured compare list in order, without fallback, ranking or default mutation.
|
|
58
|
+
|
|
59
|
+
## Routes and batching
|
|
60
|
+
|
|
61
|
+
- `local`: pinned EmbeddingGemma 2 Q8 CPU, 768 dimensions. The operator supplies assets; the package verifies the exact model hash and runtime commit, starts only its own loopback child, uses CPU-only flags, shares it across acquisitions and closes it once. No download, install, global binary search, warmup or foreign listener takeover.
|
|
62
|
+
- `openai`: `text-embedding-3-small`, 1536 dimensions. Complete prefixed strings are submitted; `cl100k_base` counts the exact prepared string and a local encode/decode round-trip is checked. Mandatory limits are 8192 tokens per input, 2048 inputs and 300000 tokens per request.
|
|
63
|
+
- `sarvam`: hosted `embeddinggemma-2`, 768 dimensions. Strings are submitted and the service enforces its documented per-string token estimate; no local count or borrowed aggregate cap is invented.
|
|
64
|
+
- `gateway`: the declared OpenAI recipe through LiteLLM. Only `text-embedding-3-small` and `openai/text-embedding-3-small` aliases are supported. One request carries generic host attribution as `x-litellm-customer-id` and `x-litellm-tags`; missing or unsafe attribution refuses before inference.
|
|
65
|
+
|
|
66
|
+
The package supplies the document prefix `title: none | text: ` exactly once and normalizes vectors with the recorded stable L2 identity. It never summarizes, trims, chunks or truncates input text.
|
|
67
|
+
|
|
68
|
+
## MCP attribution
|
|
69
|
+
|
|
70
|
+
Hosts pass generic attribution in `params._meta` under `pi-embeddings/context`:
|
|
71
|
+
|
|
72
|
+
```json
|
|
73
|
+
{ "pi-embeddings/context": { "endUser": "verified-owner", "tags": ["stage:dev", "base:..."] } }
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
This is attribution only. The authenticated server-to-server boundary supplies caller authority; metadata is never proof of ownership and cannot include provider, model, endpoint or credential overrides.
|
|
77
|
+
|
|
78
|
+
## Generating spaces
|
|
79
|
+
|
|
80
|
+
Descriptors record canonical provider, model, known revision or explicit null, quantization/runtime/pooling provenance, dimensions, preparation prefix and normalization identity. Local and Sarvam remain distinct at 768 dimensions. Direct OpenAI and the declared gateway alias share the OpenAI descriptor only when the effective text, preparation and normalization remain identical. API keys, service URLs and gateway aliases are route metadata, not implicit new spaces.
|
|
81
|
+
|
|
82
|
+
Existing stored vector documents are preserved. Package outcome descriptors allow callers to compare complete identity before persistence; a successful inference from an incompatible space is still reported truthfully.
|
|
83
|
+
|
|
84
|
+
## Limits
|
|
85
|
+
|
|
86
|
+
No application capacity caps are added. Provider request limits above are mandatory documented constraints. Sarvam and local publish no aggregate request cap, so none is invented. No cost estimator or pricing table is included; unknown provider accounting is reported as null.
|
|
87
|
+
|
|
88
|
+
Live cloud or local inference, service deployment and shared database writes are not performed by this package.
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { EmbeddingErrorCode } from './schemas.js';
|
|
2
|
+
/** Fixed, redacted diagnostics. Provider bodies, input text and credentials never enter an error. */
|
|
3
|
+
export type KnownUsage = Readonly<{
|
|
4
|
+
readonly providerReportedInputTokens?: number | null | undefined;
|
|
5
|
+
readonly preparedInputTokens?: number | null | undefined;
|
|
6
|
+
}>;
|
|
7
|
+
export declare class EmbeddingsError extends Error {
|
|
8
|
+
readonly code: EmbeddingErrorCode;
|
|
9
|
+
readonly httpStatus: number | undefined;
|
|
10
|
+
/** Counts already known when a later validation or transport step failed; billing stays unknown. */
|
|
11
|
+
readonly knownUsage: KnownUsage | undefined;
|
|
12
|
+
constructor(code: EmbeddingErrorCode, options?: {
|
|
13
|
+
httpStatus?: number;
|
|
14
|
+
knownUsage?: KnownUsage;
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
export declare const codeOf: (error: unknown) => EmbeddingErrorCode;
|
|
18
|
+
/** Only these typed failures may advance an ordinary call to the next configured fallback route. */
|
|
19
|
+
export declare const fallbackCodeForStatus: (status: number) => EmbeddingErrorCode | undefined;
|
|
20
|
+
export declare const isFallbackError: (error: unknown) => boolean;
|
|
21
|
+
export declare const statusCode: (status: number) => EmbeddingErrorCode;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export class EmbeddingsError extends Error {
|
|
2
|
+
code;
|
|
3
|
+
httpStatus;
|
|
4
|
+
/** Counts already known when a later validation or transport step failed; billing stays unknown. */
|
|
5
|
+
knownUsage;
|
|
6
|
+
constructor(code, options) {
|
|
7
|
+
super(code);
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.httpStatus = options?.httpStatus;
|
|
10
|
+
this.knownUsage = options?.knownUsage;
|
|
11
|
+
this.name = 'EmbeddingsError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export const codeOf = (error) => error instanceof EmbeddingsError ? error.code : 'transport-failed';
|
|
15
|
+
/** Only these typed failures may advance an ordinary call to the next configured fallback route. */
|
|
16
|
+
export const fallbackCodeForStatus = (status) => {
|
|
17
|
+
if (status === 401)
|
|
18
|
+
return 'http-auth';
|
|
19
|
+
if (status === 404)
|
|
20
|
+
return 'http-not-found';
|
|
21
|
+
if (status === 429)
|
|
22
|
+
return 'http-rate-limit';
|
|
23
|
+
return undefined;
|
|
24
|
+
};
|
|
25
|
+
export const isFallbackError = (error) => error instanceof EmbeddingsError &&
|
|
26
|
+
(error.code === 'missing-credentials' ||
|
|
27
|
+
error.code === 'http-auth' ||
|
|
28
|
+
error.code === 'http-not-found' ||
|
|
29
|
+
error.code === 'http-rate-limit');
|
|
30
|
+
export const statusCode = (status) => {
|
|
31
|
+
const fallback = fallbackCodeForStatus(status);
|
|
32
|
+
if (fallback !== undefined)
|
|
33
|
+
return fallback;
|
|
34
|
+
if (status === 403)
|
|
35
|
+
return 'http-forbidden';
|
|
36
|
+
if (status === 400 || status === 422)
|
|
37
|
+
return 'http-bad-request';
|
|
38
|
+
if (status >= 500)
|
|
39
|
+
return 'http-server-error';
|
|
40
|
+
return 'http-bad-request';
|
|
41
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AcquiredProvider } from './providers.js';
|
|
2
|
+
import { type EmbeddingCompareResult, type EmbeddingContext, type EmbeddingRequest, type EmbeddingResult, type EmbeddingRoute } from './schemas.js';
|
|
3
|
+
type ExecuteArgs = Readonly<{
|
|
4
|
+
routes: readonly EmbeddingRoute[];
|
|
5
|
+
request: EmbeddingRequest;
|
|
6
|
+
context: EmbeddingContext | undefined;
|
|
7
|
+
signal: AbortSignal;
|
|
8
|
+
allowFallback: boolean;
|
|
9
|
+
acquire: (route: EmbeddingRoute, signal: AbortSignal) => Promise<AcquiredProvider>;
|
|
10
|
+
idPrefix?: string;
|
|
11
|
+
}>;
|
|
12
|
+
/**
|
|
13
|
+
* Runs one ordinary call or one explicit comparison entry. Successful inputs are never replayed on a
|
|
14
|
+
* fallback route; only unfinished inputs continue. Every input keeps its original zero-based index.
|
|
15
|
+
*/
|
|
16
|
+
export declare function executeEmbeddings(args: ExecuteArgs): Promise<EmbeddingResult>;
|
|
17
|
+
/** Explicit comparison: configured entries only, no fallback, no ranking and no default mutation. */
|
|
18
|
+
export declare function executeCompare(args: {
|
|
19
|
+
routes: readonly EmbeddingRoute[];
|
|
20
|
+
request: EmbeddingRequest;
|
|
21
|
+
context: EmbeddingContext | undefined;
|
|
22
|
+
signal: AbortSignal;
|
|
23
|
+
acquire: (route: EmbeddingRoute, signal: AbortSignal) => Promise<AcquiredProvider>;
|
|
24
|
+
}): Promise<EmbeddingCompareResult>;
|
|
25
|
+
export {};
|
package/dist/execute.js
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { EmbeddingsError, codeOf, isFallbackError } from './errors.js';
|
|
3
|
+
import { EMBEDDINGS_PROTOCOL_VERSION, EMBEDDING_NORMALIZATION_VERSION, } from './schemas.js';
|
|
4
|
+
const cancelled = (index) => ({
|
|
5
|
+
status: 'error',
|
|
6
|
+
index,
|
|
7
|
+
code: 'cancelled',
|
|
8
|
+
attemptId: null,
|
|
9
|
+
});
|
|
10
|
+
const unstarted = (index) => ({
|
|
11
|
+
status: 'error',
|
|
12
|
+
index,
|
|
13
|
+
code: 'unstarted',
|
|
14
|
+
attemptId: null,
|
|
15
|
+
});
|
|
16
|
+
const preparedTokenCount = (input) => input.kind === 'tokens' ? input.tokens.length : (input.tokenCount ?? 0);
|
|
17
|
+
/**
|
|
18
|
+
* Runs one ordinary call or one explicit comparison entry. Successful inputs are never replayed on a
|
|
19
|
+
* fallback route; only unfinished inputs continue. Every input keeps its original zero-based index.
|
|
20
|
+
*/
|
|
21
|
+
export async function executeEmbeddings(args) {
|
|
22
|
+
const prefix = args.idPrefix ?? randomUUID();
|
|
23
|
+
const outcomes = new Array(args.request.inputs.length);
|
|
24
|
+
const attempts = [];
|
|
25
|
+
const failureByIndex = new Map();
|
|
26
|
+
let remaining = args.request.inputs.map((_input, index) => index);
|
|
27
|
+
for (const [routeIndex, route] of args.routes.entries()) {
|
|
28
|
+
if (remaining.length === 0)
|
|
29
|
+
break;
|
|
30
|
+
if (args.signal.aborted) {
|
|
31
|
+
for (const index of remaining)
|
|
32
|
+
outcomes[index] = cancelled(index);
|
|
33
|
+
remaining = [];
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
let acquired;
|
|
37
|
+
try {
|
|
38
|
+
acquired = await args.acquire(route, args.signal);
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
const code = codeOf(error);
|
|
42
|
+
const attemptId = `${prefix}-${routeIndex}-${attempts.length}`;
|
|
43
|
+
attempts.push({
|
|
44
|
+
id: attemptId,
|
|
45
|
+
route: route.provider,
|
|
46
|
+
model: route.model,
|
|
47
|
+
routeIndex,
|
|
48
|
+
status: 'error',
|
|
49
|
+
usage: null,
|
|
50
|
+
errorCode: code,
|
|
51
|
+
});
|
|
52
|
+
for (const index of remaining)
|
|
53
|
+
failureByIndex.set(index, { code, attemptId });
|
|
54
|
+
if (args.allowFallback && isFallbackError(error))
|
|
55
|
+
continue;
|
|
56
|
+
for (const index of remaining)
|
|
57
|
+
outcomes[index] = { status: 'error', index, code, attemptId };
|
|
58
|
+
remaining = [];
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const unfinished = [];
|
|
62
|
+
{
|
|
63
|
+
const provider = acquired.provider;
|
|
64
|
+
const prepared = [];
|
|
65
|
+
for (const index of remaining) {
|
|
66
|
+
if (args.signal.aborted) {
|
|
67
|
+
outcomes[index] = cancelled(index);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
const input = await provider.prepare(args.request.inputs[index] ?? '', args.signal);
|
|
72
|
+
prepared.push({ index, input });
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (args.signal.aborted)
|
|
76
|
+
outcomes[index] = cancelled(index);
|
|
77
|
+
else {
|
|
78
|
+
const code = codeOf(error);
|
|
79
|
+
failureByIndex.set(index, { code, attemptId: null });
|
|
80
|
+
outcomes[index] = { status: 'error', index, code, attemptId: null };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
let batch = [];
|
|
85
|
+
let tokens = 0;
|
|
86
|
+
const flush = async () => {
|
|
87
|
+
if (batch.length === 0)
|
|
88
|
+
return;
|
|
89
|
+
const captured = batch;
|
|
90
|
+
batch = [];
|
|
91
|
+
tokens = 0;
|
|
92
|
+
const attemptId = `${prefix}-${routeIndex}-${attempts.length}`;
|
|
93
|
+
const preparedForBatch = captured.reduce((sum, entry) => sum + preparedTokenCount(entry.input), 0);
|
|
94
|
+
const attempt = {
|
|
95
|
+
id: attemptId,
|
|
96
|
+
route: route.provider,
|
|
97
|
+
model: provider.model,
|
|
98
|
+
routeIndex,
|
|
99
|
+
status: 'success',
|
|
100
|
+
usage: {
|
|
101
|
+
providerReportedInputTokens: null,
|
|
102
|
+
preparedInputTokens: preparedForBatch > 0 ? preparedForBatch : null,
|
|
103
|
+
billedTokens: null,
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
attempts.push(attempt);
|
|
107
|
+
if (args.signal.aborted) {
|
|
108
|
+
attempt.status = 'cancelled';
|
|
109
|
+
for (const entry of captured)
|
|
110
|
+
outcomes[entry.index] = cancelled(entry.index);
|
|
111
|
+
unfinished.push(...captured.map((entry) => entry.index));
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
const result = await provider.embed(captured.map((entry) => entry.input), args.signal, args.context);
|
|
116
|
+
attempt.usage = result.usage;
|
|
117
|
+
if (result.vectors.length !== captured.length)
|
|
118
|
+
throw new EmbeddingsError('provider-response-mismatch');
|
|
119
|
+
for (const [offset, entry] of captured.entries()) {
|
|
120
|
+
const vector = result.vectors[offset];
|
|
121
|
+
if (vector === undefined)
|
|
122
|
+
throw new EmbeddingsError('provider-response-mismatch');
|
|
123
|
+
outcomes[entry.index] = {
|
|
124
|
+
status: 'success',
|
|
125
|
+
index: entry.index,
|
|
126
|
+
vector: [...vector],
|
|
127
|
+
route: route.provider,
|
|
128
|
+
model: provider.model,
|
|
129
|
+
space: provider.space,
|
|
130
|
+
attemptId,
|
|
131
|
+
normalization: EMBEDDING_NORMALIZATION_VERSION,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
const code = codeOf(error);
|
|
137
|
+
attempt.status = 'error';
|
|
138
|
+
attempt.errorCode = code;
|
|
139
|
+
const known = error instanceof EmbeddingsError ? error.knownUsage : undefined;
|
|
140
|
+
if (known !== undefined && attempt.usage !== null)
|
|
141
|
+
attempt.usage = {
|
|
142
|
+
providerReportedInputTokens: known.providerReportedInputTokens ?? attempt.usage.providerReportedInputTokens,
|
|
143
|
+
preparedInputTokens: known.preparedInputTokens ?? attempt.usage.preparedInputTokens,
|
|
144
|
+
billedTokens: null,
|
|
145
|
+
};
|
|
146
|
+
for (const entry of captured)
|
|
147
|
+
failureByIndex.set(entry.index, { code, attemptId });
|
|
148
|
+
if (args.signal.aborted || code === 'cancelled') {
|
|
149
|
+
for (const entry of captured)
|
|
150
|
+
outcomes[entry.index] = cancelled(entry.index);
|
|
151
|
+
}
|
|
152
|
+
else if (args.allowFallback && isFallbackError(error)) {
|
|
153
|
+
unfinished.push(...captured.map((entry) => entry.index));
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
for (const entry of captured)
|
|
157
|
+
outcomes[entry.index] = { status: 'error', index: entry.index, code, attemptId };
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
for (const entry of prepared) {
|
|
162
|
+
const count = preparedTokenCount(entry.input);
|
|
163
|
+
if (batch.length > 0 && (batch.length + 1 > provider.maxRequestInputs || tokens + count > provider.maxRequestTokens))
|
|
164
|
+
await flush();
|
|
165
|
+
batch = [...batch, entry];
|
|
166
|
+
tokens += count;
|
|
167
|
+
}
|
|
168
|
+
await flush();
|
|
169
|
+
}
|
|
170
|
+
remaining = unfinished;
|
|
171
|
+
}
|
|
172
|
+
for (const index of remaining) {
|
|
173
|
+
if (outcomes[index] === undefined)
|
|
174
|
+
outcomes[index] = args.signal.aborted
|
|
175
|
+
? cancelled(index)
|
|
176
|
+
: failureByIndex.get(index) === undefined
|
|
177
|
+
? unstarted(index)
|
|
178
|
+
: {
|
|
179
|
+
status: 'error',
|
|
180
|
+
index,
|
|
181
|
+
code: failureByIndex.get(index)?.code ?? 'unstarted',
|
|
182
|
+
attemptId: failureByIndex.get(index)?.attemptId ?? null,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
|
|
187
|
+
outcomes: outcomes.map((outcome, index) => outcome ?? unstarted(index)),
|
|
188
|
+
attempts,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/** Explicit comparison: configured entries only, no fallback, no ranking and no default mutation. */
|
|
192
|
+
export async function executeCompare(args) {
|
|
193
|
+
const entries = [];
|
|
194
|
+
for (const [index, route] of args.routes.entries()) {
|
|
195
|
+
if (args.signal.aborted) {
|
|
196
|
+
entries.push({
|
|
197
|
+
route: route.provider,
|
|
198
|
+
model: route.model,
|
|
199
|
+
status: 'cancelled',
|
|
200
|
+
result: {
|
|
201
|
+
schemaVersion: EMBEDDINGS_PROTOCOL_VERSION,
|
|
202
|
+
outcomes: args.request.inputs.map((_input, offset) => cancelled(offset)),
|
|
203
|
+
attempts: [],
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const result = await executeEmbeddings({
|
|
209
|
+
routes: [route],
|
|
210
|
+
request: args.request,
|
|
211
|
+
context: args.context,
|
|
212
|
+
signal: args.signal,
|
|
213
|
+
allowFallback: false,
|
|
214
|
+
acquire: args.acquire,
|
|
215
|
+
idPrefix: `compare-${index}-${randomUUID()}`,
|
|
216
|
+
});
|
|
217
|
+
entries.push({
|
|
218
|
+
route: route.provider,
|
|
219
|
+
model: route.model,
|
|
220
|
+
status: result.outcomes.every((outcome) => outcome.status === 'success')
|
|
221
|
+
? 'success'
|
|
222
|
+
: args.signal.aborted
|
|
223
|
+
? 'cancelled'
|
|
224
|
+
: 'error',
|
|
225
|
+
result,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
return { schemaVersion: EMBEDDINGS_PROTOCOL_VERSION, entries };
|
|
229
|
+
}
|