@grafctory/llms 0.0.0-stage → 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/LICENSE +201 -0
- package/README.md +60 -2
- package/dist/quotas.d.ts +59 -0
- package/dist/quotas.d.ts.map +1 -0
- package/dist/quotas.js +98 -0
- package/dist/quotas.js.map +1 -0
- package/dist/usage.d.ts +55 -0
- package/dist/usage.d.ts.map +1 -0
- package/dist/usage.js +40 -0
- package/dist/usage.js.map +1 -0
- package/dist/vectors.d.ts +90 -0
- package/dist/vectors.d.ts.map +1 -0
- package/dist/vectors.js +145 -0
- package/dist/vectors.js.map +1 -0
- package/package.json +64 -4
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,61 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @grafctory/llms
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[![npm][npm-badge]][npm] [![Grafctory][grafctory-badge]][grafctory]
|
|
4
|
+
|
|
5
|
+
[npm-badge]: https://img.shields.io/npm/v/@grafctory/llms
|
|
6
|
+
[npm]: https://www.npmjs.com/package/@grafctory/llms
|
|
7
|
+
[grafctory-badge]: https://img.shields.io/badge/part%20of-Grafctory-blue
|
|
8
|
+
[grafctory]: https://github.com/grafctory
|
|
9
|
+
|
|
10
|
+
AI tasks and shared services for [@grafctory/llms].
|
|
11
|
+
|
|
12
|
+
Provides the building blocks shared by AI jobs and the model connectors serving them, from embedding vectors that work
|
|
13
|
+
with any model provider to model calls kept within rate quotas and traced to the source of their cost.
|
|
14
|
+
|
|
15
|
+
Jobs using them are set up and run under the [@grafctory/gear] job executor. This
|
|
16
|
+
package contributes building blocks for those jobs, not an execution runtime of its own.
|
|
17
|
+
|
|
18
|
+
[@grafctory/llms]: https://github.com/grafctory/llms
|
|
19
|
+
[@grafctory/gear]: https://github.com/grafctory/gear
|
|
20
|
+
|
|
21
|
+
# Installation
|
|
22
|
+
|
|
23
|
+
```shell
|
|
24
|
+
npm install @grafctory/gear # the job executor
|
|
25
|
+
npm install @grafctory/llms # this package
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
> [!IMPORTANT]
|
|
29
|
+
>
|
|
30
|
+
> Node.js 22 or later is required.
|
|
31
|
+
|
|
32
|
+
> [!WARNING]
|
|
33
|
+
>
|
|
34
|
+
> TypeScript consumers must use `"moduleResolution": "nodenext"/"node16"/"bundler"` in `tsconfig.json`.
|
|
35
|
+
> The legacy `"node"` resolver is not supported.
|
|
36
|
+
|
|
37
|
+
# Usage
|
|
38
|
+
|
|
39
|
+
| Module | Description |
|
|
40
|
+
|-----------------------------------|---------------------|
|
|
41
|
+
| [@grafctory/llms/vectors][vectors] | Embedding vectors |
|
|
42
|
+
| [@grafctory/llms/quotas][quotas] | Model rate quotas |
|
|
43
|
+
| [@grafctory/llms/usage][usage] | Model usage tracing |
|
|
44
|
+
|
|
45
|
+
[vectors]: https://grafctory.github.io/llms/modules/_grafctory_llms.vectors.html
|
|
46
|
+
|
|
47
|
+
[quotas]: https://grafctory.github.io/llms/modules/_grafctory_llms.quotas.html
|
|
48
|
+
|
|
49
|
+
[usage]: https://grafctory.github.io/llms/modules/_grafctory_llms.usage.html
|
|
50
|
+
|
|
51
|
+
# Support
|
|
52
|
+
|
|
53
|
+
- open an [issue](https://github.com/grafctory/llms/issues) to report a problem or to suggest a new feature
|
|
54
|
+
- start a [discussion](https://github.com/grafctory/llms/discussions) to ask a how-to question or to share an idea
|
|
55
|
+
|
|
56
|
+
# License
|
|
57
|
+
|
|
58
|
+
This project is licensed under the Apache 2.0 License –
|
|
59
|
+
see [LICENSE](https://github.com/grafctory/llms?tab=Apache-2.0-1-ov-file) file for details.
|
|
60
|
+
|
|
61
|
+
<sub>Grafctory™ is a trademark of Metreeca srl.</sub>
|
package/dist/quotas.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model rate quotas.
|
|
3
|
+
*
|
|
4
|
+
* Lets a model connector keep concurrent requests to a model within its rate quota, retrying those the provider rejects
|
|
5
|
+
* over it and logging each attempt under the model name, so a long run completes rather than failing on rate limits.
|
|
6
|
+
* Where the provider advertises the request limit of a model, the pace follows it instead of probing it by rejections.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import { type Optional } from "@grafctory/core";
|
|
11
|
+
/**
|
|
12
|
+
* Model rate quota.
|
|
13
|
+
*
|
|
14
|
+
* Submits requests to a single model, paced against an adaptive throttle shared by all of them, so that concurrent
|
|
15
|
+
* consumers of the model keep within its rate quota. Attempts are logged under the model name.
|
|
16
|
+
*
|
|
17
|
+
* Until the provider advertises the request limit of the model, the pace is set by the throttle alone, slowing down on
|
|
18
|
+
* rejections and speeding up on successes; once advertised, the limit caps how fast the throttle may go.
|
|
19
|
+
*/
|
|
20
|
+
export type Quota = {
|
|
21
|
+
/**
|
|
22
|
+
* Submits a request to the model.
|
|
23
|
+
*
|
|
24
|
+
* @typeParam V The type of the value the request resolves to
|
|
25
|
+
*
|
|
26
|
+
* @param request The request to submit, issued anew on every attempt
|
|
27
|
+
* @param recover The recovery deciding whether a rejection is retried: returns the delay in ms the request is to
|
|
28
|
+
* be retried after, 0 leaving the pace to the throttle, or undefined to give up with the rejection
|
|
29
|
+
*
|
|
30
|
+
* @returns The value `request` resolves to, once an attempt succeeds
|
|
31
|
+
*
|
|
32
|
+
* @throws The rejection of the last attempt, if `recover` gives up on it
|
|
33
|
+
*/
|
|
34
|
+
submit<V>(request: () => Promise<V>, recover: (error: unknown) => Optional<number>): Promise<V>;
|
|
35
|
+
/**
|
|
36
|
+
* Caps the pace of the model at the request limit the provider advertises for it.
|
|
37
|
+
*
|
|
38
|
+
* Meant to be called with whatever each response or rejection advertises, as often as the provider replies: requests
|
|
39
|
+
* already waiting keep the pace they were submitted at, so a change of limit takes effect from the next request on.
|
|
40
|
+
*
|
|
41
|
+
* @param limit The number of requests per minute the provider accepts for the model, or undefined if the provider
|
|
42
|
+
* advertises none, leaving the pace as it stands until a later call states a limit
|
|
43
|
+
*
|
|
44
|
+
* @throws {@link !TypeError TypeError} If `limit` is neither undefined nor a positive finite number
|
|
45
|
+
*/
|
|
46
|
+
limit(limit: Optional<number>): void;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Opens the rate quota of a model.
|
|
50
|
+
*
|
|
51
|
+
* Meant for model connectors: a connector opens one quota per model and submits every request to that model through
|
|
52
|
+
* it, so that concurrent jobs drawing on the same model are paced together rather than each at a pace of its own.
|
|
53
|
+
*
|
|
54
|
+
* @param model The id of the model the quota paces requests to
|
|
55
|
+
*
|
|
56
|
+
* @returns A new quota for `model`, pacing only the requests submitted through it
|
|
57
|
+
*/
|
|
58
|
+
export declare function createQuota(model: string): Quota;
|
|
59
|
+
//# sourceMappingURL=quotas.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"quotas.d.ts","sourceRoot":"","sources":["../src/quotas.ts"],"names":[],"mappings":"AAgBA;;;;;;;;GAQG;AAEH,OAAO,EAAU,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAqBxD;;;;;;;;GAQG;AACH,MAAM,MAAM,KAAK,GAAG;IAEnB;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,QAAQ,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IAE/F;;;;;;;;;;OAUG;IACH,KAAK,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,IAAI,CAAA;CAEpC,CAAA;AAKD;;;;;;;;;GASG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,CAsEhD"}
|
package/dist/quotas.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright © 2026 Metreeca srl
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Model rate quotas.
|
|
18
|
+
*
|
|
19
|
+
* Lets a model connector keep concurrent requests to a model within its rate quota, retrying those the provider rejects
|
|
20
|
+
* over it and logging each attempt under the model name, so a long run completes rather than failing on rate limits.
|
|
21
|
+
* Where the provider advertises the request limit of a model, the pace follows it instead of probing it by rejections.
|
|
22
|
+
*
|
|
23
|
+
* @module
|
|
24
|
+
*/
|
|
25
|
+
import { assert } from "@grafctory/core";
|
|
26
|
+
import { createThrottle } from "@grafctory/core/async";
|
|
27
|
+
import { log } from "@grafctory/tape";
|
|
28
|
+
/**
|
|
29
|
+
* The smallest delay in ms a quota leaves between two requests before its model advertises a request limit.
|
|
30
|
+
*
|
|
31
|
+
* Set to the smallest delay the throttle can still back off from: delays are whole ms, so below 5 ms a 1.10 backoff
|
|
32
|
+
* rounds back to the delay it started from and the throttle would keep its pace however many requests are rejected.
|
|
33
|
+
*/
|
|
34
|
+
const Floor = 10;
|
|
35
|
+
/**
|
|
36
|
+
* The largest delay in ms a quota leaves between two requests, however low the limit its model advertises.
|
|
37
|
+
*/
|
|
38
|
+
const Ceiling = 60 * 1000;
|
|
39
|
+
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
40
|
+
/**
|
|
41
|
+
* Opens the rate quota of a model.
|
|
42
|
+
*
|
|
43
|
+
* Meant for model connectors: a connector opens one quota per model and submits every request to that model through
|
|
44
|
+
* it, so that concurrent jobs drawing on the same model are paced together rather than each at a pace of its own.
|
|
45
|
+
*
|
|
46
|
+
* @param model The id of the model the quota paces requests to
|
|
47
|
+
*
|
|
48
|
+
* @returns A new quota for `model`, pacing only the requests submitted through it
|
|
49
|
+
*/
|
|
50
|
+
export function createQuota(model) {
|
|
51
|
+
const logger = log(["/", model]);
|
|
52
|
+
const pace = { floor: Floor, throttle: throttle(Floor) };
|
|
53
|
+
return Object.freeze({
|
|
54
|
+
submit,
|
|
55
|
+
limit
|
|
56
|
+
});
|
|
57
|
+
/**
|
|
58
|
+
* Creates the throttle pacing requests to the model.
|
|
59
|
+
*
|
|
60
|
+
* @param floor The smallest delay in ms the throttle may leave between two requests
|
|
61
|
+
*
|
|
62
|
+
* @returns A new throttle with no requests submitted yet, never pacing faster than `floor`
|
|
63
|
+
*/
|
|
64
|
+
function throttle(floor) {
|
|
65
|
+
return createThrottle({
|
|
66
|
+
minimum: floor,
|
|
67
|
+
maximum: Ceiling,
|
|
68
|
+
buildup: 1.10,
|
|
69
|
+
backoff: 1.10,
|
|
70
|
+
recover: 0.95
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
function submit(request, recover) {
|
|
74
|
+
return pace.throttle.retry(request, {
|
|
75
|
+
recover,
|
|
76
|
+
monitor: (attempt, attempts, elapsed) => {
|
|
77
|
+
const count = attempts > 0 ? `${attempt + 1}/${attempts}` : `${attempt + 1}`;
|
|
78
|
+
if (elapsed === undefined) {
|
|
79
|
+
logger.error `request attempt ${count} aborted`;
|
|
80
|
+
}
|
|
81
|
+
else if (attempt > 0) {
|
|
82
|
+
logger.warning `request attempt ${count} rejected with delay ${elapsed} ms`;
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
logger.info `request attempt ${count} submitted with delay ${elapsed} ms`;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function limit(limit) {
|
|
91
|
+
const $limit = assert(limit, limit => limit === undefined || Number.isFinite(limit) && limit > 0, `illegal request limit <${limit}>`);
|
|
92
|
+
const floor = $limit === undefined ? pace.floor : Math.min(Math.ceil(60 * 1000 / $limit), Ceiling);
|
|
93
|
+
if (floor !== pace.floor) {
|
|
94
|
+
Object.assign(pace, { floor, throttle: throttle(floor) });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
//# sourceMappingURL=quotas.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"quotas.js","sourceRoot":"","sources":["../src/quotas.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;;;;;GAQG;AAEH,OAAO,EAAE,MAAM,EAAiB,MAAM,iBAAiB,CAAC;AACxD,OAAO,EAAE,cAAc,EAAiB,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAGtC;;;;;GAKG;AACH,MAAM,KAAK,GAAG,EAAE,CAAC;AAEjB;;GAEG;AACH,MAAM,OAAO,GAAG,EAAE,GAAC,IAAI,CAAC;AA+CxB,wHAAwH;AAExH;;;;;;;;;GASG;AACH,MAAM,UAAU,WAAW,CAAC,KAAa;IAExC,MAAM,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;IAEjC,MAAM,IAAI,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;IAGzD,OAAO,MAAM,CAAC,MAAM,CAAC;QACpB,MAAM;QACN,KAAK;KACL,CAAC,CAAC;IAGH;;;;;;OAMG;IACH,SAAS,QAAQ,CAAC,KAAa;QAE9B,OAAO,cAAc,CAAC;YACrB,OAAO,EAAE,KAAK;YACd,OAAO,EAAE,OAAO;YAChB,OAAO,EAAE,IAAI;YACb,OAAO,EAAE,IAAI;YACb,OAAO,EAAE,IAAI;SACb,CAAC,CAAC;IAEJ,CAAC;IAED,SAAS,MAAM,CAAI,OAAyB,EAAE,OAA6C;QAE1F,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,EAAE;YAEnC,OAAO;YAEP,OAAO,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE;gBAEvC,MAAM,KAAK,GAAG,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,GAAC,CAAC,IAAI,QAAQ,EAAE,CAAC,CAAC,CAAC,GAAG,OAAO,GAAC,CAAC,EAAE,CAAC;gBAEzE,IAAK,OAAO,KAAK,SAAS,EAAG,CAAC;oBAC7B,MAAM,CAAC,KAAK,CAAA,mBAAmB,KAAK,UAAU,CAAC;gBAChD,CAAC;qBAAM,IAAK,OAAO,GAAG,CAAC,EAAG,CAAC;oBAC1B,MAAM,CAAC,OAAO,CAAA,mBAAmB,KAAK,wBAAwB,OAAO,KAAK,CAAC;gBAC5E,CAAC;qBAAM,CAAC;oBACP,MAAM,CAAC,IAAI,CAAA,mBAAmB,KAAK,yBAAyB,OAAO,KAAK,CAAC;gBAC1E,CAAC;YAEF,CAAC;SAED,CAAC,CAAC;IAEJ,CAAC;IAED,SAAS,KAAK,CAAC,KAAuB;QAErC,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAC/F,0BAA0B,KAAK,GAAG,CAClC,CAAC;QAEF,MAAM,KAAK,GAAG,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,GAAC,IAAI,GAAC,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;QAE/F,IAAK,KAAK,KAAK,IAAI,CAAC,KAAK,EAAG,CAAC;YAC5B,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC3D,CAAC;IAEF,CAAC;AAEF,CAAC"}
|
package/dist/usage.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model request labels.
|
|
3
|
+
*
|
|
4
|
+
* Identify the source the {@link Usage} of a request is attributed to: each key names a label, such as `job` or
|
|
5
|
+
* `team`, and its value identifies the source along that label, such as `events-loader` or `data`.
|
|
6
|
+
*
|
|
7
|
+
* The labels of a request are logged with its usage (see {@link charge}). Where the provider accepts them, they are
|
|
8
|
+
* also attached to the request itself, so its cost is split by source in the provider billing reports as well.
|
|
9
|
+
*
|
|
10
|
+
* > [!NOTE]
|
|
11
|
+
* >
|
|
12
|
+
* > Each provider sets its own limits on keys, values and their number: model connectors bring labels within the
|
|
13
|
+
* > limits of their provider before attaching them to a request, and log them as supplied.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
*
|
|
17
|
+
* ```typescript
|
|
18
|
+
* const labels: Labels = { job: "events-loader", team: "data" };
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export type Labels = {
|
|
22
|
+
readonly [label: string]: string;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Token usage of a model request.
|
|
26
|
+
*
|
|
27
|
+
* States what a request consumed in the terms all providers bill by, so usage logged for any of them reads alike. Usage
|
|
28
|
+
* is attributed to its source by the {@link Labels} of the request, and logged together with them by {@link charge}.
|
|
29
|
+
*/
|
|
30
|
+
export type Usage = {
|
|
31
|
+
/**
|
|
32
|
+
* The input tokens the request consumed, including those spent on tool use prompts.
|
|
33
|
+
*/
|
|
34
|
+
readonly input: number;
|
|
35
|
+
/**
|
|
36
|
+
* The output tokens the request consumed, including those spent on reasoning.
|
|
37
|
+
*/
|
|
38
|
+
readonly output: number;
|
|
39
|
+
/**
|
|
40
|
+
* The output tokens the request spent on reasoning alone.
|
|
41
|
+
*/
|
|
42
|
+
readonly reasoning: number;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Logs the token usage of a model request.
|
|
46
|
+
*
|
|
47
|
+
* Meant for model connectors, which log every request they issue. Each entry is filed under the model and states the
|
|
48
|
+
* labels and tokens of the request, so a cost spike can be traced to its source from the log alone.
|
|
49
|
+
*
|
|
50
|
+
* @param model The id of the model the request was submitted to
|
|
51
|
+
* @param labels The labels identifying the cost source of the request
|
|
52
|
+
* @param usage The tokens the request consumed
|
|
53
|
+
*/
|
|
54
|
+
export declare function charge(model: string, labels: Labels, usage: Usage): void;
|
|
55
|
+
//# sourceMappingURL=usage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usage.d.ts","sourceRoot":"","sources":["../src/usage.ts"],"names":[],"mappings":"AA6BA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,MAAM,MAAM,GAAG;IAEpB,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAAA;CAEhC,CAAA;AAED;;;;;GAKG;AACH,MAAM,MAAM,KAAK,GAAG;IAEnB;;OAEG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IAEtB;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IAEvB;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;CAE1B,CAAA;AAKD;;;;;;;;;GASG;AACH,wBAAgB,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI,CAOxE"}
|
package/dist/usage.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright © 2026 Metreeca srl
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Model usage tracing.
|
|
18
|
+
*
|
|
19
|
+
* Attributes model calls to the source of their cost, such as the job or team issuing them, and logs the tokens each
|
|
20
|
+
* call consumes with its labels, so that spend can be traced to its source from the log and in provider billing
|
|
21
|
+
* reports.
|
|
22
|
+
*
|
|
23
|
+
* @module
|
|
24
|
+
*/
|
|
25
|
+
import { log } from "@grafctory/tape";
|
|
26
|
+
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
27
|
+
/**
|
|
28
|
+
* Logs the token usage of a model request.
|
|
29
|
+
*
|
|
30
|
+
* Meant for model connectors, which log every request they issue. Each entry is filed under the model and states the
|
|
31
|
+
* labels and tokens of the request, so a cost spike can be traced to its source from the log alone.
|
|
32
|
+
*
|
|
33
|
+
* @param model The id of the model the request was submitted to
|
|
34
|
+
* @param labels The labels identifying the cost source of the request
|
|
35
|
+
* @param usage The tokens the request consumed
|
|
36
|
+
*/
|
|
37
|
+
export function charge(model, labels, usage) {
|
|
38
|
+
log(["/", model]).info("tokens {input} in · {output} out · {reasoning} reasoning · {labels}", { model, labels, ...usage });
|
|
39
|
+
}
|
|
40
|
+
//# sourceMappingURL=usage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usage.js","sourceRoot":"","sources":["../src/usage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;;;;;GAQG;AAEH,OAAO,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAuDtC,wHAAwH;AAExH;;;;;;;;;GASG;AACH,MAAM,UAAU,MAAM,CAAC,KAAa,EAAE,MAAc,EAAE,KAAY;IAEjE,GAAG,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,CACrB,qEAAqE,EACrE,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,KAAK,EAAE,CAC3B,CAAC;AAEH,CAAC"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Embedding vectors.
|
|
3
|
+
*
|
|
4
|
+
* Works with embedding vectors from any model provider: condense the fields of a resource into the text to embed, rank
|
|
5
|
+
* vectors by semantic proximity, and store them compactly as text, at a fraction of the size of their JSON form.
|
|
6
|
+
*
|
|
7
|
+
* @module
|
|
8
|
+
*/
|
|
9
|
+
import { type Some } from "@grafctory/core/arrays";
|
|
10
|
+
import type { Text } from "@grafctory/core/strings";
|
|
11
|
+
/**
|
|
12
|
+
* A vector.
|
|
13
|
+
*
|
|
14
|
+
* Holds the components positioning a point in a multi-dimensional space, for instance the embedding of a text in a
|
|
15
|
+
* semantic space. Components are matched by position, so two vectors are comparable only if produced by the same
|
|
16
|
+
* source.
|
|
17
|
+
*/
|
|
18
|
+
export type Vector = readonly number[];
|
|
19
|
+
/**
|
|
20
|
+
* A distance between two vectors.
|
|
21
|
+
*
|
|
22
|
+
* Measures how far apart two vectors are: a smaller value means a closer pair. Scale and range depend on the measure,
|
|
23
|
+
* so a distance carries no absolute meaning: it is useful for ranking and for comparison against thresholds tuned for
|
|
24
|
+
* the same measure.
|
|
25
|
+
*/
|
|
26
|
+
export type Distance = number;
|
|
27
|
+
/**
|
|
28
|
+
* Builds the synopsis of a resource.
|
|
29
|
+
*
|
|
30
|
+
* Condenses the fields describing a resource into a single text, for instance the text to be embedded for it.
|
|
31
|
+
* Fragments are trimmed, blank and undefined ones are dropped, and the rest are joined one per line. Every field of a
|
|
32
|
+
* resource can thus be passed in as it stands, without first filtering out the unset ones.
|
|
33
|
+
*
|
|
34
|
+
* @param values The fragments describing the resource; each is a single text, a collection of texts or undefined, so
|
|
35
|
+
* that repeatable and optional properties can be passed in directly from the resource holding them
|
|
36
|
+
*
|
|
37
|
+
* @returns The synopsis of the resource, or an empty text if no fragment carries any text
|
|
38
|
+
*/
|
|
39
|
+
export declare function synopsis(...values: readonly Some<Text>[]): Text;
|
|
40
|
+
/**
|
|
41
|
+
* Computes the cosine distance between two vectors.
|
|
42
|
+
*
|
|
43
|
+
* Cosine distance is defined as `1 - cosine similarity`, where cosine similarity measures the cosine of the angle
|
|
44
|
+
* between two vectors in n-dimensional space: values range from 0 to 2, with 0 for identical direction, 1 for
|
|
45
|
+
* orthogonality and 2 for opposite directions.
|
|
46
|
+
*
|
|
47
|
+
* Only vectors of the same length are comparable, as components are matched by position: vectors of different length,
|
|
48
|
+
* as produced by different sources, are rejected rather than reconciled.
|
|
49
|
+
*
|
|
50
|
+
* @param x The first vector
|
|
51
|
+
* @param y The second vector
|
|
52
|
+
*
|
|
53
|
+
* @returns The cosine distance between `x` and `y`
|
|
54
|
+
*
|
|
55
|
+
* @throws {@link !RangeError RangeError} If `x` and `y` have different lengths, if either carries a non-finite
|
|
56
|
+
* component, or if either has a zero norm, that is if it is empty or all its components are 0
|
|
57
|
+
*
|
|
58
|
+
* @see {@link https://en.wikipedia.org/wiki/Cosine_similarity Cosine similarity}
|
|
59
|
+
*/
|
|
60
|
+
export declare function cosine(x: Vector, y: Vector): Distance;
|
|
61
|
+
/**
|
|
62
|
+
* Compresses a vector to a compact textual form.
|
|
63
|
+
*
|
|
64
|
+
* Trades precision for size, quantising components to 16-bit integers and encoding them as base64 text: storage
|
|
65
|
+
* shrinks by roughly 75% compared to a JSON array, at a loss negligible for similarity ranking. Components must lie
|
|
66
|
+
* in the `[-1, 1]` range, as they do in a normalised vector: values outside it are rejected rather than silently
|
|
67
|
+
* wrapped around by the conversion.
|
|
68
|
+
*
|
|
69
|
+
* @param vector The vector to compress
|
|
70
|
+
*
|
|
71
|
+
* @returns The compact textual form of `vector`, to be restored by {@link decompress}
|
|
72
|
+
*
|
|
73
|
+
* @throws {@link !RangeError RangeError} If `vector` carries a non-finite component or a component outside the
|
|
74
|
+
* `[-1, 1]` range
|
|
75
|
+
*/
|
|
76
|
+
export declare function compress(vector: Vector): string;
|
|
77
|
+
/**
|
|
78
|
+
* Decompresses a vector from its compact textual form.
|
|
79
|
+
*
|
|
80
|
+
* Restores components to the `[-1, 1]` range, approximating the original values within the quantisation step applied
|
|
81
|
+
* by {@link compress}. Truncated input is rejected rather than restored as a silently shortened vector.
|
|
82
|
+
*
|
|
83
|
+
* @param vector The compact textual form of the vector to restore, as produced by {@link compress}
|
|
84
|
+
*
|
|
85
|
+
* @returns The vector encoded by `vector`
|
|
86
|
+
*
|
|
87
|
+
* @throws {@link !RangeError RangeError} If `vector` doesn't decode to a whole number of components
|
|
88
|
+
*/
|
|
89
|
+
export declare function decompress(vector: string): Vector;
|
|
90
|
+
//# sourceMappingURL=vectors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vectors.d.ts","sourceRoot":"","sources":["../src/vectors.ts"],"names":[],"mappings":"AAgBA;;;;;;;GAOG;AAEH,OAAO,EAAQ,KAAK,IAAI,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAgBpD;;;;;;GAMG;AACH,MAAM,MAAM,MAAM,GACjB,SAAS,MAAM,EAAE,CAAA;AAElB;;;;;;GAMG;AACH,MAAM,MAAM,QAAQ,GACnB,MAAM,CAAA;AAKP;;;;;;;;;;;GAWG;AACH,wBAAgB,QAAQ,CAAC,GAAG,MAAM,EAAE,SAAS,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,CAQ/D;AAKD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,MAAM,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,QAAQ,CAoCrD;AAKD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAa/C;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAejD"}
|
package/dist/vectors.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright © 2026 Metreeca srl
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Embedding vectors.
|
|
18
|
+
*
|
|
19
|
+
* Works with embedding vectors from any model provider: condense the fields of a resource into the text to embed, rank
|
|
20
|
+
* vectors by semantic proximity, and store them compactly as text, at a fraction of the size of their JSON form.
|
|
21
|
+
*
|
|
22
|
+
* @module
|
|
23
|
+
*/
|
|
24
|
+
import { some } from "@grafctory/core/arrays";
|
|
25
|
+
/**
|
|
26
|
+
* The factor mapping normalised components onto the int16 range under quantisation.
|
|
27
|
+
*
|
|
28
|
+
* States the largest magnitude a signed 16-bit integer carries, so that a component of the `[-1, 1]` range
|
|
29
|
+
* {@link compress} accepts spans the whole encoding and is restored by {@link decompress} within half a step of
|
|
30
|
+
* `1/32767`. The bound is symmetric, leaving `-32768` unused, so that components at either end of the range are
|
|
31
|
+
* quantised alike and none is clipped.
|
|
32
|
+
*/
|
|
33
|
+
const Scale = 32767;
|
|
34
|
+
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
35
|
+
/**
|
|
36
|
+
* Builds the synopsis of a resource.
|
|
37
|
+
*
|
|
38
|
+
* Condenses the fields describing a resource into a single text, for instance the text to be embedded for it.
|
|
39
|
+
* Fragments are trimmed, blank and undefined ones are dropped, and the rest are joined one per line. Every field of a
|
|
40
|
+
* resource can thus be passed in as it stands, without first filtering out the unset ones.
|
|
41
|
+
*
|
|
42
|
+
* @param values The fragments describing the resource; each is a single text, a collection of texts or undefined, so
|
|
43
|
+
* that repeatable and optional properties can be passed in directly from the resource holding them
|
|
44
|
+
*
|
|
45
|
+
* @returns The synopsis of the resource, or an empty text if no fragment carries any text
|
|
46
|
+
*/
|
|
47
|
+
export function synopsis(...values) {
|
|
48
|
+
return values
|
|
49
|
+
.flatMap(value => some(value))
|
|
50
|
+
.map(text => text.trim())
|
|
51
|
+
.filter(text => text !== "")
|
|
52
|
+
.join("\n");
|
|
53
|
+
}
|
|
54
|
+
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
55
|
+
/**
|
|
56
|
+
* Computes the cosine distance between two vectors.
|
|
57
|
+
*
|
|
58
|
+
* Cosine distance is defined as `1 - cosine similarity`, where cosine similarity measures the cosine of the angle
|
|
59
|
+
* between two vectors in n-dimensional space: values range from 0 to 2, with 0 for identical direction, 1 for
|
|
60
|
+
* orthogonality and 2 for opposite directions.
|
|
61
|
+
*
|
|
62
|
+
* Only vectors of the same length are comparable, as components are matched by position: vectors of different length,
|
|
63
|
+
* as produced by different sources, are rejected rather than reconciled.
|
|
64
|
+
*
|
|
65
|
+
* @param x The first vector
|
|
66
|
+
* @param y The second vector
|
|
67
|
+
*
|
|
68
|
+
* @returns The cosine distance between `x` and `y`
|
|
69
|
+
*
|
|
70
|
+
* @throws {@link !RangeError RangeError} If `x` and `y` have different lengths, if either carries a non-finite
|
|
71
|
+
* component, or if either has a zero norm, that is if it is empty or all its components are 0
|
|
72
|
+
*
|
|
73
|
+
* @see {@link https://en.wikipedia.org/wiki/Cosine_similarity Cosine similarity}
|
|
74
|
+
*/
|
|
75
|
+
export function cosine(x, y) {
|
|
76
|
+
if (x.length !== y.length) {
|
|
77
|
+
throw new RangeError(`mismatched embedding lengths <${x.length}>/<${y.length}>`);
|
|
78
|
+
}
|
|
79
|
+
if (!x.every(Number.isFinite)) {
|
|
80
|
+
throw new RangeError("non-finite x embedding components");
|
|
81
|
+
}
|
|
82
|
+
if (!y.every(Number.isFinite)) {
|
|
83
|
+
throw new RangeError("non-finite y embedding components");
|
|
84
|
+
}
|
|
85
|
+
const xnorm = norm(x);
|
|
86
|
+
const ynorm = norm(y);
|
|
87
|
+
if (xnorm === 0) {
|
|
88
|
+
throw new RangeError("zero-length x embedding");
|
|
89
|
+
}
|
|
90
|
+
if (ynorm === 0) {
|
|
91
|
+
throw new RangeError("zero-length y embedding");
|
|
92
|
+
}
|
|
93
|
+
const dot = x.reduce((sum, xi, index) => sum + xi * y[index], 0);
|
|
94
|
+
return 1 - dot / (xnorm * ynorm);
|
|
95
|
+
function norm(embedding) {
|
|
96
|
+
return Math.sqrt(embedding.reduce((sum, component) => sum + component * component, 0));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
|
100
|
+
/**
|
|
101
|
+
* Compresses a vector to a compact textual form.
|
|
102
|
+
*
|
|
103
|
+
* Trades precision for size, quantising components to 16-bit integers and encoding them as base64 text: storage
|
|
104
|
+
* shrinks by roughly 75% compared to a JSON array, at a loss negligible for similarity ranking. Components must lie
|
|
105
|
+
* in the `[-1, 1]` range, as they do in a normalised vector: values outside it are rejected rather than silently
|
|
106
|
+
* wrapped around by the conversion.
|
|
107
|
+
*
|
|
108
|
+
* @param vector The vector to compress
|
|
109
|
+
*
|
|
110
|
+
* @returns The compact textual form of `vector`, to be restored by {@link decompress}
|
|
111
|
+
*
|
|
112
|
+
* @throws {@link !RangeError RangeError} If `vector` carries a non-finite component or a component outside the
|
|
113
|
+
* `[-1, 1]` range
|
|
114
|
+
*/
|
|
115
|
+
export function compress(vector) {
|
|
116
|
+
if (!vector.every(Number.isFinite)) {
|
|
117
|
+
throw new RangeError("non-finite vector components");
|
|
118
|
+
}
|
|
119
|
+
if (vector.some(component => component < -1 || component > 1)) {
|
|
120
|
+
throw new RangeError("out-of-range vector components");
|
|
121
|
+
}
|
|
122
|
+
const quantised = Int16Array.from(vector, component => Math.round(component * Scale));
|
|
123
|
+
return Buffer.from(quantised.buffer).toString("base64");
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Decompresses a vector from its compact textual form.
|
|
127
|
+
*
|
|
128
|
+
* Restores components to the `[-1, 1]` range, approximating the original values within the quantisation step applied
|
|
129
|
+
* by {@link compress}. Truncated input is rejected rather than restored as a silently shortened vector.
|
|
130
|
+
*
|
|
131
|
+
* @param vector The compact textual form of the vector to restore, as produced by {@link compress}
|
|
132
|
+
*
|
|
133
|
+
* @returns The vector encoded by `vector`
|
|
134
|
+
*
|
|
135
|
+
* @throws {@link !RangeError RangeError} If `vector` doesn't decode to a whole number of components
|
|
136
|
+
*/
|
|
137
|
+
export function decompress(vector) {
|
|
138
|
+
const buffer = Buffer.from(vector, "base64");
|
|
139
|
+
if (buffer.byteLength % Int16Array.BYTES_PER_ELEMENT !== 0) {
|
|
140
|
+
throw new RangeError(`truncated compressed embedding <${buffer.byteLength}>`);
|
|
141
|
+
}
|
|
142
|
+
const quantised = new Int16Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Int16Array.BYTES_PER_ELEMENT);
|
|
143
|
+
return Array.from(quantised, component => component / Scale);
|
|
144
|
+
}
|
|
145
|
+
//# sourceMappingURL=vectors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vectors.js","sourceRoot":"","sources":["../src/vectors.ts"],"names":[],"mappings":"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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@grafctory/llms",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "AI tasks and shared services for @grafctory/llms.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"typescript",
|
|
7
|
+
"pipeline",
|
|
8
|
+
"ai",
|
|
9
|
+
"llm"
|
|
10
|
+
],
|
|
11
|
+
"homepage": "https://grafctory.github.io/llms/",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/grafctory/llms/issues",
|
|
14
|
+
"email": "info@grafctory.dev"
|
|
15
|
+
},
|
|
16
|
+
"license": "Apache-2.0",
|
|
17
|
+
"author": {
|
|
18
|
+
"name": "Metreeca",
|
|
19
|
+
"email": "info@metreeca.com",
|
|
20
|
+
"url": "https://www.metreeca.com/"
|
|
21
|
+
},
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/grafctory/llms.git",
|
|
25
|
+
"directory": "packages/llms"
|
|
26
|
+
},
|
|
27
|
+
"type": "module",
|
|
28
|
+
"sideEffects": false,
|
|
29
|
+
"exports": {
|
|
30
|
+
"./vectors": {
|
|
31
|
+
"@grafctory/source": "./src/vectors.ts",
|
|
32
|
+
"default": "./dist/vectors.js"
|
|
33
|
+
},
|
|
34
|
+
"./quotas": {
|
|
35
|
+
"@grafctory/source": "./src/quotas.ts",
|
|
36
|
+
"default": "./dist/quotas.js"
|
|
37
|
+
},
|
|
38
|
+
"./usage": {
|
|
39
|
+
"@grafctory/source": "./src/usage.ts",
|
|
40
|
+
"default": "./dist/usage.js"
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"files": [
|
|
44
|
+
"README.md",
|
|
45
|
+
"LICENSE",
|
|
46
|
+
"dist"
|
|
47
|
+
],
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=22.22.0"
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"clean": "ush rm dist docs node_modules",
|
|
53
|
+
"build": "ush rm dist && tsc -p tsconfig.build.json",
|
|
54
|
+
"check": "npx vitest --typecheck run"
|
|
55
|
+
},
|
|
56
|
+
"dependencies": {
|
|
57
|
+
"@grafctory/core": "^0.14.2",
|
|
58
|
+
"@grafctory/tape": "^0.13.1"
|
|
59
|
+
},
|
|
60
|
+
"devDependencies": {
|
|
61
|
+
"@types/node": "^25.9.3",
|
|
62
|
+
"typescript": "^6.0.3",
|
|
63
|
+
"vitest": "^4.1.12"
|
|
64
|
+
},
|
|
65
|
+
"peerDependencies": null
|
|
66
|
+
}
|