letsdecide 0.0.0-stage → 0.3.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 +202 -0
- package/README.md +80 -3
- package/conformance.d.ts +21 -0
- package/conformance.js +91 -0
- package/index.d.ts +247 -0
- package/index.js +378 -0
- package/middleware.d.ts +98 -0
- package/middleware.js +385 -0
- package/package.json +30 -6
- package/pkg/letsdecide_wasm.d.ts +68 -0
- package/pkg/letsdecide_wasm.js +488 -0
- package/pkg/letsdecide_wasm_bg.wasm +0 -0
- package/pkg/letsdecide_wasm_bg.wasm.d.ts +19 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,80 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# letsdecide (JavaScript / TypeScript)
|
|
2
|
+
|
|
3
|
+
One request shape for every decision API (Jev, Clef, OpenAI, Gemini). The core
|
|
4
|
+
is Rust compiled to WebAssembly (about 160 KB gzipped); it builds the HTTP request
|
|
5
|
+
and parses the reply, and `fetch` sends it. You call providers directly with
|
|
6
|
+
your own keys. There is no gateway.
|
|
7
|
+
|
|
8
|
+
Works in Node, browsers and edge runtimes. Includes TypeScript types.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install letsdecide
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```js
|
|
19
|
+
import { Client } from "letsdecide";
|
|
20
|
+
|
|
21
|
+
// Settings go per provider, so a key is only ever sent to its own provider.
|
|
22
|
+
const client = new Client({
|
|
23
|
+
byProvider: { gemini: { apiKey: process.env.GEMINI_API_KEY } },
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const result = await client.decide("gemini/gemini-decision-1", {
|
|
27
|
+
input: "I was charged twice.",
|
|
28
|
+
questions: {
|
|
29
|
+
billing: { kind: "yesno", instructions: "Is this about billing?" },
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
result.answers.billing; // { kind: "yesno", probability: 0.97 }
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
In Node, pass the WASM bytes (see [Node](#node) below). Browsers and edge
|
|
37
|
+
runtimes load it by themselves.
|
|
38
|
+
|
|
39
|
+
Change the model string (`"provider/model"`) to change provider. Supported:
|
|
40
|
+
`jev/<model>`, `clef/<model>`, `gemini/<model>`, `openai/<model>` and
|
|
41
|
+
`systemone/<model>` for any System One compatible server.
|
|
42
|
+
|
|
43
|
+
### Node
|
|
44
|
+
|
|
45
|
+
Node's `fetch` can't load the `.wasm` file from a `file:` URL, so pass the
|
|
46
|
+
bytes:
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
import { readFileSync } from "node:fs";
|
|
50
|
+
import { Client } from "letsdecide";
|
|
51
|
+
|
|
52
|
+
const wasm = readFileSync(
|
|
53
|
+
new URL("./pkg/letsdecide_wasm_bg.wasm", import.meta.resolve("letsdecide")),
|
|
54
|
+
);
|
|
55
|
+
const client = new Client({ byProvider: { gemini: { apiKey: "..." } } }, { wasm });
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Errors
|
|
59
|
+
|
|
60
|
+
Failures throw `LetsDecideError` with `code`, `status`, `retryable` and
|
|
61
|
+
`retryAfterMs`. Keys and request bodies are never included.
|
|
62
|
+
|
|
63
|
+
### Retry and fallback
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
import { Client, compose, retry, fallback } from "letsdecide";
|
|
67
|
+
|
|
68
|
+
const client = new Client({
|
|
69
|
+
byProvider: { clef: { apiKey: "...", accountId: "..." }, jev: { apiKey: "..." } },
|
|
70
|
+
});
|
|
71
|
+
const decide = compose(client, fallback(["jev/jev-latest"]), retry());
|
|
72
|
+
const res = await decide("clef/clef-flash", request);
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## More
|
|
76
|
+
|
|
77
|
+
Full documentation, the answer and error reference, and the other bindings
|
|
78
|
+
(Rust, Python): <https://github.com/azoies1/letsdecide>
|
|
79
|
+
|
|
80
|
+
Apache-2.0.
|
package/conformance.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Codec, DecisionRequest, DecisionResponse, Engine, Json } from "./index.js";
|
|
2
|
+
|
|
3
|
+
export interface Fixture {
|
|
4
|
+
name?: string;
|
|
5
|
+
model: string;
|
|
6
|
+
config?: Record<string, Json>;
|
|
7
|
+
request: DecisionRequest;
|
|
8
|
+
/** Codecs: the exact request to build. */
|
|
9
|
+
http?: { url: string; headers: [string, string][] | Record<string, string>; body: Json };
|
|
10
|
+
/** Codecs: the recorded reply. */
|
|
11
|
+
response?: { status: number; headers?: [string, string][]; body: Json };
|
|
12
|
+
expected: { ok: DecisionResponse } | { error: { code: string; retry_after_ms?: number } };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface Report {
|
|
16
|
+
passed: number;
|
|
17
|
+
failed: number;
|
|
18
|
+
results: { name: string; ok: boolean; problems: string[] }[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function checkProvider(impl: Codec | Engine, fixtures: Fixture[], options?: { wasm?: BufferSource | WebAssembly.Module }): Promise<Report>;
|
package/conformance.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Conformance kit: run a custom provider against fixtures in the same format as
|
|
2
|
+
// the core's golden fixtures (`tests/fixtures/**.json`).
|
|
3
|
+
//
|
|
4
|
+
// Fixture: { name?, model, config?, request, http?, response?, expected }
|
|
5
|
+
// - codecs: `http` is the exact request to build ({ url, headers, body }) and
|
|
6
|
+
// `response` the recorded reply ({ status, headers, body }).
|
|
7
|
+
// - engines: no `http` or `response`; `decide` is called directly.
|
|
8
|
+
// - expected: { ok: DecisionResponse } or { error: { code, retry_after_ms? } }.
|
|
9
|
+
|
|
10
|
+
import { check, initialize, LetsDecideError } from "./index.js";
|
|
11
|
+
|
|
12
|
+
// Key order doesn't matter; numbers compare after one trip through the core.
|
|
13
|
+
function canon(v) {
|
|
14
|
+
if (Array.isArray(v)) return v.map(canon);
|
|
15
|
+
if (v && typeof v === "object") {
|
|
16
|
+
return Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon(v[k])]));
|
|
17
|
+
}
|
|
18
|
+
return v;
|
|
19
|
+
}
|
|
20
|
+
const same = (a, b) => JSON.stringify(canon(a)) === JSON.stringify(canon(b));
|
|
21
|
+
const headerMap = (h = []) =>
|
|
22
|
+
Object.fromEntries((Array.isArray(h) ? h : Object.entries(h)).map(([k, v]) => [k.toLowerCase(), v]));
|
|
23
|
+
|
|
24
|
+
function camel(config = {}) {
|
|
25
|
+
return {
|
|
26
|
+
apiKey: config.api_key,
|
|
27
|
+
accessToken: config.access_token,
|
|
28
|
+
baseUrl: config.base_url,
|
|
29
|
+
accountId: config.account_id,
|
|
30
|
+
headers: config.headers ?? [],
|
|
31
|
+
options: config.options ?? {},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Runs `impl` (a codec `{ build, parse }` or an engine `{ decide }`) against `fixtures`.
|
|
37
|
+
* Resolves to `{ passed, failed, results: [{ name, ok, problems }] }`. Never throws for a
|
|
38
|
+
* failing fixture: problems are listed.
|
|
39
|
+
*/
|
|
40
|
+
export async function checkProvider(impl, fixtures, { wasm } = {}) {
|
|
41
|
+
await initialize(wasm);
|
|
42
|
+
const results = [];
|
|
43
|
+
for (const [i, fx] of fixtures.entries()) {
|
|
44
|
+
const name = fx.name ?? `fixture ${i}`;
|
|
45
|
+
const problems = [];
|
|
46
|
+
const model = fx.model.slice(fx.model.indexOf("/") + 1);
|
|
47
|
+
let got;
|
|
48
|
+
try {
|
|
49
|
+
if (typeof impl.decide === "function") {
|
|
50
|
+
got = await impl.decide(model, fx.request, {});
|
|
51
|
+
} else {
|
|
52
|
+
const http = await impl.build(model, fx.request, camel(fx.config));
|
|
53
|
+
if (fx.http) {
|
|
54
|
+
if (http.url !== fx.http.url) problems.push(`url: got ${http.url}, want ${fx.http.url}`);
|
|
55
|
+
if (!same(headerMap(http.headers), headerMap(fx.http.headers))) problems.push("headers differ");
|
|
56
|
+
let body = http.body;
|
|
57
|
+
try {
|
|
58
|
+
body = typeof body === "string" ? JSON.parse(body) : body;
|
|
59
|
+
} catch {
|
|
60
|
+
problems.push("body is not JSON");
|
|
61
|
+
}
|
|
62
|
+
if (!same(body, fx.http.body)) problems.push("body differs");
|
|
63
|
+
}
|
|
64
|
+
const r = fx.response;
|
|
65
|
+
const body = typeof r.body === "string" ? r.body : JSON.stringify(r.body);
|
|
66
|
+
got = await impl.parse(fx.request, { status: r.status, headers: r.headers ?? [], body });
|
|
67
|
+
}
|
|
68
|
+
got = await check(fx.request, got);
|
|
69
|
+
if (fx.expected.error) {
|
|
70
|
+
problems.push(`expected error ${fx.expected.error.code}, got a response`);
|
|
71
|
+
} else if (!same(got, await check(fx.request, fx.expected.ok))) {
|
|
72
|
+
problems.push("response differs from expected");
|
|
73
|
+
}
|
|
74
|
+
} catch (e) {
|
|
75
|
+
const want = fx.expected.error;
|
|
76
|
+
if (!(e instanceof LetsDecideError)) {
|
|
77
|
+
problems.push(`threw ${e?.constructor?.name ?? typeof e} instead of LetsDecideError`);
|
|
78
|
+
} else if (!want) {
|
|
79
|
+
problems.push(`unexpected ${e.code}: ${e.message}`);
|
|
80
|
+
} else {
|
|
81
|
+
if (e.code !== want.code) problems.push(`error code: got ${e.code}, want ${want.code}`);
|
|
82
|
+
if (want.retry_after_ms !== undefined && e.retryAfterMs !== want.retry_after_ms) {
|
|
83
|
+
problems.push(`retryAfterMs: got ${e.retryAfterMs}, want ${want.retry_after_ms}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
results.push({ name, ok: problems.length === 0, problems });
|
|
88
|
+
}
|
|
89
|
+
const passed = results.filter((r) => r.ok).length;
|
|
90
|
+
return { passed, failed: results.length - passed, results };
|
|
91
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
export type Json = string | number | boolean | null | Json[] | { [k: string]: Json };
|
|
2
|
+
|
|
3
|
+
export interface Media {
|
|
4
|
+
/** `image/*`, `audio/*`, `video/*` or a document type; non-images: Gemini only. */
|
|
5
|
+
mime_type: string;
|
|
6
|
+
/** Base64, no `data:` prefix. Give `data` or `uri`, not both. */
|
|
7
|
+
data?: string;
|
|
8
|
+
/** Gemini: `https://` URL or Files API URI (not YouTube or `gs://`). OpenAI: public `http(s)://` image URL. */
|
|
9
|
+
uri?: string;
|
|
10
|
+
/** Gemini only, passed through (`resolution`, `fps`, `page_options`, ...). */
|
|
11
|
+
options?: Record<string, Json>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type Question =
|
|
15
|
+
| {
|
|
16
|
+
kind: "yesno";
|
|
17
|
+
instructions: string;
|
|
18
|
+
/** What yes / no mean. Gemini only. */
|
|
19
|
+
yes_description?: string;
|
|
20
|
+
no_description?: string;
|
|
21
|
+
}
|
|
22
|
+
| { kind: "choice"; instructions: string; options: Record<string, string> }
|
|
23
|
+
| { kind: "score"; instructions: string; levels: { id: string; description: string }[] };
|
|
24
|
+
|
|
25
|
+
export interface DecisionRequest {
|
|
26
|
+
input: Json;
|
|
27
|
+
media?: Media[];
|
|
28
|
+
/** Ids match `[a-z0-9_]{1,64}`; Gemini also allows `[A-Za-z0-9_-]` keys and wider option ids. */
|
|
29
|
+
questions: Record<string, Question>;
|
|
30
|
+
/** Extra top-level body fields, sent as-is. Keys the adapter sets are rejected. */
|
|
31
|
+
provider_extras?: Record<string, Json>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** `provider`: sent by the provider. `probabilities`: not sent, read off the chosen option or top level. */
|
|
35
|
+
export type ConfidenceSource = "provider" | "probabilities";
|
|
36
|
+
|
|
37
|
+
export type Answer =
|
|
38
|
+
| { kind: "yesno"; probability: number }
|
|
39
|
+
| { kind: "choice"; choice: string; confidence: number | null; confidence_source?: ConfidenceSource; probabilities: Record<string, number> }
|
|
40
|
+
| { kind: "score"; value: number; confidence: number | null; confidence_source?: ConfidenceSource; probabilities: Record<string, number> }
|
|
41
|
+
| { kind: "refused" };
|
|
42
|
+
|
|
43
|
+
export interface DecisionResponse {
|
|
44
|
+
model: string | null;
|
|
45
|
+
answers: Record<string, Answer>;
|
|
46
|
+
input_tokens: number | null;
|
|
47
|
+
/** From `spec/prices.json`, when the model's price is known. An estimate. */
|
|
48
|
+
estimated_cost_usd?: number;
|
|
49
|
+
cached_tokens?: number;
|
|
50
|
+
thought_tokens?: number;
|
|
51
|
+
/** Present when every answer is `refused` and the provider gave a reason. */
|
|
52
|
+
block_reason?: string;
|
|
53
|
+
/** Never compare numbers across sources as if on one scale. */
|
|
54
|
+
probability_source: "provider" | "logprob" | "nli";
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
type Lazy<T> = T | (() => T | Promise<T>);
|
|
58
|
+
|
|
59
|
+
/** One provider's settings. A provider only ever sees its own entry. */
|
|
60
|
+
export interface ProviderSettings {
|
|
61
|
+
/** Static key, e.g. `gemini` (sent as `x-goog-api-key`), `jev`, `openai`. */
|
|
62
|
+
apiKey?: Lazy<string>;
|
|
63
|
+
/** OAuth token (e.g. `clef`); wins over `apiKey`. A function is called per request, so you can refresh it. */
|
|
64
|
+
accessToken?: Lazy<string>;
|
|
65
|
+
/** Required for `systemone`; overrides the default endpoint elsewhere. */
|
|
66
|
+
baseUrl?: Lazy<string>;
|
|
67
|
+
/** Required for `clef`. */
|
|
68
|
+
accountId?: Lazy<string>;
|
|
69
|
+
/** Headers for this provider only; win over shared `headers` with the same name. */
|
|
70
|
+
headers?: Lazy<Record<string, string> | [string, string][]>;
|
|
71
|
+
/** Free-form settings for custom providers; built-ins ignore them. */
|
|
72
|
+
options?: Lazy<Record<string, Json>>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Credentials and endpoints are per provider, so a key can never reach another provider.
|
|
77
|
+
* Any other top-level field is an `InvalidRequest` (`invalid_config`).
|
|
78
|
+
*/
|
|
79
|
+
export interface ClientConfig {
|
|
80
|
+
/** Settings per provider prefix, e.g. `{ gemini: { apiKey }, clef: { accessToken, accountId } }`. */
|
|
81
|
+
byProvider?: Record<string, ProviderSettings>;
|
|
82
|
+
/** Sent to every provider (tracing, gateways). Never put secrets here. */
|
|
83
|
+
headers?: Lazy<Record<string, string> | [string, string][]>;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface ClientOptions {
|
|
87
|
+
/** Defaults to `globalThis.fetch`. */
|
|
88
|
+
fetch?: typeof fetch;
|
|
89
|
+
/** WASM bytes or module, where the runtime can't `fetch` a file URL (e.g. Node). */
|
|
90
|
+
wasm?: BufferSource | WebAssembly.Module;
|
|
91
|
+
/** Custom HTTP providers by name. */
|
|
92
|
+
providers?: Record<string, Codec>;
|
|
93
|
+
/** Custom engines by name. */
|
|
94
|
+
engines?: Record<string, Engine>;
|
|
95
|
+
/** Providers described as data, by name. See `docs/dialects.md`. */
|
|
96
|
+
dialects?: Record<string, DialectSpec>;
|
|
97
|
+
/** Built-in names that `providers`, `engines` or `dialects` may override. */
|
|
98
|
+
replace?: string[];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type ErrorCode =
|
|
102
|
+
| "InvalidRequest"
|
|
103
|
+
| "Unsupported"
|
|
104
|
+
| "Auth"
|
|
105
|
+
| "RateLimited"
|
|
106
|
+
| "ProviderUnavailable"
|
|
107
|
+
| "BadResponse"
|
|
108
|
+
| "ProviderError";
|
|
109
|
+
|
|
110
|
+
export type Reason =
|
|
111
|
+
| "too_many_questions" | "too_many_options" | "too_many_levels" | "too_many_media"
|
|
112
|
+
| "media_not_accepted" | "question_kind" | "unknown_provider" | "no_logprobs"
|
|
113
|
+
| "multi_token_label" | "missing_config" | "invalid_config" | "name_taken"
|
|
114
|
+
| "missing_answer" | "unexpected_answer" | "wrong_answer_kind" | "unknown_id"
|
|
115
|
+
| "invalid_number";
|
|
116
|
+
|
|
117
|
+
/** Safe to log by construction: no keys, header values, input or bodies. */
|
|
118
|
+
export interface ErrorDetails {
|
|
119
|
+
reason: Reason;
|
|
120
|
+
provider?: string;
|
|
121
|
+
/** Question id. */
|
|
122
|
+
question?: string;
|
|
123
|
+
/** Option or level id. */
|
|
124
|
+
id?: string;
|
|
125
|
+
limit?: number;
|
|
126
|
+
actual?: number;
|
|
127
|
+
mime_type?: string;
|
|
128
|
+
/** Config field name, never its value. */
|
|
129
|
+
field?: string;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export class LetsDecideError extends Error {
|
|
133
|
+
code: ErrorCode;
|
|
134
|
+
status?: number;
|
|
135
|
+
retryAfterMs?: number;
|
|
136
|
+
retryable: boolean;
|
|
137
|
+
details?: ErrorDetails;
|
|
138
|
+
/** `ProviderError` only: the custom provider's name. */
|
|
139
|
+
provider?: string;
|
|
140
|
+
/** `ProviderError` only: what user code threw. Non-enumerable, so loggers don't print it. */
|
|
141
|
+
original?: unknown;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function initialize(wasm?: BufferSource | WebAssembly.Module): Promise<unknown>;
|
|
145
|
+
|
|
146
|
+
export class Client {
|
|
147
|
+
constructor(config?: ClientConfig, options?: ClientOptions);
|
|
148
|
+
/** `model` is `"provider/model"`, e.g. `"clef/clef-flash"`. */
|
|
149
|
+
decide(model: string, request: DecisionRequest, options?: { signal?: AbortSignal }): Promise<DecisionResponse>;
|
|
150
|
+
/** Capabilities of any `"provider/model"`, built-in or custom. */
|
|
151
|
+
capabilities(model: string): Promise<Capabilities>;
|
|
152
|
+
}
|
|
153
|
+
export * from "./middleware.js";
|
|
154
|
+
|
|
155
|
+
export type Capabilities = {
|
|
156
|
+
max_questions?: number | null;
|
|
157
|
+
max_options?: number | null;
|
|
158
|
+
max_levels?: number | null;
|
|
159
|
+
max_media?: number | null;
|
|
160
|
+
/** Accepted MIME types; `type/*` matches a kind. Empty or missing: no media. */
|
|
161
|
+
media?: string[];
|
|
162
|
+
/** `yesno`, `choice`, `score`. Empty or missing: all. */
|
|
163
|
+
question_kinds?: string[];
|
|
164
|
+
/** Allow Gemini-style ids `[A-Za-z0-9_-]{1,128}`. */
|
|
165
|
+
wide_ids?: boolean;
|
|
166
|
+
/** Yes/no questions may carry `yes_description` / `no_description`. */
|
|
167
|
+
yesno_descriptions?: boolean;
|
|
168
|
+
probabilities?: "provider" | "logprob" | "nli";
|
|
169
|
+
locality?: "cloud" | "network" | "device";
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
/** Config as a custom codec sees it. `accessToken` is already resolved. */
|
|
173
|
+
export interface ProviderConfig {
|
|
174
|
+
apiKey?: string;
|
|
175
|
+
accessToken?: string;
|
|
176
|
+
baseUrl?: string;
|
|
177
|
+
accountId?: string;
|
|
178
|
+
headers: [string, string][];
|
|
179
|
+
options: Record<string, Json>;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export interface HttpRequestOut {
|
|
183
|
+
method?: string;
|
|
184
|
+
url: string;
|
|
185
|
+
headers?: Record<string, string> | [string, string][];
|
|
186
|
+
body?: string;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export interface HttpReply {
|
|
190
|
+
status: number;
|
|
191
|
+
headers: [string, string][];
|
|
192
|
+
body: string;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** A custom HTTP provider. Keep `build` and `parse` pure; the client sends the request. */
|
|
196
|
+
export interface Codec {
|
|
197
|
+
build(model: string, request: DecisionRequest, config: ProviderConfig): HttpRequestOut | Promise<HttpRequestOut>;
|
|
198
|
+
/** Throw `LetsDecideError` (e.g. from `classifyHttp`) for failures. */
|
|
199
|
+
parse(request: DecisionRequest, response: HttpReply): DecisionResponse | Promise<DecisionResponse>;
|
|
200
|
+
/** Checked before `build`. Missing: only the request itself is validated. */
|
|
201
|
+
capabilities?: Capabilities;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** A custom provider that isn't one HTTP round trip: local models, mocks, rules. */
|
|
205
|
+
export interface Engine {
|
|
206
|
+
/** `options.decide` calls any model through the same client (custom or built-in), e.g. a panel's members. */
|
|
207
|
+
decide(
|
|
208
|
+
model: string,
|
|
209
|
+
request: DecisionRequest,
|
|
210
|
+
options: { signal?: AbortSignal; decide: (model: string, request: DecisionRequest, options?: { signal?: AbortSignal }) => Promise<DecisionResponse> },
|
|
211
|
+
): Promise<DecisionResponse>;
|
|
212
|
+
capabilities?: Capabilities;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export const BUILTIN: readonly string[];
|
|
216
|
+
/** How deep engines may call back into the client. */
|
|
217
|
+
export const MAX_DEPTH: number;
|
|
218
|
+
export function validate(request: DecisionRequest, capabilities?: Capabilities | null, options?: { wasm?: BufferSource | WebAssembly.Module }): Promise<void>;
|
|
219
|
+
export function check(request: DecisionRequest, response: unknown, options?: { wasm?: BufferSource | WebAssembly.Module }): Promise<DecisionResponse>;
|
|
220
|
+
export function classifyHttp(response: { status: number; headers?: Record<string, string> | [string, string][]; body?: string }, options?: { wasm?: BufferSource | WebAssembly.Module }): Promise<LetsDecideError>;
|
|
221
|
+
export function capabilities(model: string, options?: { wasm?: BufferSource | WebAssembly.Module }): Promise<Capabilities>;
|
|
222
|
+
export function mockEngine(options?: { answers?: Record<string, Answer>; model?: string; probabilitySource?: "provider" | "logprob" | "nli" }): Engine;
|
|
223
|
+
|
|
224
|
+
/** A provider described as data. `extends` a built-in and set what differs; objects merge, arrays replace. */
|
|
225
|
+
export interface DialectSpec {
|
|
226
|
+
extends: "jev" | "clef" | "gemini" | "openai" | "systemone";
|
|
227
|
+
/** Default endpoint; a provider's `baseUrl` setting overrides it. */
|
|
228
|
+
base_url?: string;
|
|
229
|
+
/** Placeholders: `{model}`, `{account_id}`, `{options.<name>}` (from the provider's `options`). */
|
|
230
|
+
path?: string;
|
|
231
|
+
/** Scheme inferred: `authorization` gets `Bearer <key>`, any other header the raw key. */
|
|
232
|
+
auth?: { header?: string; scheme?: "bearer" | "raw"; required?: boolean };
|
|
233
|
+
/** `state`: JSON input as-is. `input`: JSON input as text (Gemini style). */
|
|
234
|
+
input_field?: "state" | "input";
|
|
235
|
+
media_encoding?: "none" | "jev_assets" | "data_url_list" | "typed_blocks" | "content_parts";
|
|
236
|
+
/** Replies wrapped under this key, e.g. `"result"`. */
|
|
237
|
+
envelope?: string;
|
|
238
|
+
/** HTTP 400 `error.code` values that mean "input blocked": every answer is `refused`. */
|
|
239
|
+
blocked_error_codes?: string[];
|
|
240
|
+
capabilities?: Capabilities;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** A dialect after `extends` is applied, as `dialect()` and `resolveDialect()` return it. */
|
|
244
|
+
export type ResolvedDialect = Omit<DialectSpec, "extends"> & { family: "systemone" | "openai" };
|
|
245
|
+
|
|
246
|
+
export function dialect(name: string, options?: { wasm?: BufferSource | WebAssembly.Module }): Promise<ResolvedDialect>;
|
|
247
|
+
export function resolveDialect(spec: DialectSpec, options?: { wasm?: BufferSource | WebAssembly.Module }): Promise<ResolvedDialect>;
|